diff --git a/src/leetcode/0175.combine-two-tables/.env b/src/leetcode/0175.combine-two-tables/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0175.combine-two-tables/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0175.combine-two-tables/.gitignore b/src/leetcode/0175.combine-two-tables/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0175.combine-two-tables/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0175.combine-two-tables/Cargo.toml b/src/leetcode/0175.combine-two-tables/Cargo.toml deleted file mode 100644 index 21f13b08..00000000 --- a/src/leetcode/0175.combine-two-tables/Cargo.toml +++ /dev/null @@ -1,7 +0,0 @@ -[package] -name = "lc-0175-combine-two-tables" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] diff --git a/src/leetcode/0175.combine-two-tables/diesel.toml b/src/leetcode/0175.combine-two-tables/diesel.toml deleted file mode 100644 index 5f58982a..00000000 --- a/src/leetcode/0175.combine-two-tables/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0175.combine-two-tables/migrations" diff --git a/src/leetcode/0175.combine-two-tables/docker-compose.yml b/src/leetcode/0175.combine-two-tables/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0175.combine-two-tables/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0175.combine-two-tables/index.md b/src/leetcode/0175.combine-two-tables/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0175.combine-two-tables/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0175.combine-two-tables/migrations/.keep b/src/leetcode/0175.combine-two-tables/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0175.combine-two-tables/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0175.combine-two-tables/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0175.combine-two-tables/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0175.combine-two-tables/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0175.combine-two-tables/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0175.combine-two-tables/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0175.combine-two-tables/migrations/2024-05-31-232329_Person/down.sql b/src/leetcode/0175.combine-two-tables/migrations/2024-05-31-232329_Person/down.sql deleted file mode 100644 index 152dfb84..00000000 --- a/src/leetcode/0175.combine-two-tables/migrations/2024-05-31-232329_Person/down.sql +++ /dev/null @@ -1,3 +0,0 @@ --- This file should undo anything in `up.sql` - -DROP TABLE Person; diff --git a/src/leetcode/0175.combine-two-tables/migrations/2024-05-31-232329_Person/up.sql b/src/leetcode/0175.combine-two-tables/migrations/2024-05-31-232329_Person/up.sql deleted file mode 100644 index 9234ab8e..00000000 --- a/src/leetcode/0175.combine-two-tables/migrations/2024-05-31-232329_Person/up.sql +++ /dev/null @@ -1,16 +0,0 @@ --- Your SQL goes here - -CREATE TABLE IF NOT EXISTS Person -( - personId SERIAL PRIMARY KEY, - lastName varChar(32) NOT NULL, - firstName varChar(32) NOT NULL -); - --- Add records - -INSERT INTO Person -(personId, lastName, firstName) -VALUES -(1, 'Wang', 'Allen'), -(2, 'Alice', 'Bob'); diff --git a/src/leetcode/0175.combine-two-tables/migrations/2024-05-31-232339_Address/down.sql b/src/leetcode/0175.combine-two-tables/migrations/2024-05-31-232339_Address/down.sql deleted file mode 100644 index 27df8c70..00000000 --- a/src/leetcode/0175.combine-two-tables/migrations/2024-05-31-232339_Address/down.sql +++ /dev/null @@ -1,3 +0,0 @@ --- This file should undo anything in `up.sql` - -DROP TABLE Address; diff --git a/src/leetcode/0175.combine-two-tables/migrations/2024-05-31-232339_Address/up.sql b/src/leetcode/0175.combine-two-tables/migrations/2024-05-31-232339_Address/up.sql deleted file mode 100644 index e654bd76..00000000 --- a/src/leetcode/0175.combine-two-tables/migrations/2024-05-31-232339_Address/up.sql +++ /dev/null @@ -1,18 +0,0 @@ --- Your SQL goes here - -CREATE TABLE IF NOT EXISTS Address -( - addressId SERIAL PRIMARY KEY, - personId INTEGER NOT NULL, - city varchar(64), - state varchar(64) -); - --- Add records - -INSERT INTO Address -(addressId, personId, city, state) -VALUES -(1, 2, 'New York City', 'New York'), -(2, 3, 'Leetcode', 'California'); - diff --git a/src/leetcode/0175.combine-two-tables/query.sql b/src/leetcode/0175.combine-two-tables/query.sql deleted file mode 100644 index 7021be25..00000000 --- a/src/leetcode/0175.combine-two-tables/query.sql +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - - -SELECT p.firstname, p.lastname, a.city, a.state -FROM person AS p - LEFT JOIN address AS a - ON p.personId = a.personId; \ No newline at end of file diff --git a/src/leetcode/0175.combine-two-tables/src/main.rs b/src/leetcode/0175.combine-two-tables/src/main.rs deleted file mode 100644 index 9edcfeb7..00000000 --- a/src/leetcode/0175.combine-two-tables/src/main.rs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -pub fn solution1() { - todo!(); -} - -pub type SolutionFn = fn(); - -fn check_solution(_func: SolutionFn) { - todo!(); -} - -fn main() { - check_solution(solution1); -} - -#[cfg(test)] -mod tests { - use super::{check_solution, solution1}; - - #[test] - fn test_solution1() { - check_solution(solution1); - } -} diff --git a/src/leetcode/0175.combine-two-tables/src/schema.rs b/src/leetcode/0175.combine-two-tables/src/schema.rs deleted file mode 100644 index f421ec08..00000000 --- a/src/leetcode/0175.combine-two-tables/src/schema.rs +++ /dev/null @@ -1,27 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - address (addressid) { - addressid -> Int4, - personid -> Int4, - #[max_length = 64] - city -> Nullable, - #[max_length = 64] - state -> Nullable, - } -} - -diesel::table! { - person (personid) { - personid -> Int4, - #[max_length = 32] - lastname -> Varchar, - #[max_length = 32] - firstname -> Varchar, - } -} - -diesel::allow_tables_to_appear_in_same_query!( - address, - person, -); diff --git a/src/leetcode/0176.second-highest-salary/.env b/src/leetcode/0176.second-highest-salary/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0176.second-highest-salary/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0176.second-highest-salary/.gitignore b/src/leetcode/0176.second-highest-salary/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0176.second-highest-salary/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0176.second-highest-salary/Cargo.toml b/src/leetcode/0176.second-highest-salary/Cargo.toml deleted file mode 100644 index 6f3acbd1..00000000 --- a/src/leetcode/0176.second-highest-salary/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-0176-second-highest-salary" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/0176.second-highest-salary/diesel.toml b/src/leetcode/0176.second-highest-salary/diesel.toml deleted file mode 100644 index 3b17a1cd..00000000 --- a/src/leetcode/0176.second-highest-salary/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0176.second-highest-salary/migrations" diff --git a/src/leetcode/0176.second-highest-salary/docker-compose.yml b/src/leetcode/0176.second-highest-salary/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0176.second-highest-salary/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0176.second-highest-salary/index.md b/src/leetcode/0176.second-highest-salary/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0176.second-highest-salary/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0176.second-highest-salary/migrations/.keep b/src/leetcode/0176.second-highest-salary/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0176.second-highest-salary/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0176.second-highest-salary/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0176.second-highest-salary/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0176.second-highest-salary/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0176.second-highest-salary/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0176.second-highest-salary/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0176.second-highest-salary/migrations/2024-06-02-010424_employee/down.sql b/src/leetcode/0176.second-highest-salary/migrations/2024-06-02-010424_employee/down.sql deleted file mode 100644 index 03638d0f..00000000 --- a/src/leetcode/0176.second-highest-salary/migrations/2024-06-02-010424_employee/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE employee; diff --git a/src/leetcode/0176.second-highest-salary/migrations/2024-06-02-010424_employee/up.sql b/src/leetcode/0176.second-highest-salary/migrations/2024-06-02-010424_employee/up.sql deleted file mode 100644 index ee8b0ff9..00000000 --- a/src/leetcode/0176.second-highest-salary/migrations/2024-06-02-010424_employee/up.sql +++ /dev/null @@ -1,9 +0,0 @@ - -CREATE TABLE IF NOT EXISTS employee ( - id SERIAL PRIMARY KEY, - salary INTEGER NOT NULL -); - -INSERT INTO employee (id, salary) VALUES ('1', '100'); -INSERT INTO employee (id, salary) VALUES ('2', '200'); -INSERT INTO employee (id, salary) VALUES ('3', '300'); diff --git a/src/leetcode/0176.second-highest-salary/query.sql b/src/leetcode/0176.second-highest-salary/query.sql deleted file mode 100644 index f00be751..00000000 --- a/src/leetcode/0176.second-highest-salary/query.sql +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -EXPLAIN -SELECT CASE WHEN COUNT(salary) > 0 THEN salary END AS SecondHighestSalary -FROM employee -GROUP BY id -ORDER BY salary DESC -LIMIT 1 OFFSET 3; - -EXPLAIN -SELECT (SELECT DISTINCT salary - FROM employee - ORDER BY salary DESC - LIMIT 1 OFFSET 1) - AS SecondHighestSalary; - - -EXPLAIN -SELECT sa AS SecondHighestSalary -FROM (SELECT DISTINCT salary - FROM employee - ORDER BY salary DESC - LIMIT 1 OFFSET 1) - AS sa; - -EXPLAIN -SELECT MAX(salary) AS SecondHighestSalary -FROM employee -WHERE salary < (SELECT MAX(salary) AS salary FROM employee); - - -EXPLAIN -WITH context AS (SELECT DISTINCT salary - FROM employee - ORDER BY salary DESC) -SELECT (SELECT salary - FROM context - LIMIT 1 OFFSET 1) - AS SecondHighestSalary; \ No newline at end of file diff --git a/src/leetcode/0176.second-highest-salary/src/db.rs b/src/leetcode/0176.second-highest-salary/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/0176.second-highest-salary/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/0176.second-highest-salary/src/error.rs b/src/leetcode/0176.second-highest-salary/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/0176.second-highest-salary/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/0176.second-highest-salary/src/main.rs b/src/leetcode/0176.second-highest-salary/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/0176.second-highest-salary/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/0176.second-highest-salary/src/schema.rs b/src/leetcode/0176.second-highest-salary/src/schema.rs deleted file mode 100644 index 618100eb..00000000 --- a/src/leetcode/0176.second-highest-salary/src/schema.rs +++ /dev/null @@ -1,8 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - employee (id) { - id -> Int4, - salary -> Int4, - } -} diff --git a/src/leetcode/0177.nth-highest-salary/.env b/src/leetcode/0177.nth-highest-salary/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0177.nth-highest-salary/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0177.nth-highest-salary/.gitignore b/src/leetcode/0177.nth-highest-salary/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0177.nth-highest-salary/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0177.nth-highest-salary/Cargo.toml b/src/leetcode/0177.nth-highest-salary/Cargo.toml deleted file mode 100644 index 485df585..00000000 --- a/src/leetcode/0177.nth-highest-salary/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-0177-nth-highest-salary" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/0177.nth-highest-salary/diesel.toml b/src/leetcode/0177.nth-highest-salary/diesel.toml deleted file mode 100644 index 12b1984d..00000000 --- a/src/leetcode/0177.nth-highest-salary/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0177.nth-highest-salary/migrations" diff --git a/src/leetcode/0177.nth-highest-salary/docker-compose.yml b/src/leetcode/0177.nth-highest-salary/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0177.nth-highest-salary/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0177.nth-highest-salary/index.md b/src/leetcode/0177.nth-highest-salary/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0177.nth-highest-salary/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0177.nth-highest-salary/migrations/.keep b/src/leetcode/0177.nth-highest-salary/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0177.nth-highest-salary/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0177.nth-highest-salary/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0177.nth-highest-salary/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0177.nth-highest-salary/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0177.nth-highest-salary/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0177.nth-highest-salary/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0177.nth-highest-salary/migrations/2024-06-02-013136_employee/down.sql b/src/leetcode/0177.nth-highest-salary/migrations/2024-06-02-013136_employee/down.sql deleted file mode 100644 index 03638d0f..00000000 --- a/src/leetcode/0177.nth-highest-salary/migrations/2024-06-02-013136_employee/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE employee; diff --git a/src/leetcode/0177.nth-highest-salary/migrations/2024-06-02-013136_employee/up.sql b/src/leetcode/0177.nth-highest-salary/migrations/2024-06-02-013136_employee/up.sql deleted file mode 100644 index 9be70d9e..00000000 --- a/src/leetcode/0177.nth-highest-salary/migrations/2024-06-02-013136_employee/up.sql +++ /dev/null @@ -1,9 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS employee ( - id SERIAL PRIMARY KEY, - salary INTEGER NOT NULL -); - -INSERT INTO Employee (id, salary) VALUES ('1', '100'); -INSERT INTO Employee (id, salary) VALUES ('2', '200'); -INSERT INTO Employee (id, salary) VALUES ('3', '300'); diff --git a/src/leetcode/0177.nth-highest-salary/query.sql b/src/leetcode/0177.nth-highest-salary/query.sql deleted file mode 100644 index 60c67fb0..00000000 --- a/src/leetcode/0177.nth-highest-salary/query.sql +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - - -EXPLAIN -SELECT (SELECT DISTINCT salary - FROM employee - ORDER BY salary DESC - LIMIT 1 OFFSET 1) - AS SecondHighestSalary; - -SELECT NULLIF((SELECT DISTINCT salary - FROM employee - ORDER BY salary DESC - LIMIT 1 OFFSET 3), -1) AS SecondHighestSalary; - -SELECT (SELECT salary - FROM employee - ORDER BY salary DESC - LIMIT 1 OFFSET 1) AS getNthHighestSalary; - -CREATE FUNCTION NthHighestSalary(N IN INTEGER) - RETURNS INTEGER - LANGUAGE plpgsql -AS -$$ -DECLARE - nth_salary INTEGER; - offset_num INTEGER; -BEGIN - --SET offset_num = MAX(N - 1, 0); - SELECT CASE WHEN N > 0 THEN N - 1 ELSE 0 END INTO offset_num; - - SELECT DISTINCT salary - INTO nth_salary - FROM employee - ORDER BY salary DESC - LIMIT 1 OFFSET offset_num; - - RETURN nth_salary; -END; -$$; - -CREATE FUNCTION NthHighestSalary(N IN INTEGER) - RETURNS INTEGER - LANGUAGE plpgsql -AS -$$ -DECLARE - nth_salary INTEGER; - offset_num INTEGER; -BEGIN - --SET offset_num = MAX(N - 1, 0); - SELECT CASE WHEN N > 0 THEN N - 1 ELSE 0 END INTO offset_num; - - SELECT DISTINCT salary - INTO nth_salary - FROM employee - ORDER BY salary DESC - LIMIT 1 OFFSET offset_num; - - RETURN (SELECT CASE WHEN N > 0 THEN nth_salary END); -END; -$$; - -CREATE FUNCTION NthHighestSalary(N IN INTEGER) - RETURNS INTEGER - LANGUAGE plpgsql -AS -$$ -BEGIN - RETURN (SELECT CASE - WHEN N < 1 THEN NULL - WHEN (SELECT DISTINCT COUNT(1) FROM employee) < N THEN NULL - ELSE (SELECT DISTINCT salary - FROM employee - ORDER BY salary DESC - LIMIT 1 OFFSET N - 1) - END); -END; -$$; - -CREATE FUNCTION NthHighestSalary(N IN INTEGER) - RETURNS TABLE - ( - salary INTEGER - ) - LANGUAGE plpgsql -AS -$$ -BEGIN - RETURN QUERY (SELECT CASE - WHEN N < 1 THEN NULL - WHEN (SELECT DISTINCT COUNT(1) FROM employee) < N THEN NULL - ELSE (SELECT DISTINCT salary - FROM employee - ORDER BY salary DESC - LIMIT 1 OFFSET N - 1) - END); -END; -$$; - -DROP FUNCTION NthHighestSalary; - -SELECT NthHighestSalary(3); -SELECT NthHighestSalary(2); -SELECT NthHighestSalary(1); -SELECT NthHighestSalary(0); -SELECT NthHighestSalary(-1); \ No newline at end of file diff --git a/src/leetcode/0177.nth-highest-salary/src/db.rs b/src/leetcode/0177.nth-highest-salary/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/0177.nth-highest-salary/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/0177.nth-highest-salary/src/error.rs b/src/leetcode/0177.nth-highest-salary/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/0177.nth-highest-salary/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/0177.nth-highest-salary/src/main.rs b/src/leetcode/0177.nth-highest-salary/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/0177.nth-highest-salary/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/0177.nth-highest-salary/src/schema.rs b/src/leetcode/0177.nth-highest-salary/src/schema.rs deleted file mode 100644 index 618100eb..00000000 --- a/src/leetcode/0177.nth-highest-salary/src/schema.rs +++ /dev/null @@ -1,8 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - employee (id) { - id -> Int4, - salary -> Int4, - } -} diff --git a/src/leetcode/0181.employees-earning-more-than-their-managers/.env b/src/leetcode/0181.employees-earning-more-than-their-managers/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0181.employees-earning-more-than-their-managers/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0181.employees-earning-more-than-their-managers/.gitignore b/src/leetcode/0181.employees-earning-more-than-their-managers/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0181.employees-earning-more-than-their-managers/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0181.employees-earning-more-than-their-managers/Cargo.toml b/src/leetcode/0181.employees-earning-more-than-their-managers/Cargo.toml deleted file mode 100644 index b4affae2..00000000 --- a/src/leetcode/0181.employees-earning-more-than-their-managers/Cargo.toml +++ /dev/null @@ -1,7 +0,0 @@ -[package] -name = "lc-0181-employees-earning-more-than-their-managers" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] diff --git a/src/leetcode/0181.employees-earning-more-than-their-managers/diesel.toml b/src/leetcode/0181.employees-earning-more-than-their-managers/diesel.toml deleted file mode 100644 index 5112973b..00000000 --- a/src/leetcode/0181.employees-earning-more-than-their-managers/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0181.employees-earning-more-than-their-managers/migrations" diff --git a/src/leetcode/0181.employees-earning-more-than-their-managers/docker-compose.yml b/src/leetcode/0181.employees-earning-more-than-their-managers/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0181.employees-earning-more-than-their-managers/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0181.employees-earning-more-than-their-managers/index.md b/src/leetcode/0181.employees-earning-more-than-their-managers/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0181.employees-earning-more-than-their-managers/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0181.employees-earning-more-than-their-managers/migrations/.keep b/src/leetcode/0181.employees-earning-more-than-their-managers/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0181.employees-earning-more-than-their-managers/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0181.employees-earning-more-than-their-managers/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0181.employees-earning-more-than-their-managers/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0181.employees-earning-more-than-their-managers/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0181.employees-earning-more-than-their-managers/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0181.employees-earning-more-than-their-managers/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0181.employees-earning-more-than-their-managers/migrations/2024-06-01-001635_employee/down.sql b/src/leetcode/0181.employees-earning-more-than-their-managers/migrations/2024-06-01-001635_employee/down.sql deleted file mode 100644 index 40d95dbf..00000000 --- a/src/leetcode/0181.employees-earning-more-than-their-managers/migrations/2024-06-01-001635_employee/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE employee diff --git a/src/leetcode/0181.employees-earning-more-than-their-managers/migrations/2024-06-01-001635_employee/up.sql b/src/leetcode/0181.employees-earning-more-than-their-managers/migrations/2024-06-01-001635_employee/up.sql deleted file mode 100644 index 6f6cde93..00000000 --- a/src/leetcode/0181.employees-earning-more-than-their-managers/migrations/2024-06-01-001635_employee/up.sql +++ /dev/null @@ -1,19 +0,0 @@ --- Your SQL goes here - -CREATE TABLE IF NOT EXISTS employee -( - id SERIAL PRIMARY KEY, - name VARCHAR(32), - salary INTEGER, - managerId INTEGER -); - - --- Add records -INSERT INTO employee -(id, name, salary, managerId) -VALUES -(1, 'Joe', 70000 , 3), -(2, 'Henry', 80000, 4), -(3, 'Sam', 60000, Null), -(4, 'Max', 90000, Null); diff --git a/src/leetcode/0181.employees-earning-more-than-their-managers/query.sql b/src/leetcode/0181.employees-earning-more-than-their-managers/query.sql deleted file mode 100644 index f00e49c3..00000000 --- a/src/leetcode/0181.employees-earning-more-than-their-managers/query.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT name AS Employee -FROM employee AS e1 -WHERE e1.salary > - (SELECT salary - FROM employee AS e2 - WHERE e2.id = e1.managerid); - -EXPLAIN -SELECT name AS Employee -FROM employee AS e1 -WHERE e1.salary > - (SELECT salary - FROM employee AS e2 - WHERE e2.id = e1.managerid); - -SELECT e1.name AS Employee -FROM employee as e1, - employee AS e2 -WHERE e1.salary > e2.salary - AND e1.managerid = e2.id; - -EXPLAIN -SELECT e1.name AS Employee -FROM employee as e1, - employee AS e2 -WHERE e1.salary > e2.salary - AND e1.managerid = e2.id; \ No newline at end of file diff --git a/src/leetcode/0181.employees-earning-more-than-their-managers/src/.env b/src/leetcode/0181.employees-earning-more-than-their-managers/src/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0181.employees-earning-more-than-their-managers/src/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0181.employees-earning-more-than-their-managers/src/.gitignore b/src/leetcode/0181.employees-earning-more-than-their-managers/src/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0181.employees-earning-more-than-their-managers/src/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0181.employees-earning-more-than-their-managers/src/docker-compose.yml b/src/leetcode/0181.employees-earning-more-than-their-managers/src/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0181.employees-earning-more-than-their-managers/src/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0181.employees-earning-more-than-their-managers/src/main.rs b/src/leetcode/0181.employees-earning-more-than-their-managers/src/main.rs deleted file mode 100644 index 9edcfeb7..00000000 --- a/src/leetcode/0181.employees-earning-more-than-their-managers/src/main.rs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -pub fn solution1() { - todo!(); -} - -pub type SolutionFn = fn(); - -fn check_solution(_func: SolutionFn) { - todo!(); -} - -fn main() { - check_solution(solution1); -} - -#[cfg(test)] -mod tests { - use super::{check_solution, solution1}; - - #[test] - fn test_solution1() { - check_solution(solution1); - } -} diff --git a/src/leetcode/0181.employees-earning-more-than-their-managers/src/schema.rs b/src/leetcode/0181.employees-earning-more-than-their-managers/src/schema.rs deleted file mode 100644 index fe673473..00000000 --- a/src/leetcode/0181.employees-earning-more-than-their-managers/src/schema.rs +++ /dev/null @@ -1,11 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - employee (id) { - id -> Int4, - #[max_length = 32] - name -> Nullable, - salary -> Nullable, - managerid -> Nullable, - } -} diff --git a/src/leetcode/0182.duplicate-emails/.env b/src/leetcode/0182.duplicate-emails/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0182.duplicate-emails/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0182.duplicate-emails/.gitignore b/src/leetcode/0182.duplicate-emails/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0182.duplicate-emails/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0182.duplicate-emails/Cargo.toml b/src/leetcode/0182.duplicate-emails/Cargo.toml deleted file mode 100644 index 12294a2c..00000000 --- a/src/leetcode/0182.duplicate-emails/Cargo.toml +++ /dev/null @@ -1,7 +0,0 @@ -[package] -name = "lc-0182-duplicate-emails" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] diff --git a/src/leetcode/0182.duplicate-emails/diesel.toml b/src/leetcode/0182.duplicate-emails/diesel.toml deleted file mode 100644 index 03f66a2c..00000000 --- a/src/leetcode/0182.duplicate-emails/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0182.duplicate-emails/migrations" diff --git a/src/leetcode/0182.duplicate-emails/docker-compose.yml b/src/leetcode/0182.duplicate-emails/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0182.duplicate-emails/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0182.duplicate-emails/index.md b/src/leetcode/0182.duplicate-emails/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0182.duplicate-emails/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0182.duplicate-emails/migrations/.keep b/src/leetcode/0182.duplicate-emails/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0182.duplicate-emails/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0182.duplicate-emails/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0182.duplicate-emails/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0182.duplicate-emails/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0182.duplicate-emails/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0182.duplicate-emails/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0182.duplicate-emails/migrations/2024-06-01-003106_person/down.sql b/src/leetcode/0182.duplicate-emails/migrations/2024-06-01-003106_person/down.sql deleted file mode 100644 index 7c6c694f..00000000 --- a/src/leetcode/0182.duplicate-emails/migrations/2024-06-01-003106_person/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE person; diff --git a/src/leetcode/0182.duplicate-emails/migrations/2024-06-01-003106_person/up.sql b/src/leetcode/0182.duplicate-emails/migrations/2024-06-01-003106_person/up.sql deleted file mode 100644 index cad1827e..00000000 --- a/src/leetcode/0182.duplicate-emails/migrations/2024-06-01-003106_person/up.sql +++ /dev/null @@ -1,14 +0,0 @@ --- Your SQL goes here - -CREATE TABLE IF NOT EXISTS person -( - id SERIAL PRIMARY KEY, - email VARCHAR(255) NOT NULL -); - -INSERT INTO person -(id, email) -VALUES -(1, 'a@b.com'), -(2, 'c@d.com'), -(3, 'a@b.com'); diff --git a/src/leetcode/0182.duplicate-emails/query.sql b/src/leetcode/0182.duplicate-emails/query.sql deleted file mode 100644 index 343f7f27..00000000 --- a/src/leetcode/0182.duplicate-emails/query.sql +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT p.email -FROM (SELECT email, COUNT(email) AS count - FROM person - GROUP BY email) AS p -WHERE p.count > 1; - -EXPLAIN -SELECT p.email -FROM (SELECT email, COUNT(email) AS count - FROM person - GROUP BY email) AS p -WHERE p.count > 1; - -SELECT email -FROM person -GROUP BY email -HAVING count(email) > 1; diff --git a/src/leetcode/0182.duplicate-emails/src/main.rs b/src/leetcode/0182.duplicate-emails/src/main.rs deleted file mode 100644 index 23d089cc..00000000 --- a/src/leetcode/0182.duplicate-emails/src/main.rs +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -fn main() {} diff --git a/src/leetcode/0182.duplicate-emails/src/schema.rs b/src/leetcode/0182.duplicate-emails/src/schema.rs deleted file mode 100644 index acb2e5fd..00000000 --- a/src/leetcode/0182.duplicate-emails/src/schema.rs +++ /dev/null @@ -1,9 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - person (id) { - id -> Int4, - #[max_length = 255] - email -> Varchar, - } -} diff --git a/src/leetcode/0183.customers-who-never-order/.env b/src/leetcode/0183.customers-who-never-order/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0183.customers-who-never-order/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0183.customers-who-never-order/.gitignore b/src/leetcode/0183.customers-who-never-order/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0183.customers-who-never-order/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0183.customers-who-never-order/Cargo.toml b/src/leetcode/0183.customers-who-never-order/Cargo.toml deleted file mode 100644 index 60f21776..00000000 --- a/src/leetcode/0183.customers-who-never-order/Cargo.toml +++ /dev/null @@ -1,7 +0,0 @@ -[package] -name = "lc-0183-customers-who-never-order" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] diff --git a/src/leetcode/0183.customers-who-never-order/diesel.toml b/src/leetcode/0183.customers-who-never-order/diesel.toml deleted file mode 100644 index 83ea311e..00000000 --- a/src/leetcode/0183.customers-who-never-order/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0183.customers-who-never-order/migrations" diff --git a/src/leetcode/0183.customers-who-never-order/docker-compose.yml b/src/leetcode/0183.customers-who-never-order/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0183.customers-who-never-order/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0183.customers-who-never-order/index.md b/src/leetcode/0183.customers-who-never-order/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0183.customers-who-never-order/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0183.customers-who-never-order/migrations/.keep b/src/leetcode/0183.customers-who-never-order/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0183.customers-who-never-order/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0183.customers-who-never-order/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0183.customers-who-never-order/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0183.customers-who-never-order/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0183.customers-who-never-order/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0183.customers-who-never-order/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0183.customers-who-never-order/migrations/2024-06-01-004724_customers/down.sql b/src/leetcode/0183.customers-who-never-order/migrations/2024-06-01-004724_customers/down.sql deleted file mode 100644 index 74250471..00000000 --- a/src/leetcode/0183.customers-who-never-order/migrations/2024-06-01-004724_customers/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE customers; diff --git a/src/leetcode/0183.customers-who-never-order/migrations/2024-06-01-004724_customers/up.sql b/src/leetcode/0183.customers-who-never-order/migrations/2024-06-01-004724_customers/up.sql deleted file mode 100644 index a2f9b607..00000000 --- a/src/leetcode/0183.customers-who-never-order/migrations/2024-06-01-004724_customers/up.sql +++ /dev/null @@ -1,11 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS customers -( - id SERIAL PRIMARY KEY, - name VARCHAR(255) NOT NULL -); - -INSERT INTO customers (id, name) VALUES (1, 'Joe'); -INSERT INTO customers (id, name) VALUES (2, 'Henry'); -INSERT INTO customers (id, name) VALUES (3, 'Sam'); -INSERT INTO customers (id, name) VALUES (4, 'Max'); diff --git a/src/leetcode/0183.customers-who-never-order/migrations/2024-06-01-004925_orders/down.sql b/src/leetcode/0183.customers-who-never-order/migrations/2024-06-01-004925_orders/down.sql deleted file mode 100644 index f07077f2..00000000 --- a/src/leetcode/0183.customers-who-never-order/migrations/2024-06-01-004925_orders/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE orders; diff --git a/src/leetcode/0183.customers-who-never-order/migrations/2024-06-01-004925_orders/up.sql b/src/leetcode/0183.customers-who-never-order/migrations/2024-06-01-004925_orders/up.sql deleted file mode 100644 index 3f98892c..00000000 --- a/src/leetcode/0183.customers-who-never-order/migrations/2024-06-01-004925_orders/up.sql +++ /dev/null @@ -1,9 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS orders -( - id SERIAL PRIMARY KEY, - customerId INTEGER NOT NULL -); - -INSERT INTO orders (id, customerId) VALUES (1, 3); -INSERT INTO orders (id, customerId) VALUES (2, 1); diff --git a/src/leetcode/0183.customers-who-never-order/query.sql b/src/leetcode/0183.customers-who-never-order/query.sql deleted file mode 100644 index 8c41c276..00000000 --- a/src/leetcode/0183.customers-who-never-order/query.sql +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT c.name AS Customers -FROM customers AS c -WHERE c.id NOT IN - (SELECT DISTINCT o.customerid - FROM orders AS o); - -EXPLAIN -SELECT c.name AS Customers -FROM customers AS c -WHERE c.id NOT IN - (SELECT DISTINCT o.customerid - FROM orders AS o); - -EXPLAIN -SELECT c.name AS Customers -FROM customers AS c -WHERE c.id NOT IN - (SELECT o.customerid - FROM orders AS o); \ No newline at end of file diff --git a/src/leetcode/0183.customers-who-never-order/src/main.rs b/src/leetcode/0183.customers-who-never-order/src/main.rs deleted file mode 100644 index 23d089cc..00000000 --- a/src/leetcode/0183.customers-who-never-order/src/main.rs +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -fn main() {} diff --git a/src/leetcode/0183.customers-who-never-order/src/schema.rs b/src/leetcode/0183.customers-who-never-order/src/schema.rs deleted file mode 100644 index eae47ec6..00000000 --- a/src/leetcode/0183.customers-who-never-order/src/schema.rs +++ /dev/null @@ -1,21 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - customers (id) { - id -> Int4, - #[max_length = 255] - name -> Varchar, - } -} - -diesel::table! { - orders (id) { - id -> Int4, - customerid -> Int4, - } -} - -diesel::allow_tables_to_appear_in_same_query!( - customers, - orders, -); diff --git a/src/leetcode/0196.delete-duplicate-emails/.env b/src/leetcode/0196.delete-duplicate-emails/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0196.delete-duplicate-emails/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0196.delete-duplicate-emails/.gitignore b/src/leetcode/0196.delete-duplicate-emails/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0196.delete-duplicate-emails/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0196.delete-duplicate-emails/Cargo.toml b/src/leetcode/0196.delete-duplicate-emails/Cargo.toml deleted file mode 100644 index 46b5ebf3..00000000 --- a/src/leetcode/0196.delete-duplicate-emails/Cargo.toml +++ /dev/null @@ -1,7 +0,0 @@ -[package] -name = "lc-0196-delete-duplicate-emails" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] diff --git a/src/leetcode/0196.delete-duplicate-emails/diesel.toml b/src/leetcode/0196.delete-duplicate-emails/diesel.toml deleted file mode 100644 index ba82bcc1..00000000 --- a/src/leetcode/0196.delete-duplicate-emails/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0196.delete-duplicate-emails/migrations" diff --git a/src/leetcode/0196.delete-duplicate-emails/docker-compose.yml b/src/leetcode/0196.delete-duplicate-emails/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0196.delete-duplicate-emails/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0196.delete-duplicate-emails/index.md b/src/leetcode/0196.delete-duplicate-emails/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0196.delete-duplicate-emails/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0196.delete-duplicate-emails/migrations/.keep b/src/leetcode/0196.delete-duplicate-emails/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0196.delete-duplicate-emails/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0196.delete-duplicate-emails/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0196.delete-duplicate-emails/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0196.delete-duplicate-emails/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0196.delete-duplicate-emails/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0196.delete-duplicate-emails/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0196.delete-duplicate-emails/migrations/2024-06-01-014757_person/down.sql b/src/leetcode/0196.delete-duplicate-emails/migrations/2024-06-01-014757_person/down.sql deleted file mode 100644 index 7c6c694f..00000000 --- a/src/leetcode/0196.delete-duplicate-emails/migrations/2024-06-01-014757_person/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE person; diff --git a/src/leetcode/0196.delete-duplicate-emails/migrations/2024-06-01-014757_person/up.sql b/src/leetcode/0196.delete-duplicate-emails/migrations/2024-06-01-014757_person/up.sql deleted file mode 100644 index 429962e9..00000000 --- a/src/leetcode/0196.delete-duplicate-emails/migrations/2024-06-01-014757_person/up.sql +++ /dev/null @@ -1,11 +0,0 @@ --- Your SQL goes here - -CREATE TABLE IF NOT EXISTS person -( - id SERIAL PRIMARY KEY, - email varchar(255) NOT NULL -); - -INSERT INTO person (id, email) VALUES (1, 'john@example.com'); -INSERT INTO person (id, email) VALUES (2, 'bob@example.com'); -INSERT INTO person (id, email) VALUES (3, 'john@example.com'); diff --git a/src/leetcode/0196.delete-duplicate-emails/query.sql b/src/leetcode/0196.delete-duplicate-emails/query.sql deleted file mode 100644 index 56ac44a9..00000000 --- a/src/leetcode/0196.delete-duplicate-emails/query.sql +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT * -FROM person AS p1, - person AS p2 -WHERE p1.email = p2.email - AND p1.id > p2.id; - -DELETE -FROM person AS p1 USING person AS p2 -WHERE p1.email = p2.email - AND p1.id > p2.id; - - -SELECT p1.id -FROM person AS p1, - person AS p2 -WHERE p1.id > p2.id - AND p1.email = p2.email; - -EXPLAIN -SELECT p1.id -FROM person AS p1, - person AS p2 -WHERE p1.id > p2.id - AND p1.email = p2.email; - -DELETE -from person -WHERE id IN (SELECT p1.id - FROM person AS p1, - person AS p2 - WHERE p1.id > p2.id - AND p1.email = p2.email); - -SELECT min(id) -FROM person -GROUP BY email; - -EXPLAIN -SELECT * -FROM person -WHERE id NOT IN (SELECT min(id) - FROM person - GROUP BY email); - -DELETE -FROm person -WHERE id NOT IN (SELECT min(id) - FROM person - GROUP BY email); \ No newline at end of file diff --git a/src/leetcode/0196.delete-duplicate-emails/src/main.rs b/src/leetcode/0196.delete-duplicate-emails/src/main.rs deleted file mode 100644 index 23d089cc..00000000 --- a/src/leetcode/0196.delete-duplicate-emails/src/main.rs +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -fn main() {} diff --git a/src/leetcode/0196.delete-duplicate-emails/src/schema.rs b/src/leetcode/0196.delete-duplicate-emails/src/schema.rs deleted file mode 100644 index acb2e5fd..00000000 --- a/src/leetcode/0196.delete-duplicate-emails/src/schema.rs +++ /dev/null @@ -1,9 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - person (id) { - id -> Int4, - #[max_length = 255] - email -> Varchar, - } -} diff --git a/src/leetcode/0197.rising-temperature/.env b/src/leetcode/0197.rising-temperature/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0197.rising-temperature/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0197.rising-temperature/.gitignore b/src/leetcode/0197.rising-temperature/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0197.rising-temperature/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0197.rising-temperature/Cargo.toml b/src/leetcode/0197.rising-temperature/Cargo.toml deleted file mode 100644 index f018e6a4..00000000 --- a/src/leetcode/0197.rising-temperature/Cargo.toml +++ /dev/null @@ -1,7 +0,0 @@ -[package] -name = "lc-0197-rising-temperature" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] diff --git a/src/leetcode/0197.rising-temperature/diesel.toml b/src/leetcode/0197.rising-temperature/diesel.toml deleted file mode 100644 index ba0980b8..00000000 --- a/src/leetcode/0197.rising-temperature/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0197.rising-temperature/migrations" diff --git a/src/leetcode/0197.rising-temperature/docker-compose.yml b/src/leetcode/0197.rising-temperature/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0197.rising-temperature/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0197.rising-temperature/index.md b/src/leetcode/0197.rising-temperature/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0197.rising-temperature/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0197.rising-temperature/migrations/.keep b/src/leetcode/0197.rising-temperature/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0197.rising-temperature/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0197.rising-temperature/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0197.rising-temperature/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0197.rising-temperature/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0197.rising-temperature/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0197.rising-temperature/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0197.rising-temperature/migrations/2024-06-01-021022_weather/down.sql b/src/leetcode/0197.rising-temperature/migrations/2024-06-01-021022_weather/down.sql deleted file mode 100644 index ddf73584..00000000 --- a/src/leetcode/0197.rising-temperature/migrations/2024-06-01-021022_weather/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE weather; diff --git a/src/leetcode/0197.rising-temperature/migrations/2024-06-01-021022_weather/up.sql b/src/leetcode/0197.rising-temperature/migrations/2024-06-01-021022_weather/up.sql deleted file mode 100644 index 3304bd22..00000000 --- a/src/leetcode/0197.rising-temperature/migrations/2024-06-01-021022_weather/up.sql +++ /dev/null @@ -1,11 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS weather ( - id SERIAL PRIMARY KEY, - recordDate DATE DEFAULT CURRENT_DATE NOT NULL, - temperature INTEGER NOT NULL -); - -INSERT INTO weather (id, recordDate, temperature) VALUES (1, '2015-01-01', 10); -INSERT INTO weather (id, recordDate, temperature) VALUES (2, '2015-01-02', 25); -INSERT INTO weather (id, recordDate, temperature) VALUES (3, '2015-01-03', 20); -INSERT INTO weather (id, recordDate, temperature) VALUES (4, '2015-01-04', 30); diff --git a/src/leetcode/0197.rising-temperature/query.sql b/src/leetcode/0197.rising-temperature/query.sql deleted file mode 100644 index ff13f1c6..00000000 --- a/src/leetcode/0197.rising-temperature/query.sql +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT w2.id -FROM weather AS w1, - weather AS w2 -WHERE w1.recorddate + 1 = w2.recorddate - AND w1.temperature < w2.temperature; - -EXPLAIN -SELECT w2.id -FROM weather AS w1, - weather AS w2 -WHERE w1.recorddate + 1 = w2.recorddate - AND w1.temperature < w2.temperature; - -SELECT w2.id -FROM weather AS w1 - INNER JOIN - weather AS w2 - ON w1.recorddate + 1 = w2.recorddate - AND w1.temperature < w2.temperature; - -EXPLAIN -SELECT w2.id -FROM weather AS w1 - INNER JOIN - weather AS w2 - ON w1.recorddate + 1 = w2.recorddate - AND w1.temperature < w2.temperature; - -SELECT w1.id -FROM weather AS w1 -WHERE EXISTS(SELECT 1 - FROM weather AS w2 - WHERE w2.recorddate + 1 = w1.recorddate - AND w2.temperature < w1.temperature); - -EXPLAIN -SELECT w1.id -FROM weather AS w1 -WHERE EXISTS(SELECT 1 - FROM weather AS w2 - WHERE w2.recorddate + 1 = w1.recorddate - AND w2.temperature < w1.temperature); - - -EXPLAIN -SELECT w1.id -FROM weather AS w1 -WHERE EXISTS(SELECT 1 - FROM weather AS w2 - WHERE w2.temperature < w1.temperature - AND w2.recorddate + 1 = w1.recorddate); \ No newline at end of file diff --git a/src/leetcode/0197.rising-temperature/src/main.rs b/src/leetcode/0197.rising-temperature/src/main.rs deleted file mode 100644 index 23d089cc..00000000 --- a/src/leetcode/0197.rising-temperature/src/main.rs +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -fn main() {} diff --git a/src/leetcode/0197.rising-temperature/src/schema.rs b/src/leetcode/0197.rising-temperature/src/schema.rs deleted file mode 100644 index 8f7d712e..00000000 --- a/src/leetcode/0197.rising-temperature/src/schema.rs +++ /dev/null @@ -1,9 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - weather (id) { - id -> Int4, - recorddate -> Date, - temperature -> Int4, - } -} diff --git a/src/leetcode/0511.game-play-analysis-i/.env b/src/leetcode/0511.game-play-analysis-i/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0511.game-play-analysis-i/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0511.game-play-analysis-i/.gitignore b/src/leetcode/0511.game-play-analysis-i/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0511.game-play-analysis-i/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0511.game-play-analysis-i/Cargo.toml b/src/leetcode/0511.game-play-analysis-i/Cargo.toml deleted file mode 100644 index 57b6c7b5..00000000 --- a/src/leetcode/0511.game-play-analysis-i/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-0511-game-play-analysis-i" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/0511.game-play-analysis-i/diesel.toml b/src/leetcode/0511.game-play-analysis-i/diesel.toml deleted file mode 100644 index da5ad1ab..00000000 --- a/src/leetcode/0511.game-play-analysis-i/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0511.game-play-analysis-i/migrations" diff --git a/src/leetcode/0511.game-play-analysis-i/docker-compose.yml b/src/leetcode/0511.game-play-analysis-i/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0511.game-play-analysis-i/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0511.game-play-analysis-i/index.md b/src/leetcode/0511.game-play-analysis-i/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0511.game-play-analysis-i/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0511.game-play-analysis-i/migrations/.keep b/src/leetcode/0511.game-play-analysis-i/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0511.game-play-analysis-i/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0511.game-play-analysis-i/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0511.game-play-analysis-i/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0511.game-play-analysis-i/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0511.game-play-analysis-i/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0511.game-play-analysis-i/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0511.game-play-analysis-i/migrations/2024-06-01-053932_activity/down.sql b/src/leetcode/0511.game-play-analysis-i/migrations/2024-06-01-053932_activity/down.sql deleted file mode 100644 index 5be5184d..00000000 --- a/src/leetcode/0511.game-play-analysis-i/migrations/2024-06-01-053932_activity/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE activity; diff --git a/src/leetcode/0511.game-play-analysis-i/migrations/2024-06-01-053932_activity/up.sql b/src/leetcode/0511.game-play-analysis-i/migrations/2024-06-01-053932_activity/up.sql deleted file mode 100644 index 2c1864e0..00000000 --- a/src/leetcode/0511.game-play-analysis-i/migrations/2024-06-01-053932_activity/up.sql +++ /dev/null @@ -1,16 +0,0 @@ --- Your SQL goes here - -CREATE TABLE IF NOT EXISTS activity -( - player_id INTEGER NOT NULL, - device_id INTEGER NOT NULL, - event_date DATE NOT NULL DEFAULT CURRENT_DATE, - games_played INTEGER NOT NULL, - PRIMARY KEY (player_id, event_date) -); - -INSERT INTO activity (player_id, device_id, event_date, games_played) VALUES ('1', '2', '2016-03-01', '5'); -INSERT INTO activity (player_id, device_id, event_date, games_played) VALUES ('1', '2', '2016-05-02', '6'); -INSERT INTO activity (player_id, device_id, event_date, games_played) VALUES ('2', '3', '2017-06-25', '1'); -INSERT INTO activity (player_id, device_id, event_date, games_played) VALUES ('3', '1', '2016-03-02', '0'); -INSERT INTO activity (player_id, device_id, event_date, games_played) VALUES ('3', '4', '2018-07-03', '5'); diff --git a/src/leetcode/0511.game-play-analysis-i/query.sql b/src/leetcode/0511.game-play-analysis-i/query.sql deleted file mode 100644 index 3fe32cd4..00000000 --- a/src/leetcode/0511.game-play-analysis-i/query.sql +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT player_id, MIN(event_date) AS first_login -FROM activity -GROUP BY player_id; \ No newline at end of file diff --git a/src/leetcode/0511.game-play-analysis-i/src/db.rs b/src/leetcode/0511.game-play-analysis-i/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/0511.game-play-analysis-i/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/0511.game-play-analysis-i/src/error.rs b/src/leetcode/0511.game-play-analysis-i/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/0511.game-play-analysis-i/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/0511.game-play-analysis-i/src/main.rs b/src/leetcode/0511.game-play-analysis-i/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/0511.game-play-analysis-i/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/0511.game-play-analysis-i/src/schema.rs b/src/leetcode/0511.game-play-analysis-i/src/schema.rs deleted file mode 100644 index 5dabb71a..00000000 --- a/src/leetcode/0511.game-play-analysis-i/src/schema.rs +++ /dev/null @@ -1,10 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - activity (player_id, event_date) { - player_id -> Int4, - device_id -> Int4, - event_date -> Date, - games_played -> Int4, - } -} diff --git a/src/leetcode/0577.employee-bonus/.env b/src/leetcode/0577.employee-bonus/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0577.employee-bonus/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0577.employee-bonus/.gitignore b/src/leetcode/0577.employee-bonus/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0577.employee-bonus/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0577.employee-bonus/Cargo.toml b/src/leetcode/0577.employee-bonus/Cargo.toml deleted file mode 100644 index dc637600..00000000 --- a/src/leetcode/0577.employee-bonus/Cargo.toml +++ /dev/null @@ -1,7 +0,0 @@ -[package] -name = "lc-0577-employee-bonus" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] diff --git a/src/leetcode/0577.employee-bonus/diesel.toml b/src/leetcode/0577.employee-bonus/diesel.toml deleted file mode 100644 index 911a55ab..00000000 --- a/src/leetcode/0577.employee-bonus/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0577.employee-bonus/migrations" diff --git a/src/leetcode/0577.employee-bonus/docker-compose.yml b/src/leetcode/0577.employee-bonus/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0577.employee-bonus/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0577.employee-bonus/index.md b/src/leetcode/0577.employee-bonus/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0577.employee-bonus/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0577.employee-bonus/migrations/.keep b/src/leetcode/0577.employee-bonus/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0577.employee-bonus/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0577.employee-bonus/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0577.employee-bonus/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0577.employee-bonus/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0577.employee-bonus/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0577.employee-bonus/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0577.employee-bonus/migrations/2024-06-01-000204_employee/down.sql b/src/leetcode/0577.employee-bonus/migrations/2024-06-01-000204_employee/down.sql deleted file mode 100644 index c29fe0bb..00000000 --- a/src/leetcode/0577.employee-bonus/migrations/2024-06-01-000204_employee/down.sql +++ /dev/null @@ -1,3 +0,0 @@ --- This file should undo anything in `up.sql` - -DROP Table empolyee; diff --git a/src/leetcode/0577.employee-bonus/migrations/2024-06-01-000204_employee/up.sql b/src/leetcode/0577.employee-bonus/migrations/2024-06-01-000204_employee/up.sql deleted file mode 100644 index 9c28804c..00000000 --- a/src/leetcode/0577.employee-bonus/migrations/2024-06-01-000204_employee/up.sql +++ /dev/null @@ -1,18 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS employee -( - empId SERIAL PRIMARY KEY, - name VARCHAR(32), - supervisor INTEGER, - salary INTEGER -); - --- Add records - -INSERT INTO employee -(empId, name, supervisor, salary) -VALUES -(3, 'Brad', NULL, 4000), -(1, 'John', 3, 1000), -(2, 'Dan', 3, 2000), -(4, 'Thomas', 3, 4000); diff --git a/src/leetcode/0577.employee-bonus/migrations/2024-06-01-000517_bonus/down.sql b/src/leetcode/0577.employee-bonus/migrations/2024-06-01-000517_bonus/down.sql deleted file mode 100644 index 64b6c6a6..00000000 --- a/src/leetcode/0577.employee-bonus/migrations/2024-06-01-000517_bonus/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE bonus; diff --git a/src/leetcode/0577.employee-bonus/migrations/2024-06-01-000517_bonus/up.sql b/src/leetcode/0577.employee-bonus/migrations/2024-06-01-000517_bonus/up.sql deleted file mode 100644 index 93862109..00000000 --- a/src/leetcode/0577.employee-bonus/migrations/2024-06-01-000517_bonus/up.sql +++ /dev/null @@ -1,14 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS bonus -( - id SERIAL PRIMARY KEY, - empId INTEGER, - bonus INTEGER -); - --- Add records -INSERT INTO bonus -(empId, bonus) -VALUES -(2, 500), -(4, 2000); diff --git a/src/leetcode/0577.employee-bonus/query.sql b/src/leetcode/0577.employee-bonus/query.sql deleted file mode 100644 index 6c6592bc..00000000 --- a/src/leetcode/0577.employee-bonus/query.sql +++ /dev/null @@ -1,5 +0,0 @@ -SELECT e.name, b.bonus -FROM employee AS e - LEFT JOIN bonus AS b on e.empid = b.empid -WHERE b.bonus < 1000 - OR b.bonus IS NULL; \ No newline at end of file diff --git a/src/leetcode/0577.employee-bonus/src/main.rs b/src/leetcode/0577.employee-bonus/src/main.rs deleted file mode 100644 index 9edcfeb7..00000000 --- a/src/leetcode/0577.employee-bonus/src/main.rs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -pub fn solution1() { - todo!(); -} - -pub type SolutionFn = fn(); - -fn check_solution(_func: SolutionFn) { - todo!(); -} - -fn main() { - check_solution(solution1); -} - -#[cfg(test)] -mod tests { - use super::{check_solution, solution1}; - - #[test] - fn test_solution1() { - check_solution(solution1); - } -} diff --git a/src/leetcode/0577.employee-bonus/src/schema.rs b/src/leetcode/0577.employee-bonus/src/schema.rs deleted file mode 100644 index 34abcb81..00000000 --- a/src/leetcode/0577.employee-bonus/src/schema.rs +++ /dev/null @@ -1,24 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - bonus (id) { - id -> Int4, - empid -> Nullable, - bonus -> Nullable, - } -} - -diesel::table! { - employee (empid) { - empid -> Int4, - #[max_length = 32] - name -> Nullable, - supervisor -> Nullable, - salary -> Nullable, - } -} - -diesel::allow_tables_to_appear_in_same_query!( - bonus, - employee, -); diff --git a/src/leetcode/0584.find-customer-referee/.env b/src/leetcode/0584.find-customer-referee/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0584.find-customer-referee/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0584.find-customer-referee/.gitignore b/src/leetcode/0584.find-customer-referee/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0584.find-customer-referee/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0584.find-customer-referee/Cargo.toml b/src/leetcode/0584.find-customer-referee/Cargo.toml deleted file mode 100644 index 838fbb82..00000000 --- a/src/leetcode/0584.find-customer-referee/Cargo.toml +++ /dev/null @@ -1,7 +0,0 @@ -[package] -name = "lc-0584-find-customer-referee" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] diff --git a/src/leetcode/0584.find-customer-referee/diesel.toml b/src/leetcode/0584.find-customer-referee/diesel.toml deleted file mode 100644 index c5b27c3b..00000000 --- a/src/leetcode/0584.find-customer-referee/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0584.find-customer-referee/migrations" diff --git a/src/leetcode/0584.find-customer-referee/docker-compose.yml b/src/leetcode/0584.find-customer-referee/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0584.find-customer-referee/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0584.find-customer-referee/index.md b/src/leetcode/0584.find-customer-referee/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0584.find-customer-referee/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0584.find-customer-referee/migrations/.keep b/src/leetcode/0584.find-customer-referee/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0584.find-customer-referee/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0584.find-customer-referee/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0584.find-customer-referee/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0584.find-customer-referee/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0584.find-customer-referee/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0584.find-customer-referee/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0584.find-customer-referee/migrations/2024-06-01-022757_customer/down.sql b/src/leetcode/0584.find-customer-referee/migrations/2024-06-01-022757_customer/down.sql deleted file mode 100644 index 0b001fb3..00000000 --- a/src/leetcode/0584.find-customer-referee/migrations/2024-06-01-022757_customer/down.sql +++ /dev/null @@ -1,3 +0,0 @@ --- This file should undo anything in `up.sql` - -DROP TABLE customer; diff --git a/src/leetcode/0584.find-customer-referee/migrations/2024-06-01-022757_customer/up.sql b/src/leetcode/0584.find-customer-referee/migrations/2024-06-01-022757_customer/up.sql deleted file mode 100644 index 6f06c220..00000000 --- a/src/leetcode/0584.find-customer-referee/migrations/2024-06-01-022757_customer/up.sql +++ /dev/null @@ -1,14 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS customer -( - id SERIAL PRIMARY KEY, - name VARCHAR(255) NOT NULL, - referee_id INTEGER -); - -insert into customer (id, name, referee_id) VALUES (1, 'Will', NULL); -insert into customer (id, name, referee_id) VALUES (2, 'Jane', NULL); -insert into customer (id, name, referee_id) VALUES (3, 'Alex', 2); -insert into customer (id, name, referee_id) VALUES (4, 'Bill', NULL); -insert into customer (id, name, referee_id) VALUES (5, 'Zack', 1); -insert into customer (id, name, referee_id) VALUES (6, 'Mark', 2); diff --git a/src/leetcode/0584.find-customer-referee/query.sql b/src/leetcode/0584.find-customer-referee/query.sql deleted file mode 100644 index b6ed4a6d..00000000 --- a/src/leetcode/0584.find-customer-referee/query.sql +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT name -FROM customer -WHERE referee_id != 2 - OR referee_id IS NULL; \ No newline at end of file diff --git a/src/leetcode/0584.find-customer-referee/src/main.rs b/src/leetcode/0584.find-customer-referee/src/main.rs deleted file mode 100644 index 23d089cc..00000000 --- a/src/leetcode/0584.find-customer-referee/src/main.rs +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -fn main() {} diff --git a/src/leetcode/0584.find-customer-referee/src/schema.rs b/src/leetcode/0584.find-customer-referee/src/schema.rs deleted file mode 100644 index 30b4ee2a..00000000 --- a/src/leetcode/0584.find-customer-referee/src/schema.rs +++ /dev/null @@ -1,10 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - customer (id) { - id -> Int4, - #[max_length = 255] - name -> Varchar, - referee_id -> Nullable, - } -} diff --git a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/.env b/src/leetcode/0586.customer-placing-the-largest-number-of-orders/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/.gitignore b/src/leetcode/0586.customer-placing-the-largest-number-of-orders/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/Cargo.toml b/src/leetcode/0586.customer-placing-the-largest-number-of-orders/Cargo.toml deleted file mode 100644 index f7c52642..00000000 --- a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/Cargo.toml +++ /dev/null @@ -1,7 +0,0 @@ -[package] -name = "lc-0586-customer-placing-the-largest-number-of-orders" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] diff --git a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/diesel.toml b/src/leetcode/0586.customer-placing-the-largest-number-of-orders/diesel.toml deleted file mode 100644 index 73c5464f..00000000 --- a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0586.customer-placing-the-largest-number-of-orders/migrations" diff --git a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/docker-compose.yml b/src/leetcode/0586.customer-placing-the-largest-number-of-orders/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/index.md b/src/leetcode/0586.customer-placing-the-largest-number-of-orders/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/migrations/.keep b/src/leetcode/0586.customer-placing-the-largest-number-of-orders/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0586.customer-placing-the-largest-number-of-orders/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0586.customer-placing-the-largest-number-of-orders/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/migrations/2024-06-01-024027_orders/down.sql b/src/leetcode/0586.customer-placing-the-largest-number-of-orders/migrations/2024-06-01-024027_orders/down.sql deleted file mode 100644 index f07077f2..00000000 --- a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/migrations/2024-06-01-024027_orders/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE orders; diff --git a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/migrations/2024-06-01-024027_orders/up.sql b/src/leetcode/0586.customer-placing-the-largest-number-of-orders/migrations/2024-06-01-024027_orders/up.sql deleted file mode 100644 index f57b1df8..00000000 --- a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/migrations/2024-06-01-024027_orders/up.sql +++ /dev/null @@ -1,11 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS orders -( - order_number SERIAL PRIMARY KEY, - customer_number INTEGER NOT NULL -); - -INSERT INTO orders (order_number, customer_number) VALUES (1, 1); -INSERT INTO orders (order_number, customer_number) VALUES (2, 2); -INSERT INTO orders (order_number, customer_number) VALUES (3, 3); -INSERT INTO orders (order_number, customer_number) VALUES (4, 3); diff --git a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/query.sql b/src/leetcode/0586.customer-placing-the-largest-number-of-orders/query.sql deleted file mode 100644 index 69d63249..00000000 --- a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/query.sql +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT * -FROM orders; - -SELECT customer_number -FROM orders -GROUP BY customer_number -ORDER BY count(order_number) DESC -LIMIT 1; - -EXPLAIN -SELECT customer_number -FROM orders -GROUP BY customer_number -ORDER BY count(order_number) DESC -LIMIT 1; - -SELECT customer_number, COUNT(order_number) -FROM orders -GROUP BY customer_number; - -SELECT customer_number -FROM orders -GROUP BY customer_number -ORDER BY count(*) DESC -LIMIT 1; diff --git a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/src/main.rs b/src/leetcode/0586.customer-placing-the-largest-number-of-orders/src/main.rs deleted file mode 100644 index 23d089cc..00000000 --- a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/src/main.rs +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -fn main() {} diff --git a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/src/schema.rs b/src/leetcode/0586.customer-placing-the-largest-number-of-orders/src/schema.rs deleted file mode 100644 index b271a886..00000000 --- a/src/leetcode/0586.customer-placing-the-largest-number-of-orders/src/schema.rs +++ /dev/null @@ -1,8 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - orders (order_number) { - order_number -> Int4, - customer_number -> Int4, - } -} diff --git a/src/leetcode/0595.big-countries/.env b/src/leetcode/0595.big-countries/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0595.big-countries/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0595.big-countries/.gitignore b/src/leetcode/0595.big-countries/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0595.big-countries/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0595.big-countries/Cargo.toml b/src/leetcode/0595.big-countries/Cargo.toml deleted file mode 100644 index a4df656b..00000000 --- a/src/leetcode/0595.big-countries/Cargo.toml +++ /dev/null @@ -1,7 +0,0 @@ -[package] -name = "lc-0595-big-countries" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] diff --git a/src/leetcode/0595.big-countries/diesel.toml b/src/leetcode/0595.big-countries/diesel.toml deleted file mode 100644 index ab6c9ca2..00000000 --- a/src/leetcode/0595.big-countries/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0595.big-countries/migrations" diff --git a/src/leetcode/0595.big-countries/docker-compose.yml b/src/leetcode/0595.big-countries/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0595.big-countries/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0595.big-countries/index.md b/src/leetcode/0595.big-countries/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0595.big-countries/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0595.big-countries/migrations/.keep b/src/leetcode/0595.big-countries/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0595.big-countries/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0595.big-countries/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0595.big-countries/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0595.big-countries/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0595.big-countries/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0595.big-countries/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0595.big-countries/migrations/2024-06-01-025908_world/down.sql b/src/leetcode/0595.big-countries/migrations/2024-06-01-025908_world/down.sql deleted file mode 100644 index 7bcb60e1..00000000 --- a/src/leetcode/0595.big-countries/migrations/2024-06-01-025908_world/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE world; diff --git a/src/leetcode/0595.big-countries/migrations/2024-06-01-025908_world/up.sql b/src/leetcode/0595.big-countries/migrations/2024-06-01-025908_world/up.sql deleted file mode 100644 index 1009c90c..00000000 --- a/src/leetcode/0595.big-countries/migrations/2024-06-01-025908_world/up.sql +++ /dev/null @@ -1,16 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS world -( - id SERIAL PRIMARY KEY, - name VARCHAR(255) NOT NULL, - continent VARCHAR(255), - area INTEGER, - population INTEGER, - gdp BIGINT -); - -INSERT INTO world (name, continent, area, population, gdp) VALUES ('Afghanistan', 'Asia', '652230', '25500100', '20343000000'); -INSERT INTO world (name, continent, area, population, gdp) VALUES ('Albania', 'Europe', '28748', '2831741', '12960000000'); -INSERT INTO world (name, continent, area, population, gdp) VALUES ('Algeria', 'Africa', '2381741', '37100000', '188681000000'); -INSERT INTO world (name, continent, area, population, gdp) VALUES ('Andorra', 'Europe', '468', '78115', '3712000000'); -INSERT INTO world (name, continent, area, population, gdp) VALUES ('Angola', 'Africa', '1246700', '20609294', '100990000000'); diff --git a/src/leetcode/0595.big-countries/query.sql b/src/leetcode/0595.big-countries/query.sql deleted file mode 100644 index 241bfa21..00000000 --- a/src/leetcode/0595.big-countries/query.sql +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT * -FROM world; - -SELECT name, population, area -FROM world -WHERE area >= 3000000 - OR population >= 25000000; \ No newline at end of file diff --git a/src/leetcode/0595.big-countries/src/main.rs b/src/leetcode/0595.big-countries/src/main.rs deleted file mode 100644 index 23d089cc..00000000 --- a/src/leetcode/0595.big-countries/src/main.rs +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -fn main() {} diff --git a/src/leetcode/0595.big-countries/src/schema.rs b/src/leetcode/0595.big-countries/src/schema.rs deleted file mode 100644 index c9ab1f47..00000000 --- a/src/leetcode/0595.big-countries/src/schema.rs +++ /dev/null @@ -1,14 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - world (id) { - id -> Int4, - #[max_length = 255] - name -> Varchar, - #[max_length = 255] - continent -> Nullable, - area -> Nullable, - population -> Nullable, - gdp -> Nullable, - } -} diff --git a/src/leetcode/0596.classes-more-than-5-students/.env b/src/leetcode/0596.classes-more-than-5-students/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0596.classes-more-than-5-students/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0596.classes-more-than-5-students/.gitignore b/src/leetcode/0596.classes-more-than-5-students/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0596.classes-more-than-5-students/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0596.classes-more-than-5-students/Cargo.toml b/src/leetcode/0596.classes-more-than-5-students/Cargo.toml deleted file mode 100644 index 35ef2292..00000000 --- a/src/leetcode/0596.classes-more-than-5-students/Cargo.toml +++ /dev/null @@ -1,7 +0,0 @@ -[package] -name = "lc-0596-classes-more-than-5-students" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] diff --git a/src/leetcode/0596.classes-more-than-5-students/diesel.toml b/src/leetcode/0596.classes-more-than-5-students/diesel.toml deleted file mode 100644 index ef98867e..00000000 --- a/src/leetcode/0596.classes-more-than-5-students/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0596.classes-more-than-5-students/migrations" diff --git a/src/leetcode/0596.classes-more-than-5-students/docker-compose.yml b/src/leetcode/0596.classes-more-than-5-students/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0596.classes-more-than-5-students/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0596.classes-more-than-5-students/index.md b/src/leetcode/0596.classes-more-than-5-students/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0596.classes-more-than-5-students/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0596.classes-more-than-5-students/migrations/.keep b/src/leetcode/0596.classes-more-than-5-students/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0596.classes-more-than-5-students/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0596.classes-more-than-5-students/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0596.classes-more-than-5-students/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0596.classes-more-than-5-students/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0596.classes-more-than-5-students/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0596.classes-more-than-5-students/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0596.classes-more-than-5-students/migrations/2024-06-01-030729_courses/down.sql b/src/leetcode/0596.classes-more-than-5-students/migrations/2024-06-01-030729_courses/down.sql deleted file mode 100644 index c9c8ca67..00000000 --- a/src/leetcode/0596.classes-more-than-5-students/migrations/2024-06-01-030729_courses/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE courses; diff --git a/src/leetcode/0596.classes-more-than-5-students/migrations/2024-06-01-030729_courses/up.sql b/src/leetcode/0596.classes-more-than-5-students/migrations/2024-06-01-030729_courses/up.sql deleted file mode 100644 index 33a18ea6..00000000 --- a/src/leetcode/0596.classes-more-than-5-students/migrations/2024-06-01-030729_courses/up.sql +++ /dev/null @@ -1,17 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS courses -( - student VARCHAR(255) NOT NULL, - class VARCHAR(255) NOT NULL, - PRIMARY KEY (student, class) -); - -INSERT INTO courses (student, class) VALUES ('A', 'Math'); -INSERT INTO courses (student, class) VALUES ('B', 'English'); -INSERT INTO courses (student, class) VALUES ('C', 'Math'); -INSERT INTO courses (student, class) VALUES ('D', 'Biology'); -INSERT INTO courses (student, class) VALUES ('E', 'Math'); -INSERT INTO courses (student, class) VALUES ('F', 'Computer'); -INSERT INTO courses (student, class) VALUES ('G', 'Math'); -INSERT INTO courses (student, class) VALUES ('H', 'Math'); -INSERT INTO courses (student, class) VALUES ('I', 'Math'); diff --git a/src/leetcode/0596.classes-more-than-5-students/query.sql b/src/leetcode/0596.classes-more-than-5-students/query.sql deleted file mode 100644 index 6ce80947..00000000 --- a/src/leetcode/0596.classes-more-than-5-students/query.sql +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT class -FROM courses -GROUP BY class -HAVING COUNT(class) >= 5; - -EXPLAIN -SELECT class -FROM courses -GROUP BY class -HAVING COUNT(class) >= 5; - -EXPLAIN -SELECT class -FROM courses -GROUP BY class -HAVING COUNT(*) >= 5; \ No newline at end of file diff --git a/src/leetcode/0596.classes-more-than-5-students/src/main.rs b/src/leetcode/0596.classes-more-than-5-students/src/main.rs deleted file mode 100644 index 23d089cc..00000000 --- a/src/leetcode/0596.classes-more-than-5-students/src/main.rs +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -fn main() {} diff --git a/src/leetcode/0596.classes-more-than-5-students/src/schema.rs b/src/leetcode/0596.classes-more-than-5-students/src/schema.rs deleted file mode 100644 index 73a11fc2..00000000 --- a/src/leetcode/0596.classes-more-than-5-students/src/schema.rs +++ /dev/null @@ -1,10 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - courses (student, class) { - #[max_length = 255] - student -> Varchar, - #[max_length = 255] - class -> Varchar, - } -} diff --git a/src/leetcode/0607.sales-person/.env b/src/leetcode/0607.sales-person/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0607.sales-person/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0607.sales-person/.gitignore b/src/leetcode/0607.sales-person/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0607.sales-person/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0607.sales-person/Cargo.toml b/src/leetcode/0607.sales-person/Cargo.toml deleted file mode 100644 index f2bf379b..00000000 --- a/src/leetcode/0607.sales-person/Cargo.toml +++ /dev/null @@ -1,7 +0,0 @@ -[package] -name = "lc-0607-sales-person" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] diff --git a/src/leetcode/0607.sales-person/diesel.toml b/src/leetcode/0607.sales-person/diesel.toml deleted file mode 100644 index 5255561b..00000000 --- a/src/leetcode/0607.sales-person/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0607.sales-person/migrations" diff --git a/src/leetcode/0607.sales-person/docker-compose.yml b/src/leetcode/0607.sales-person/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0607.sales-person/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0607.sales-person/index.md b/src/leetcode/0607.sales-person/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0607.sales-person/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0607.sales-person/migrations/.keep b/src/leetcode/0607.sales-person/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0607.sales-person/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0607.sales-person/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0607.sales-person/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0607.sales-person/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0607.sales-person/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0607.sales-person/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0607.sales-person/migrations/2024-06-01-032003_SalesPerson/down.sql b/src/leetcode/0607.sales-person/migrations/2024-06-01-032003_SalesPerson/down.sql deleted file mode 100644 index 12e48bbd..00000000 --- a/src/leetcode/0607.sales-person/migrations/2024-06-01-032003_SalesPerson/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE SalesPerson; diff --git a/src/leetcode/0607.sales-person/migrations/2024-06-01-032003_SalesPerson/up.sql b/src/leetcode/0607.sales-person/migrations/2024-06-01-032003_SalesPerson/up.sql deleted file mode 100644 index 6870cd73..00000000 --- a/src/leetcode/0607.sales-person/migrations/2024-06-01-032003_SalesPerson/up.sql +++ /dev/null @@ -1,15 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS SalesPerson -( - sales_id INTEGER PRIMARY KEY, - name VARCHAR(255) NOT NULL, - salary INTEGER NOT NULL, - commission_rate INTEGER, - hire_date DATE -); - -INSERT INTO SalesPerson (sales_id, name, salary, commission_rate, hire_date) VALUES ('1', 'John', '100000', '6', '4/1/2006'); -INSERT INTO SalesPerson (sales_id, name, salary, commission_rate, hire_date) VALUES ('2', 'Amy', '12000', '5', '5/1/2010'); -INSERT INTO SalesPerson (sales_id, name, salary, commission_rate, hire_date) VALUES ('3', 'Mark', '65000', '12', '12/25/2008'); -INSERT INTO SalesPerson (sales_id, name, salary, commission_rate, hire_date) VALUES ('4', 'Pam', '25000', '25', '1/1/2005'); -INSERT INTO SalesPerson (sales_id, name, salary, commission_rate, hire_date) VALUES ('5', 'Alex', '5000', '10', '2/3/2007'); diff --git a/src/leetcode/0607.sales-person/migrations/2024-06-01-032301_Company/down.sql b/src/leetcode/0607.sales-person/migrations/2024-06-01-032301_Company/down.sql deleted file mode 100644 index cdcfb58d..00000000 --- a/src/leetcode/0607.sales-person/migrations/2024-06-01-032301_Company/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE Company; diff --git a/src/leetcode/0607.sales-person/migrations/2024-06-01-032301_Company/up.sql b/src/leetcode/0607.sales-person/migrations/2024-06-01-032301_Company/up.sql deleted file mode 100644 index e96333b3..00000000 --- a/src/leetcode/0607.sales-person/migrations/2024-06-01-032301_Company/up.sql +++ /dev/null @@ -1,12 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS Company -( - com_id INTEGER PRIMARY KEY, - name VARCHAR(255) NOT NULL, - city VARCHAR(255) -); - -INSERT INTO Company (com_id, name, city) VALUES ('1', 'RED', 'Boston'); -INSERT INTO Company (com_id, name, city) VALUES ('2', 'ORANGE', 'New York'); -INSERT INTO Company (com_id, name, city) VALUES ('3', 'YELLOW', 'Boston'); -INSERT INTO Company (com_id, name, city) VALUES ('4', 'GREEN', 'Austin'); diff --git a/src/leetcode/0607.sales-person/migrations/2024-06-01-032426_Orders/down.sql b/src/leetcode/0607.sales-person/migrations/2024-06-01-032426_Orders/down.sql deleted file mode 100644 index 0fdc2c1c..00000000 --- a/src/leetcode/0607.sales-person/migrations/2024-06-01-032426_Orders/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE Orders; diff --git a/src/leetcode/0607.sales-person/migrations/2024-06-01-032426_Orders/up.sql b/src/leetcode/0607.sales-person/migrations/2024-06-01-032426_Orders/up.sql deleted file mode 100644 index 5ca6c93f..00000000 --- a/src/leetcode/0607.sales-person/migrations/2024-06-01-032426_Orders/up.sql +++ /dev/null @@ -1,14 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS Orders -( - order_id INTEGER PRIMARY KEY, - order_date DATE NOT NULL DEFAULT CURRENT_DATE, - com_id INTEGER NOT NULL, - sales_id INTEGER NOT NULL, - amount INTEGER NOT NULL -); - -INSERT INTO Orders (order_id, order_date, com_id, sales_id, amount) VALUES ('1', '1/1/2014', '3', '4', '10000'); -INSERT INTO Orders (order_id, order_date, com_id, sales_id, amount) VALUES ('2', '2/1/2014', '4', '5', '5000'); -INSERT INTO Orders (order_id, order_date, com_id, sales_id, amount) VALUES ('3', '3/1/2014', '1', '1', '50000'); -INSERT INTO Orders (order_id, order_date, com_id, sales_id, amount) VALUES ('4', '4/1/2014', '1', '4', '25000'); diff --git a/src/leetcode/0607.sales-person/query.sql b/src/leetcode/0607.sales-person/query.sql deleted file mode 100644 index ac753a7d..00000000 --- a/src/leetcode/0607.sales-person/query.sql +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT name -FROM salesperson; - -SELECT name -FROM salesperson -WHERE sales_id NOT IN - (SELECT orders.sales_id - FROM orders - INNER JOIN company - ON company.com_id = orders.com_id - WHERE company.name = 'RED'); - - -EXPLAIN -SELECT name -FROM salesperson -WHERE sales_id NOT IN - (SELECT orders.sales_id - FROM orders - LEFT JOIN company - ON company.com_id = orders.com_id - WHERE company.name = 'RED'); \ No newline at end of file diff --git a/src/leetcode/0607.sales-person/src/main.rs b/src/leetcode/0607.sales-person/src/main.rs deleted file mode 100644 index 23d089cc..00000000 --- a/src/leetcode/0607.sales-person/src/main.rs +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -fn main() {} diff --git a/src/leetcode/0607.sales-person/src/schema.rs b/src/leetcode/0607.sales-person/src/schema.rs deleted file mode 100644 index e304a635..00000000 --- a/src/leetcode/0607.sales-person/src/schema.rs +++ /dev/null @@ -1,38 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - company (com_id) { - com_id -> Int4, - #[max_length = 255] - name -> Varchar, - #[max_length = 255] - city -> Nullable, - } -} - -diesel::table! { - orders (order_id) { - order_id -> Int4, - order_date -> Date, - com_id -> Int4, - sales_id -> Int4, - amount -> Int4, - } -} - -diesel::table! { - salesperson (sales_id) { - sales_id -> Int4, - #[max_length = 255] - name -> Varchar, - salary -> Int4, - commission_rate -> Nullable, - hire_date -> Nullable, - } -} - -diesel::allow_tables_to_appear_in_same_query!( - company, - orders, - salesperson, -); diff --git a/src/leetcode/0610.triangle-judgement/.env b/src/leetcode/0610.triangle-judgement/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0610.triangle-judgement/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0610.triangle-judgement/.gitignore b/src/leetcode/0610.triangle-judgement/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0610.triangle-judgement/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0610.triangle-judgement/Cargo.toml b/src/leetcode/0610.triangle-judgement/Cargo.toml deleted file mode 100644 index 5e9420ba..00000000 --- a/src/leetcode/0610.triangle-judgement/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-0610-triangle-judgement" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/0610.triangle-judgement/diesel.toml b/src/leetcode/0610.triangle-judgement/diesel.toml deleted file mode 100644 index c460f792..00000000 --- a/src/leetcode/0610.triangle-judgement/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0610.triangle-judgement/migrations" diff --git a/src/leetcode/0610.triangle-judgement/docker-compose.yml b/src/leetcode/0610.triangle-judgement/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0610.triangle-judgement/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0610.triangle-judgement/index.md b/src/leetcode/0610.triangle-judgement/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0610.triangle-judgement/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0610.triangle-judgement/migrations/.keep b/src/leetcode/0610.triangle-judgement/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0610.triangle-judgement/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0610.triangle-judgement/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0610.triangle-judgement/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0610.triangle-judgement/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0610.triangle-judgement/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0610.triangle-judgement/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0610.triangle-judgement/migrations/2024-06-01-075436_triangle/down.sql b/src/leetcode/0610.triangle-judgement/migrations/2024-06-01-075436_triangle/down.sql deleted file mode 100644 index 50a9007b..00000000 --- a/src/leetcode/0610.triangle-judgement/migrations/2024-06-01-075436_triangle/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE triangle; diff --git a/src/leetcode/0610.triangle-judgement/migrations/2024-06-01-075436_triangle/up.sql b/src/leetcode/0610.triangle-judgement/migrations/2024-06-01-075436_triangle/up.sql deleted file mode 100644 index 8fc9165c..00000000 --- a/src/leetcode/0610.triangle-judgement/migrations/2024-06-01-075436_triangle/up.sql +++ /dev/null @@ -1,11 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS triangle -( - x INTEGER NOT NULL, - y INTEGER NOT NULL, - z INTEGER NOT NULL, - PRIMARY KEY (x, y, z) -); - -INSERT INTO triangle (x, y, z) VALUES ('13', '15', '30'); -INSERT INTO triangle (x, y, z) VALUES ('10', '20', '15'); diff --git a/src/leetcode/0610.triangle-judgement/query.sql b/src/leetcode/0610.triangle-judgement/query.sql deleted file mode 100644 index ce26d132..00000000 --- a/src/leetcode/0610.triangle-judgement/query.sql +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT *, - CASE - WHEN x + y > z AND x + z > y AND y + z > x THEN 'Yes' - ELSE 'No' - END AS triangle -FROM triangle; \ No newline at end of file diff --git a/src/leetcode/0610.triangle-judgement/src/db.rs b/src/leetcode/0610.triangle-judgement/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/0610.triangle-judgement/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/0610.triangle-judgement/src/error.rs b/src/leetcode/0610.triangle-judgement/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/0610.triangle-judgement/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/0610.triangle-judgement/src/main.rs b/src/leetcode/0610.triangle-judgement/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/0610.triangle-judgement/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/0610.triangle-judgement/src/schema.rs b/src/leetcode/0610.triangle-judgement/src/schema.rs deleted file mode 100644 index 00eac9ac..00000000 --- a/src/leetcode/0610.triangle-judgement/src/schema.rs +++ /dev/null @@ -1,9 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - triangle (x, y, z) { - x -> Int4, - y -> Int4, - z -> Int4, - } -} diff --git a/src/leetcode/0619.biggest-single-number/.env b/src/leetcode/0619.biggest-single-number/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0619.biggest-single-number/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0619.biggest-single-number/.gitignore b/src/leetcode/0619.biggest-single-number/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0619.biggest-single-number/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0619.biggest-single-number/Cargo.toml b/src/leetcode/0619.biggest-single-number/Cargo.toml deleted file mode 100644 index f81c4956..00000000 --- a/src/leetcode/0619.biggest-single-number/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-0619-biggest-single-number" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/0619.biggest-single-number/diesel.toml b/src/leetcode/0619.biggest-single-number/diesel.toml deleted file mode 100644 index 443729ee..00000000 --- a/src/leetcode/0619.biggest-single-number/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0619.biggest-single-number/migrations" diff --git a/src/leetcode/0619.biggest-single-number/docker-compose.yml b/src/leetcode/0619.biggest-single-number/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0619.biggest-single-number/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0619.biggest-single-number/index.md b/src/leetcode/0619.biggest-single-number/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0619.biggest-single-number/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0619.biggest-single-number/migrations/.keep b/src/leetcode/0619.biggest-single-number/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0619.biggest-single-number/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0619.biggest-single-number/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0619.biggest-single-number/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0619.biggest-single-number/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0619.biggest-single-number/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0619.biggest-single-number/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0619.biggest-single-number/migrations/2024-06-01-080841_MyNumbers/down.sql b/src/leetcode/0619.biggest-single-number/migrations/2024-06-01-080841_MyNumbers/down.sql deleted file mode 100644 index b0688017..00000000 --- a/src/leetcode/0619.biggest-single-number/migrations/2024-06-01-080841_MyNumbers/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE MyNumbers; diff --git a/src/leetcode/0619.biggest-single-number/migrations/2024-06-01-080841_MyNumbers/up.sql b/src/leetcode/0619.biggest-single-number/migrations/2024-06-01-080841_MyNumbers/up.sql deleted file mode 100644 index e4f13b30..00000000 --- a/src/leetcode/0619.biggest-single-number/migrations/2024-06-01-080841_MyNumbers/up.sql +++ /dev/null @@ -1,15 +0,0 @@ --- Your SQL goes here -CREATE TABLE MyNumbers -( - id SERIAL PRIMARY KEY, - num INTEGER NOT NULL -); - -INSERT INTO MyNumbers (num) VALUES ('8'); -INSERT INTO MyNumbers (num) VALUES ('8'); -INSERT INTO MyNumbers (num) VALUES ('3'); -INSERT INTO MyNumbers (num) VALUES ('3'); -INSERT INTO MyNumbers (num) VALUES ('1'); -INSERT INTO MyNumbers (num) VALUES ('4'); -INSERT INTO MyNumbers (num) VALUES ('5'); -INSERT INTO MyNumbers (num) VALUES ('6'); diff --git a/src/leetcode/0619.biggest-single-number/query.sql b/src/leetcode/0619.biggest-single-number/query.sql deleted file mode 100644 index ac4e28ae..00000000 --- a/src/leetcode/0619.biggest-single-number/query.sql +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - - -SELECT num -FROM mynumbers -GROUP BY num -HAVING COUNT(num) = 1 -ORDER BY num DESC -LIMIT 1; - -EXPLAIN -SELECT num -FROM mynumbers -GROUP BY num -HAVING COUNT(num) = 1 -ORDER BY num DESC -LIMIT 1; - - -SELECT MAX(num) AS num -FROM (SELECT num - FROM mynumbers - GROUP BY num - HAVING COUNT(num) = 1) as mn; - -EXPLAIN -SELECT MAX(num) AS num -FROM (SELECT num - FROM mynumbers - GROUP BY num - HAVING COUNT(num) = 1) as mn; - -WITH mn AS (SELECT num - FROM mynumbers - GROUP BY num - HAVING COUNT(num) = 1) -SELECT MAX(num) AS num -FROM mn; - -EXPLAIN -WITH mn AS (SELECT num - FROM mynumbers - GROUP BY num - HAVING COUNT(num) = 1) -SELECT MAX(num) AS num -FROM mn; \ No newline at end of file diff --git a/src/leetcode/0619.biggest-single-number/src/db.rs b/src/leetcode/0619.biggest-single-number/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/0619.biggest-single-number/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/0619.biggest-single-number/src/error.rs b/src/leetcode/0619.biggest-single-number/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/0619.biggest-single-number/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/0619.biggest-single-number/src/main.rs b/src/leetcode/0619.biggest-single-number/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/0619.biggest-single-number/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/0619.biggest-single-number/src/schema.rs b/src/leetcode/0619.biggest-single-number/src/schema.rs deleted file mode 100644 index e673fb71..00000000 --- a/src/leetcode/0619.biggest-single-number/src/schema.rs +++ /dev/null @@ -1,8 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - mynumbers (id) { - id -> Int4, - num -> Int4, - } -} diff --git a/src/leetcode/0620.not-boring-movies/.env b/src/leetcode/0620.not-boring-movies/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0620.not-boring-movies/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0620.not-boring-movies/.gitignore b/src/leetcode/0620.not-boring-movies/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0620.not-boring-movies/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0620.not-boring-movies/Cargo.toml b/src/leetcode/0620.not-boring-movies/Cargo.toml deleted file mode 100644 index b6a194bb..00000000 --- a/src/leetcode/0620.not-boring-movies/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-0620-not-boring-movies" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/0620.not-boring-movies/diesel.toml b/src/leetcode/0620.not-boring-movies/diesel.toml deleted file mode 100644 index 3c71cb43..00000000 --- a/src/leetcode/0620.not-boring-movies/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0620.not-boring-movies/migrations" diff --git a/src/leetcode/0620.not-boring-movies/docker-compose.yml b/src/leetcode/0620.not-boring-movies/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0620.not-boring-movies/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0620.not-boring-movies/index.md b/src/leetcode/0620.not-boring-movies/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0620.not-boring-movies/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0620.not-boring-movies/migrations/.keep b/src/leetcode/0620.not-boring-movies/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0620.not-boring-movies/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0620.not-boring-movies/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0620.not-boring-movies/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0620.not-boring-movies/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0620.not-boring-movies/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0620.not-boring-movies/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0620.not-boring-movies/migrations/2024-06-01-082927_cinema/down.sql b/src/leetcode/0620.not-boring-movies/migrations/2024-06-01-082927_cinema/down.sql deleted file mode 100644 index 6527ef61..00000000 --- a/src/leetcode/0620.not-boring-movies/migrations/2024-06-01-082927_cinema/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE cinema; diff --git a/src/leetcode/0620.not-boring-movies/migrations/2024-06-01-082927_cinema/up.sql b/src/leetcode/0620.not-boring-movies/migrations/2024-06-01-082927_cinema/up.sql deleted file mode 100644 index 9c19bf85..00000000 --- a/src/leetcode/0620.not-boring-movies/migrations/2024-06-01-082927_cinema/up.sql +++ /dev/null @@ -1,14 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS cinema -( - id SERIAL PRIMARY KEY, - movie VARCHAR(255), - description VARCHAR(255), - rating NUMERIC(2, 1) -); - -INSERT INTO cinema (id, movie, description, rating) VALUES ('1', 'War', 'great 3D', '8.9'); -INSERT INTO cinema (id, movie, description, rating) VALUES ('2', 'Science', 'fiction', '8.5'); -INSERT INTO cinema (id, movie, description, rating) VALUES ('3', 'irish', 'boring', '6.2'); -INSERT INTO cinema (id, movie, description, rating) VALUES ('4', 'Ice song', 'Fantacy', '8.6'); -INSERT INTO cinema (id, movie, description, rating) VALUES ('5', 'House card', 'Interesting', '9.1'); diff --git a/src/leetcode/0620.not-boring-movies/query.sql b/src/leetcode/0620.not-boring-movies/query.sql deleted file mode 100644 index 67ce9f09..00000000 --- a/src/leetcode/0620.not-boring-movies/query.sql +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT * -FROM cinema -WHERE description != 'boring' - AND id % 2 = 1 -ORDER BY rating DESC; \ No newline at end of file diff --git a/src/leetcode/0620.not-boring-movies/src/db.rs b/src/leetcode/0620.not-boring-movies/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/0620.not-boring-movies/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/0620.not-boring-movies/src/error.rs b/src/leetcode/0620.not-boring-movies/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/0620.not-boring-movies/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/0620.not-boring-movies/src/main.rs b/src/leetcode/0620.not-boring-movies/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/0620.not-boring-movies/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/0620.not-boring-movies/src/schema.rs b/src/leetcode/0620.not-boring-movies/src/schema.rs deleted file mode 100644 index 2c9e5c86..00000000 --- a/src/leetcode/0620.not-boring-movies/src/schema.rs +++ /dev/null @@ -1,12 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - cinema (id) { - id -> Int4, - #[max_length = 255] - movie -> Nullable, - #[max_length = 255] - description -> Nullable, - rating -> Nullable, - } -} diff --git a/src/leetcode/0627.swap-salary/.env b/src/leetcode/0627.swap-salary/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/0627.swap-salary/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/0627.swap-salary/.gitignore b/src/leetcode/0627.swap-salary/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/0627.swap-salary/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/0627.swap-salary/Cargo.toml b/src/leetcode/0627.swap-salary/Cargo.toml deleted file mode 100644 index 4590fa73..00000000 --- a/src/leetcode/0627.swap-salary/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-0627-swap-salary" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/0627.swap-salary/diesel.toml b/src/leetcode/0627.swap-salary/diesel.toml deleted file mode 100644 index e4b9cebb..00000000 --- a/src/leetcode/0627.swap-salary/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/0627.swap-salary/migrations" diff --git a/src/leetcode/0627.swap-salary/docker-compose.yml b/src/leetcode/0627.swap-salary/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/0627.swap-salary/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/0627.swap-salary/index.md b/src/leetcode/0627.swap-salary/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/0627.swap-salary/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/0627.swap-salary/migrations/.keep b/src/leetcode/0627.swap-salary/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/0627.swap-salary/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/0627.swap-salary/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/0627.swap-salary/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/0627.swap-salary/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/0627.swap-salary/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/0627.swap-salary/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/0627.swap-salary/migrations/2024-06-01-084711_salary/down.sql b/src/leetcode/0627.swap-salary/migrations/2024-06-01-084711_salary/down.sql deleted file mode 100644 index 8e01bafa..00000000 --- a/src/leetcode/0627.swap-salary/migrations/2024-06-01-084711_salary/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE salary; diff --git a/src/leetcode/0627.swap-salary/migrations/2024-06-01-084711_salary/up.sql b/src/leetcode/0627.swap-salary/migrations/2024-06-01-084711_salary/up.sql deleted file mode 100644 index 06880818..00000000 --- a/src/leetcode/0627.swap-salary/migrations/2024-06-01-084711_salary/up.sql +++ /dev/null @@ -1,13 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS salary -( - id SERIAL PRIMARY KEY, - name VARCHAR(100) NOT NULL, - sex char(1) NOT NULL, - salary INTEGER NOT NULL -); - -INSERT INTO salary (id, name, sex, salary) VALUES ('1', 'A', 'm', '2500'); -INSERT INTO salary (id, name, sex, salary) VALUES ('2', 'B', 'f', '1500'); -INSERT INTO salary (id, name, sex, salary) VALUES ('3', 'C', 'm', '5500'); -INSERT INTO salary (id, name, sex, salary) VALUES ('4', 'D', 'f', '500'); diff --git a/src/leetcode/0627.swap-salary/query.sql b/src/leetcode/0627.swap-salary/query.sql deleted file mode 100644 index 0457da74..00000000 --- a/src/leetcode/0627.swap-salary/query.sql +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT * -FROM salary; - -UPDATE salary -SET sex = - CASE - WHEN sex = 'm' THEN 'f' - ELSE 'm' - END; diff --git a/src/leetcode/0627.swap-salary/src/db.rs b/src/leetcode/0627.swap-salary/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/0627.swap-salary/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/0627.swap-salary/src/error.rs b/src/leetcode/0627.swap-salary/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/0627.swap-salary/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/0627.swap-salary/src/main.rs b/src/leetcode/0627.swap-salary/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/0627.swap-salary/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/0627.swap-salary/src/schema.rs b/src/leetcode/0627.swap-salary/src/schema.rs deleted file mode 100644 index bf6f6005..00000000 --- a/src/leetcode/0627.swap-salary/src/schema.rs +++ /dev/null @@ -1,12 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - salary (id) { - id -> Int4, - #[max_length = 100] - name -> Varchar, - #[max_length = 1] - sex -> Bpchar, - salary -> Int4, - } -} diff --git a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/.env b/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/.gitignore b/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/Cargo.toml b/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/Cargo.toml deleted file mode 100644 index 430f659f..00000000 --- a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-1050-actors-and-directors-who-cooperated-at-least-three-times" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/diesel.toml b/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/diesel.toml deleted file mode 100644 index 60c7a387..00000000 --- a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/migrations" diff --git a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/docker-compose.yml b/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/index.md b/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/migrations/.keep b/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/migrations/2024-06-01-095059_ActorDirector/down.sql b/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/migrations/2024-06-01-095059_ActorDirector/down.sql deleted file mode 100644 index bfcbfda5..00000000 --- a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/migrations/2024-06-01-095059_ActorDirector/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE ActorDirector; diff --git a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/migrations/2024-06-01-095059_ActorDirector/up.sql b/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/migrations/2024-06-01-095059_ActorDirector/up.sql deleted file mode 100644 index 8e11c824..00000000 --- a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/migrations/2024-06-01-095059_ActorDirector/up.sql +++ /dev/null @@ -1,15 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS ActorDirector -( - actor_id INTEGER NOT NULL, - director_id INTEGER NOT NULL, - timestamp INTEGER PRIMARY KEY -); - -INSERT INTO ActorDirector (actor_id, director_id, timestamp) VALUES ('1', '1', '0'); -INSERT INTO ActorDirector (actor_id, director_id, timestamp) VALUES ('1', '1', '1'); -INSERT INTO ActorDirector (actor_id, director_id, timestamp) VALUES ('1', '1', '2'); -INSERT INTO ActorDirector (actor_id, director_id, timestamp) VALUES ('1', '2', '3'); -INSERT INTO ActorDirector (actor_id, director_id, timestamp) VALUES ('1', '2', '4'); -INSERT INTO ActorDirector (actor_id, director_id, timestamp) VALUES ('2', '1', '5'); -INSERT INTO ActorDirector (actor_id, director_id, timestamp) VALUES ('2', '1', '6'); diff --git a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/query.sql b/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/query.sql deleted file mode 100644 index 124a546d..00000000 --- a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/query.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT actor_id, director_id -FROM actordirector -GROUP BY (actor_id, director_id) -HAVING count(1) >= 3; - -EXPLAIN -SELECT actor_id, director_id -FROM actordirector -GROUP BY (actor_id, director_id) -HAVING count(1) >= 3; \ No newline at end of file diff --git a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/src/db.rs b/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/src/error.rs b/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/src/main.rs b/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/src/schema.rs b/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/src/schema.rs deleted file mode 100644 index 26a0a5e9..00000000 --- a/src/leetcode/1050.actors-and-directors-who-cooperated-at-least-three-times/src/schema.rs +++ /dev/null @@ -1,9 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - actordirector (timestamp) { - actor_id -> Int4, - director_id -> Int4, - timestamp -> Int4, - } -} diff --git a/src/leetcode/1068.product-sales-analysis-i/.env b/src/leetcode/1068.product-sales-analysis-i/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/1068.product-sales-analysis-i/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/1068.product-sales-analysis-i/.gitignore b/src/leetcode/1068.product-sales-analysis-i/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/1068.product-sales-analysis-i/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/1068.product-sales-analysis-i/Cargo.toml b/src/leetcode/1068.product-sales-analysis-i/Cargo.toml deleted file mode 100644 index d5f87f91..00000000 --- a/src/leetcode/1068.product-sales-analysis-i/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-1068-product-sales-analysis-i" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/1068.product-sales-analysis-i/diesel.toml b/src/leetcode/1068.product-sales-analysis-i/diesel.toml deleted file mode 100644 index bbcc39c3..00000000 --- a/src/leetcode/1068.product-sales-analysis-i/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/1068.product-sales-analysis-i/migrations" diff --git a/src/leetcode/1068.product-sales-analysis-i/docker-compose.yml b/src/leetcode/1068.product-sales-analysis-i/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/1068.product-sales-analysis-i/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/1068.product-sales-analysis-i/index.md b/src/leetcode/1068.product-sales-analysis-i/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/1068.product-sales-analysis-i/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/1068.product-sales-analysis-i/migrations/.keep b/src/leetcode/1068.product-sales-analysis-i/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/1068.product-sales-analysis-i/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/1068.product-sales-analysis-i/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/1068.product-sales-analysis-i/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/1068.product-sales-analysis-i/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/1068.product-sales-analysis-i/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/1068.product-sales-analysis-i/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/1068.product-sales-analysis-i/migrations/2024-06-01-224957_sales/down.sql b/src/leetcode/1068.product-sales-analysis-i/migrations/2024-06-01-224957_sales/down.sql deleted file mode 100644 index 9d665a3a..00000000 --- a/src/leetcode/1068.product-sales-analysis-i/migrations/2024-06-01-224957_sales/down.sql +++ /dev/null @@ -1,2 +0,0 @@ - -DROP TABLE sales; diff --git a/src/leetcode/1068.product-sales-analysis-i/migrations/2024-06-01-224957_sales/up.sql b/src/leetcode/1068.product-sales-analysis-i/migrations/2024-06-01-224957_sales/up.sql deleted file mode 100644 index 056cd787..00000000 --- a/src/leetcode/1068.product-sales-analysis-i/migrations/2024-06-01-224957_sales/up.sql +++ /dev/null @@ -1,13 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS sales ( - sale_id INTEGER NOT NULL, - product_id INTEGER NOT NULL, - year INTEGER NOT NULL, - quantity INTEGER NOT NULL, - price INTEGER NOT NULL, - PRIMARY KEY(sale_id, year) -); - -INSERT INTO sales (sale_id, product_id, year, quantity, price) VALUES ('1', '100', '2008', '10', '5000'); -INSERT INTO sales (sale_id, product_id, year, quantity, price) VALUES ('2', '100', '2009', '12', '5000'); -INSERT INTO sales (sale_id, product_id, year, quantity, price) VALUES ('7', '200', '2011', '15', '9000'); diff --git a/src/leetcode/1068.product-sales-analysis-i/migrations/2024-06-01-225341_product/down.sql b/src/leetcode/1068.product-sales-analysis-i/migrations/2024-06-01-225341_product/down.sql deleted file mode 100644 index e852b209..00000000 --- a/src/leetcode/1068.product-sales-analysis-i/migrations/2024-06-01-225341_product/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE product; diff --git a/src/leetcode/1068.product-sales-analysis-i/migrations/2024-06-01-225341_product/up.sql b/src/leetcode/1068.product-sales-analysis-i/migrations/2024-06-01-225341_product/up.sql deleted file mode 100644 index c62a1009..00000000 --- a/src/leetcode/1068.product-sales-analysis-i/migrations/2024-06-01-225341_product/up.sql +++ /dev/null @@ -1,9 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS product ( - product_id SERIAL PRIMARY KEY, - product_name VARCHAR(10) -); - -INSERT INTO product (product_id, product_name) VALUES ('100', 'Nokia'); -INSERT INTO product (product_id, product_name) VALUES ('200', 'Apple'); -INSERT INTO product (product_id, product_name) VALUES ('300', 'Samsung'); diff --git a/src/leetcode/1068.product-sales-analysis-i/query.sql b/src/leetcode/1068.product-sales-analysis-i/query.sql deleted file mode 100644 index 0a9a8b19..00000000 --- a/src/leetcode/1068.product-sales-analysis-i/query.sql +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT product.product_name, sales.year, sales.price -FROM sales - INNER JOIN product - ON sales.product_id = product.product_id; \ No newline at end of file diff --git a/src/leetcode/1068.product-sales-analysis-i/src/db.rs b/src/leetcode/1068.product-sales-analysis-i/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/1068.product-sales-analysis-i/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/1068.product-sales-analysis-i/src/error.rs b/src/leetcode/1068.product-sales-analysis-i/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/1068.product-sales-analysis-i/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/1068.product-sales-analysis-i/src/main.rs b/src/leetcode/1068.product-sales-analysis-i/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/1068.product-sales-analysis-i/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/1068.product-sales-analysis-i/src/schema.rs b/src/leetcode/1068.product-sales-analysis-i/src/schema.rs deleted file mode 100644 index fbab20b2..00000000 --- a/src/leetcode/1068.product-sales-analysis-i/src/schema.rs +++ /dev/null @@ -1,24 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - product (product_id) { - product_id -> Int4, - #[max_length = 10] - product_name -> Nullable, - } -} - -diesel::table! { - sales (sale_id, year) { - sale_id -> Int4, - product_id -> Int4, - year -> Int4, - quantity -> Int4, - price -> Int4, - } -} - -diesel::allow_tables_to_appear_in_same_query!( - product, - sales, -); diff --git a/src/leetcode/1075.project-employees-i/.env b/src/leetcode/1075.project-employees-i/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/1075.project-employees-i/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/1075.project-employees-i/.gitignore b/src/leetcode/1075.project-employees-i/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/1075.project-employees-i/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/1075.project-employees-i/Cargo.toml b/src/leetcode/1075.project-employees-i/Cargo.toml deleted file mode 100644 index d361948b..00000000 --- a/src/leetcode/1075.project-employees-i/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-1075-project-employees-i" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/1075.project-employees-i/diesel.toml b/src/leetcode/1075.project-employees-i/diesel.toml deleted file mode 100644 index 5997bcf6..00000000 --- a/src/leetcode/1075.project-employees-i/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/1075.project-employees-i/migrations" diff --git a/src/leetcode/1075.project-employees-i/docker-compose.yml b/src/leetcode/1075.project-employees-i/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/1075.project-employees-i/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/1075.project-employees-i/index.md b/src/leetcode/1075.project-employees-i/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/1075.project-employees-i/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/1075.project-employees-i/migrations/.keep b/src/leetcode/1075.project-employees-i/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/1075.project-employees-i/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/1075.project-employees-i/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/1075.project-employees-i/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/1075.project-employees-i/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/1075.project-employees-i/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/1075.project-employees-i/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/1075.project-employees-i/migrations/2024-06-01-230515_product/down.sql b/src/leetcode/1075.project-employees-i/migrations/2024-06-01-230515_product/down.sql deleted file mode 100644 index e852b209..00000000 --- a/src/leetcode/1075.project-employees-i/migrations/2024-06-01-230515_product/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE product; diff --git a/src/leetcode/1075.project-employees-i/migrations/2024-06-01-230515_product/up.sql b/src/leetcode/1075.project-employees-i/migrations/2024-06-01-230515_product/up.sql deleted file mode 100644 index 6625d3be..00000000 --- a/src/leetcode/1075.project-employees-i/migrations/2024-06-01-230515_product/up.sql +++ /dev/null @@ -1,12 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS project ( - project_id INTEGER NOT NULL, - employee_id INTEGER NOT NULL, - PRIMARY KEY (project_id, employee_id) -); - -INSERT INTO project (project_id, employee_id) VALUES ('1', '1'); -INSERT INTO project (project_id, employee_id) VALUES ('1', '2'); -INSERT INTO project (project_id, employee_id) VALUES ('1', '3'); -INSERT INTO project (project_id, employee_id) VALUES ('2', '1'); -INSERT INTO project (project_id, employee_id) VALUES ('2', '4'); diff --git a/src/leetcode/1075.project-employees-i/migrations/2024-06-01-230705_employee/down.sql b/src/leetcode/1075.project-employees-i/migrations/2024-06-01-230705_employee/down.sql deleted file mode 100644 index 03638d0f..00000000 --- a/src/leetcode/1075.project-employees-i/migrations/2024-06-01-230705_employee/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE employee; diff --git a/src/leetcode/1075.project-employees-i/migrations/2024-06-01-230705_employee/up.sql b/src/leetcode/1075.project-employees-i/migrations/2024-06-01-230705_employee/up.sql deleted file mode 100644 index 77ba113a..00000000 --- a/src/leetcode/1075.project-employees-i/migrations/2024-06-01-230705_employee/up.sql +++ /dev/null @@ -1,12 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS employee -( - employee_id SERIAL PRIMARY KEY, - name VARCHAR(10), - experience_years INTEGER NOT NULL -); - -INSERT INTO employee (employee_id, name, experience_years) VALUES ('1', 'Khaled', '3'); -INSERT INTO employee (employee_id, name, experience_years) VALUES ('2', 'Ali', '2'); -INSERT INTO employee (employee_id, name, experience_years) VALUES ('3', 'John', '1'); -INSERT INTO employee (employee_id, name, experience_years) VALUES ('4', 'Doe', '2'); diff --git a/src/leetcode/1075.project-employees-i/query.sql b/src/leetcode/1075.project-employees-i/query.sql deleted file mode 100644 index 7f339c40..00000000 --- a/src/leetcode/1075.project-employees-i/query.sql +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT p.project_id -FROM project AS p - LEFT JOIN employee AS e - ON p.employee_id = e.employee_id; - -SELECT p.project_id, AVG(experience_years) -FROM employee AS e - LEFT JOIN public.project AS p - ON e.employee_id = p.employee_id -GROUP BY p.project_id; - -SELECT p.project_id, AVG(experience_years)::NUMERIC(10, 2) AS average_years -FROM project AS p - LEFT JOIN employee AS e - ON e.employee_id = p.employee_id -GROUP BY p.project_id; - - -SELECT p.project_id, ROUND(AVG(experience_years)::NUMERIC, 2) AS average_years -FROM project AS p - LEFT JOIN employee AS e - ON e.employee_id = p.employee_id -GROUP BY p.project_id; \ No newline at end of file diff --git a/src/leetcode/1075.project-employees-i/src/db.rs b/src/leetcode/1075.project-employees-i/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/1075.project-employees-i/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/1075.project-employees-i/src/error.rs b/src/leetcode/1075.project-employees-i/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/1075.project-employees-i/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/1075.project-employees-i/src/main.rs b/src/leetcode/1075.project-employees-i/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/1075.project-employees-i/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/1075.project-employees-i/src/schema.rs b/src/leetcode/1075.project-employees-i/src/schema.rs deleted file mode 100644 index 3c385dc8..00000000 --- a/src/leetcode/1075.project-employees-i/src/schema.rs +++ /dev/null @@ -1,22 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - employee (employee_id) { - employee_id -> Int4, - #[max_length = 10] - name -> Nullable, - experience_years -> Int4, - } -} - -diesel::table! { - project (project_id, employee_id) { - project_id -> Int4, - employee_id -> Int4, - } -} - -diesel::allow_tables_to_appear_in_same_query!( - employee, - project, -); diff --git a/src/leetcode/1084.sales-analysis-iii/.env b/src/leetcode/1084.sales-analysis-iii/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/1084.sales-analysis-iii/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/1084.sales-analysis-iii/.gitignore b/src/leetcode/1084.sales-analysis-iii/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/1084.sales-analysis-iii/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/1084.sales-analysis-iii/Cargo.toml b/src/leetcode/1084.sales-analysis-iii/Cargo.toml deleted file mode 100644 index 13b708e5..00000000 --- a/src/leetcode/1084.sales-analysis-iii/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-1084-sales-analysis-iii" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/1084.sales-analysis-iii/diesel.toml b/src/leetcode/1084.sales-analysis-iii/diesel.toml deleted file mode 100644 index 123de709..00000000 --- a/src/leetcode/1084.sales-analysis-iii/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/1084.sales-analysis-iii/migrations" diff --git a/src/leetcode/1084.sales-analysis-iii/docker-compose.yml b/src/leetcode/1084.sales-analysis-iii/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/1084.sales-analysis-iii/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/1084.sales-analysis-iii/index.md b/src/leetcode/1084.sales-analysis-iii/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/1084.sales-analysis-iii/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/1084.sales-analysis-iii/migrations/.keep b/src/leetcode/1084.sales-analysis-iii/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/1084.sales-analysis-iii/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/1084.sales-analysis-iii/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/1084.sales-analysis-iii/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/1084.sales-analysis-iii/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/1084.sales-analysis-iii/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/1084.sales-analysis-iii/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/1084.sales-analysis-iii/migrations/2024-06-01-232356_product/down.sql b/src/leetcode/1084.sales-analysis-iii/migrations/2024-06-01-232356_product/down.sql deleted file mode 100644 index e852b209..00000000 --- a/src/leetcode/1084.sales-analysis-iii/migrations/2024-06-01-232356_product/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE product; diff --git a/src/leetcode/1084.sales-analysis-iii/migrations/2024-06-01-232356_product/up.sql b/src/leetcode/1084.sales-analysis-iii/migrations/2024-06-01-232356_product/up.sql deleted file mode 100644 index 0b7679c3..00000000 --- a/src/leetcode/1084.sales-analysis-iii/migrations/2024-06-01-232356_product/up.sql +++ /dev/null @@ -1,11 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS product -( - product_id SERIAL PRIMARY KEY, - product_name VARCHAR(10) NOT NULL, - unit_price INTEGER NOT NULL -); - -INSERT INTO product (product_id, product_name, unit_price) VALUES ('1', 'S8', '1000'); -INSERT INTO product (product_id, product_name, unit_price) VALUES ('2', 'G4', '800'); -INSERT INTO product (product_id, product_name, unit_price) VALUES ('3', 'iPhone', '1400'); diff --git a/src/leetcode/1084.sales-analysis-iii/migrations/2024-06-01-232515_sales/down.sql b/src/leetcode/1084.sales-analysis-iii/migrations/2024-06-01-232515_sales/down.sql deleted file mode 100644 index b890b1aa..00000000 --- a/src/leetcode/1084.sales-analysis-iii/migrations/2024-06-01-232515_sales/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE sales; diff --git a/src/leetcode/1084.sales-analysis-iii/migrations/2024-06-01-232515_sales/up.sql b/src/leetcode/1084.sales-analysis-iii/migrations/2024-06-01-232515_sales/up.sql deleted file mode 100644 index eb9e2982..00000000 --- a/src/leetcode/1084.sales-analysis-iii/migrations/2024-06-01-232515_sales/up.sql +++ /dev/null @@ -1,16 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS sales -( - id SERIAL PRIMARY KEY, - seller_id INTEGER NOT NULL, - product_id INTEGER NOT NULL, - buyer_id INTEGER NOT NULL, - sale_date DATE NOT NULL DEFAULT CURRENT_DATE, - quantity INTEGER NOT NULL, - price INTEGER NOT NULL -); - -INSERT INTO sales (seller_id, product_id, buyer_id, sale_date, quantity, price) VALUES ('1', '1', '1', '2019-01-21', '2', '2000'); -INSERT INTO sales (seller_id, product_id, buyer_id, sale_date, quantity, price) VALUES ('1', '2', '2', '2019-02-17', '1', '800'); -INSERT INTO sales (seller_id, product_id, buyer_id, sale_date, quantity, price) VALUES ('2', '2', '3', '2019-06-02', '1', '800'); -INSERT INTO sales (seller_id, product_id, buyer_id, sale_date, quantity, price) VALUES ('3', '3', '4', '2019-05-13', '2', '2800'); diff --git a/src/leetcode/1084.sales-analysis-iii/query.sql b/src/leetcode/1084.sales-analysis-iii/query.sql deleted file mode 100644 index c1926bfa..00000000 --- a/src/leetcode/1084.sales-analysis-iii/query.sql +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -SELECT p.product_id, p.product_name -FROM sales AS s - LEFT JOIN product AS p - ON p.product_id = s.product_id -WHERE date_ge(s.sale_date, '2019-01-01') - AND date_le(s.sale_date, '2019-03-31'); - - -SELECT p.product_id, p.product_name -FROM sales AS s - LEFT JOIN product AS p - ON p.product_id = s.product_id -GROUP BY p.product_id -HAVING MIN(s.sale_date) >= CAST('2019-01-01' AS DATE) - AND MAX(s.sale_date) <= CAST('2019-03-31' AS DATE); - - -SELECT p.product_id, p.product_name -FROM sales AS s - INNER JOIN product AS p - ON p.product_id = s.product_id -GROUP BY p.product_id, p.product_name -HAVING MIN(s.sale_date) >= '2019-01-01' - AND MAX(s.sale_date) <= '2019-03-31'; - - -EXPLAIN -SELECT p.product_id, p.product_name -FROM product AS p - INNER JOIN sales AS s - ON p.product_id = s.product_id -GROUP BY p.product_id, p.product_name -HAVING MIN(s.sale_date) >= '2019-01-01' - AND MAX(s.sale_date) <= '2019-03-31'; - - -EXPLAIN -SELECT product_id, product_name -FROM product -WHERE product_id IN - (SELECT s.product_id - FROM sales AS s - GROUP BY s.product_id - HAVING MIN(s.sale_date) >= '2019-01-01' - AND MAX(s.sale_date) <= '2019-03-31') -; diff --git a/src/leetcode/1084.sales-analysis-iii/src/db.rs b/src/leetcode/1084.sales-analysis-iii/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/1084.sales-analysis-iii/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/1084.sales-analysis-iii/src/error.rs b/src/leetcode/1084.sales-analysis-iii/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/1084.sales-analysis-iii/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/1084.sales-analysis-iii/src/main.rs b/src/leetcode/1084.sales-analysis-iii/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/1084.sales-analysis-iii/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/1084.sales-analysis-iii/src/schema.rs b/src/leetcode/1084.sales-analysis-iii/src/schema.rs deleted file mode 100644 index 400f95fd..00000000 --- a/src/leetcode/1084.sales-analysis-iii/src/schema.rs +++ /dev/null @@ -1,27 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - product (product_id) { - product_id -> Int4, - #[max_length = 10] - product_name -> Varchar, - unit_price -> Int4, - } -} - -diesel::table! { - sales (id) { - id -> Int4, - seller_id -> Int4, - product_id -> Int4, - buyer_id -> Int4, - sale_date -> Date, - quantity -> Int4, - price -> Int4, - } -} - -diesel::allow_tables_to_appear_in_same_query!( - product, - sales, -); diff --git a/src/leetcode/1141.user-activity-for-the-past-30-days-i/.env b/src/leetcode/1141.user-activity-for-the-past-30-days-i/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/1141.user-activity-for-the-past-30-days-i/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/1141.user-activity-for-the-past-30-days-i/.gitignore b/src/leetcode/1141.user-activity-for-the-past-30-days-i/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/1141.user-activity-for-the-past-30-days-i/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/1141.user-activity-for-the-past-30-days-i/Cargo.toml b/src/leetcode/1141.user-activity-for-the-past-30-days-i/Cargo.toml deleted file mode 100644 index 23e2032d..00000000 --- a/src/leetcode/1141.user-activity-for-the-past-30-days-i/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-1141-user-activity-for-the-past-30-days-i" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/1141.user-activity-for-the-past-30-days-i/diesel.toml b/src/leetcode/1141.user-activity-for-the-past-30-days-i/diesel.toml deleted file mode 100644 index 95078736..00000000 --- a/src/leetcode/1141.user-activity-for-the-past-30-days-i/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/1141.user-activity-for-the-past-30-days-i/migrations" diff --git a/src/leetcode/1141.user-activity-for-the-past-30-days-i/docker-compose.yml b/src/leetcode/1141.user-activity-for-the-past-30-days-i/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/1141.user-activity-for-the-past-30-days-i/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/1141.user-activity-for-the-past-30-days-i/index.md b/src/leetcode/1141.user-activity-for-the-past-30-days-i/index.md deleted file mode 100644 index 845f8988..00000000 --- a/src/leetcode/1141.user-activity-for-the-past-30-days-i/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](https://leetcode.com/problems/) diff --git a/src/leetcode/1141.user-activity-for-the-past-30-days-i/migrations/.keep b/src/leetcode/1141.user-activity-for-the-past-30-days-i/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/1141.user-activity-for-the-past-30-days-i/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/1141.user-activity-for-the-past-30-days-i/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/1141.user-activity-for-the-past-30-days-i/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/1141.user-activity-for-the-past-30-days-i/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/1141.user-activity-for-the-past-30-days-i/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/1141.user-activity-for-the-past-30-days-i/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/1141.user-activity-for-the-past-30-days-i/migrations/2024-08-01-080910_activity/down.sql b/src/leetcode/1141.user-activity-for-the-past-30-days-i/migrations/2024-08-01-080910_activity/down.sql deleted file mode 100644 index 5be5184d..00000000 --- a/src/leetcode/1141.user-activity-for-the-past-30-days-i/migrations/2024-08-01-080910_activity/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE activity; diff --git a/src/leetcode/1141.user-activity-for-the-past-30-days-i/migrations/2024-08-01-080910_activity/up.sql b/src/leetcode/1141.user-activity-for-the-past-30-days-i/migrations/2024-08-01-080910_activity/up.sql deleted file mode 100644 index a071ad93..00000000 --- a/src/leetcode/1141.user-activity-for-the-past-30-days-i/migrations/2024-08-01-080910_activity/up.sql +++ /dev/null @@ -1,22 +0,0 @@ --- Your SQL goes here -CREATE TYPE ACTIVITY_TYPES AS ENUM('open_session', 'end_session', 'scroll_down', 'send_message'); - -CREATE TABLE IF NOT EXISTS activity ( - id SERIAL PRIMARY KEY, - user_id int NOT NULL, - session_id int NOT NULL, - activity_date date NOT NULL, - activity_type ACTIVITY_TYPES -); - -INSERT INTO Activity (user_id, session_id, activity_date, activity_type) VALUES ('1', '1', '2019-07-20', 'open_session'); -INSERT INTO Activity (user_id, session_id, activity_date, activity_type) VALUES ('1', '1', '2019-07-20', 'scroll_down'); -INSERT INTO Activity (user_id, session_id, activity_date, activity_type) VALUES ('1', '1', '2019-07-20', 'end_session'); -INSERT INTO Activity (user_id, session_id, activity_date, activity_type) VALUES ('2', '4', '2019-07-20', 'open_session'); -INSERT INTO Activity (user_id, session_id, activity_date, activity_type) VALUES ('2', '4', '2019-07-21', 'send_message'); -INSERT INTO Activity (user_id, session_id, activity_date, activity_type) VALUES ('2', '4', '2019-07-21', 'end_session'); -INSERT INTO Activity (user_id, session_id, activity_date, activity_type) VALUES ('3', '2', '2019-07-21', 'open_session'); -INSERT INTO Activity (user_id, session_id, activity_date, activity_type) VALUES ('3', '2', '2019-07-21', 'send_message'); -INSERT INTO Activity (user_id, session_id, activity_date, activity_type) VALUES ('3', '2', '2019-07-21', 'end_session'); -INSERT INTO Activity (user_id, session_id, activity_date, activity_type) VALUES ('4', '3', '2019-06-25', 'open_session'); -INSERT INTO Activity (user_id, session_id, activity_date, activity_type) VALUES ('4', '3', '2019-06-25', 'end_session'); diff --git a/src/leetcode/1141.user-activity-for-the-past-30-days-i/query.sql b/src/leetcode/1141.user-activity-for-the-past-30-days-i/query.sql deleted file mode 100644 index df712066..00000000 --- a/src/leetcode/1141.user-activity-for-the-past-30-days-i/query.sql +++ /dev/null @@ -1,6 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - diff --git a/src/leetcode/1141.user-activity-for-the-past-30-days-i/solution.sql b/src/leetcode/1141.user-activity-for-the-past-30-days-i/solution.sql deleted file mode 100644 index 1c4a0ca3..00000000 --- a/src/leetcode/1141.user-activity-for-the-past-30-days-i/solution.sql +++ /dev/null @@ -1,6 +0,0 @@ - -SELECT activity_date AS day, COUNT(DISTINCT user_id) AS active_users -FROM activity -WHERE activity_date > '2019-06-27' AND activity_date <= '2019-07-27' -GROUP BY activity_date; - diff --git a/src/leetcode/1141.user-activity-for-the-past-30-days-i/src/db.rs b/src/leetcode/1141.user-activity-for-the-past-30-days-i/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/1141.user-activity-for-the-past-30-days-i/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/1141.user-activity-for-the-past-30-days-i/src/error.rs b/src/leetcode/1141.user-activity-for-the-past-30-days-i/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/1141.user-activity-for-the-past-30-days-i/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/1141.user-activity-for-the-past-30-days-i/src/main.rs b/src/leetcode/1141.user-activity-for-the-past-30-days-i/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/1141.user-activity-for-the-past-30-days-i/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/1141.user-activity-for-the-past-30-days-i/src/schema.rs b/src/leetcode/1141.user-activity-for-the-past-30-days-i/src/schema.rs deleted file mode 100644 index f6e81273..00000000 --- a/src/leetcode/1141.user-activity-for-the-past-30-days-i/src/schema.rs +++ /dev/null @@ -1,20 +0,0 @@ -// @generated automatically by Diesel CLI. - -pub mod sql_types { - #[derive(diesel::query_builder::QueryId, Clone, diesel::sql_types::SqlType)] - #[diesel(postgres_type(name = "activity_types"))] - pub struct ActivityTypes; -} - -diesel::table! { - use diesel::sql_types::*; - use super::sql_types::ActivityTypes; - - activity (id) { - id -> Int4, - user_id -> Int4, - session_id -> Int4, - activity_date -> Date, - activity_type -> Nullable, - } -} diff --git a/src/leetcode/1148.article-views-i/.env b/src/leetcode/1148.article-views-i/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/1148.article-views-i/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/1148.article-views-i/.gitignore b/src/leetcode/1148.article-views-i/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/1148.article-views-i/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/1148.article-views-i/Cargo.toml b/src/leetcode/1148.article-views-i/Cargo.toml deleted file mode 100644 index 03129dbc..00000000 --- a/src/leetcode/1148.article-views-i/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-1148-article-views-i" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/1148.article-views-i/diesel.toml b/src/leetcode/1148.article-views-i/diesel.toml deleted file mode 100644 index 2db38f7e..00000000 --- a/src/leetcode/1148.article-views-i/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/1148.article-views-i/migrations" diff --git a/src/leetcode/1148.article-views-i/docker-compose.yml b/src/leetcode/1148.article-views-i/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/1148.article-views-i/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/1148.article-views-i/index.md b/src/leetcode/1148.article-views-i/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/1148.article-views-i/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/1148.article-views-i/migrations/.keep b/src/leetcode/1148.article-views-i/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/1148.article-views-i/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/1148.article-views-i/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/1148.article-views-i/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/1148.article-views-i/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/1148.article-views-i/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/1148.article-views-i/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/1148.article-views-i/migrations/2024-06-01-235109_views/down.sql b/src/leetcode/1148.article-views-i/migrations/2024-06-01-235109_views/down.sql deleted file mode 100644 index 1e044a47..00000000 --- a/src/leetcode/1148.article-views-i/migrations/2024-06-01-235109_views/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE views; diff --git a/src/leetcode/1148.article-views-i/migrations/2024-06-01-235109_views/up.sql b/src/leetcode/1148.article-views-i/migrations/2024-06-01-235109_views/up.sql deleted file mode 100644 index 1d2f7f73..00000000 --- a/src/leetcode/1148.article-views-i/migrations/2024-06-01-235109_views/up.sql +++ /dev/null @@ -1,16 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS views ( - id SERIAL PRIMARY KEY, - article_id INTEGER NOT NULL, - author_id INTEGER NOT NULL, - viewer_id INTEGER NOT NULL, - view_date DATE NOT NULL DEFAULT CURRENT_DATE -); - -INSERT INTO views (article_id, author_id, viewer_id, view_date) VALUES ('1', '3', '5', '2019-08-01'); -INSERT INTO views (article_id, author_id, viewer_id, view_date) VALUES ('1', '3', '6', '2019-08-02'); -INSERT INTO views (article_id, author_id, viewer_id, view_date) VALUES ('2', '7', '7', '2019-08-01'); -INSERT INTO views (article_id, author_id, viewer_id, view_date) VALUES ('2', '7', '6', '2019-08-02'); -INSERT INTO views (article_id, author_id, viewer_id, view_date) VALUES ('4', '7', '1', '2019-07-22'); -INSERT INTO views (article_id, author_id, viewer_id, view_date) VALUES ('3', '4', '4', '2019-07-21'); -INSERT INTO views (article_id, author_id, viewer_id, view_date) VALUES ('3', '4', '4', '2019-07-21'); diff --git a/src/leetcode/1148.article-views-i/query.sql b/src/leetcode/1148.article-views-i/query.sql deleted file mode 100644 index 7543352c..00000000 --- a/src/leetcode/1148.article-views-i/query.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -EXPLAIN -SELECT DISTINCT author_id AS id -FROM views -WHERE author_id = viewer_id; - -EXPLAIN -SELECT author_id AS id -FROM views -WHERE author_id = viewer_id -GROUP BY author_id; \ No newline at end of file diff --git a/src/leetcode/1148.article-views-i/src/db.rs b/src/leetcode/1148.article-views-i/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/1148.article-views-i/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/1148.article-views-i/src/error.rs b/src/leetcode/1148.article-views-i/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/1148.article-views-i/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/1148.article-views-i/src/main.rs b/src/leetcode/1148.article-views-i/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/1148.article-views-i/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/1148.article-views-i/src/schema.rs b/src/leetcode/1148.article-views-i/src/schema.rs deleted file mode 100644 index 745f9d4e..00000000 --- a/src/leetcode/1148.article-views-i/src/schema.rs +++ /dev/null @@ -1,11 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - views (id) { - id -> Int4, - article_id -> Int4, - author_id -> Int4, - viewer_id -> Int4, - view_date -> Date, - } -} diff --git a/src/leetcode/1179.reformat-department-table/.env b/src/leetcode/1179.reformat-department-table/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/1179.reformat-department-table/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/1179.reformat-department-table/.gitignore b/src/leetcode/1179.reformat-department-table/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/1179.reformat-department-table/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/1179.reformat-department-table/Cargo.toml b/src/leetcode/1179.reformat-department-table/Cargo.toml deleted file mode 100644 index b5945714..00000000 --- a/src/leetcode/1179.reformat-department-table/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-1179-reformat-department-table" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/1179.reformat-department-table/diesel.toml b/src/leetcode/1179.reformat-department-table/diesel.toml deleted file mode 100644 index 43441660..00000000 --- a/src/leetcode/1179.reformat-department-table/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/1179.reformat-department-table/migrations" diff --git a/src/leetcode/1179.reformat-department-table/docker-compose.yml b/src/leetcode/1179.reformat-department-table/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/1179.reformat-department-table/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/1179.reformat-department-table/index.md b/src/leetcode/1179.reformat-department-table/index.md deleted file mode 100644 index 77a618ba..00000000 --- a/src/leetcode/1179.reformat-department-table/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](../problems/) diff --git a/src/leetcode/1179.reformat-department-table/migrations/.keep b/src/leetcode/1179.reformat-department-table/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/1179.reformat-department-table/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/1179.reformat-department-table/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/1179.reformat-department-table/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/1179.reformat-department-table/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/1179.reformat-department-table/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/1179.reformat-department-table/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/1179.reformat-department-table/migrations/2024-06-02-000212_department/down.sql b/src/leetcode/1179.reformat-department-table/migrations/2024-06-02-000212_department/down.sql deleted file mode 100644 index f27a3611..00000000 --- a/src/leetcode/1179.reformat-department-table/migrations/2024-06-02-000212_department/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE department; diff --git a/src/leetcode/1179.reformat-department-table/migrations/2024-06-02-000212_department/up.sql b/src/leetcode/1179.reformat-department-table/migrations/2024-06-02-000212_department/up.sql deleted file mode 100644 index 6bf64dc8..00000000 --- a/src/leetcode/1179.reformat-department-table/migrations/2024-06-02-000212_department/up.sql +++ /dev/null @@ -1,13 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS department ( - id INTEGER NOT NULL, - revenue INTEGER NOT NULL, - month VARCHAR(5) NOT NULL, - PRIMARY KEY (id, month) -); - -INSERT INTO department (id, revenue, month) VALUES ('1', '8000', 'Jan'); -INSERT INTO department (id, revenue, month) VALUES ('2', '9000', 'Jan'); -INSERT INTO department (id, revenue, month) VALUES ('3', '10000', 'Feb'); -INSERT INTO department (id, revenue, month) VALUES ('1', '7000', 'Feb'); -INSERT INTO department (id, revenue, month) VALUES ('1', '6000', 'Mar'); diff --git a/src/leetcode/1179.reformat-department-table/query.sql b/src/leetcode/1179.reformat-department-table/query.sql deleted file mode 100644 index 81ba66e4..00000000 --- a/src/leetcode/1179.reformat-department-table/query.sql +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - -EXPLAIN -SELECT id, - SUM(CASE WHEN month = 'Jan' THEN revenue ELSE NULL END) AS Jan_Revenue, - SUM(CASE WHEN month = 'Feb' THEN revenue ELSE NULL END) AS Feb_Revenue, - SUM(CASE WHEN month = 'Mar' THEN revenue ELSE NULL END) AS Mar_Revenue, - SUM(CASE WHEN month = 'Apr' THEN revenue ELSE NULL END) AS Apr_Revenue, - SUM(CASE WHEN month = 'May' THEN revenue ELSE NULL END) AS May_Revenue, - SUM(CASE WHEN month = 'Jun' THEN revenue ELSE NULL END) AS Jun_Revenue, - SUM(CASE WHEN month = 'Jul' THEN revenue ELSE NULL END) AS Jul_Revenue, - SUM(CASE WHEN month = 'Aug' THEN revenue ELSE NULL END) AS Aug_Revenue, - SUM(CASE WHEN month = 'Sep' THEN revenue ELSE NULL END) AS Sep_Revenue, - SUM(CASE WHEN month = 'Oct' THEN revenue ELSE NULL END) AS Oct_Revenue, - SUM(CASE WHEN month = 'Nov' THEN revenue ELSE NULL END) AS Nov_Revenue, - SUM(CASE WHEN month = 'Dec' THEN revenue ELSE NULL END) AS Dec_Revenue -FROM department -GROUP BY id -ORDER BY id; \ No newline at end of file diff --git a/src/leetcode/1179.reformat-department-table/src/db.rs b/src/leetcode/1179.reformat-department-table/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/1179.reformat-department-table/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/1179.reformat-department-table/src/error.rs b/src/leetcode/1179.reformat-department-table/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/1179.reformat-department-table/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/1179.reformat-department-table/src/main.rs b/src/leetcode/1179.reformat-department-table/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/1179.reformat-department-table/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/1179.reformat-department-table/src/schema.rs b/src/leetcode/1179.reformat-department-table/src/schema.rs deleted file mode 100644 index 82d48c30..00000000 --- a/src/leetcode/1179.reformat-department-table/src/schema.rs +++ /dev/null @@ -1,10 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - department (id, month) { - id -> Int4, - revenue -> Int4, - #[max_length = 5] - month -> Varchar, - } -} diff --git a/src/leetcode/1251.average-selling-price/.env b/src/leetcode/1251.average-selling-price/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/1251.average-selling-price/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/1251.average-selling-price/.gitignore b/src/leetcode/1251.average-selling-price/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/1251.average-selling-price/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/1251.average-selling-price/Cargo.toml b/src/leetcode/1251.average-selling-price/Cargo.toml deleted file mode 100644 index 1bf5f123..00000000 --- a/src/leetcode/1251.average-selling-price/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-1251-average-selling-price" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/1251.average-selling-price/diesel.toml b/src/leetcode/1251.average-selling-price/diesel.toml deleted file mode 100644 index 997b5fe6..00000000 --- a/src/leetcode/1251.average-selling-price/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/1251.average-selling-price/migrations" diff --git a/src/leetcode/1251.average-selling-price/docker-compose.yml b/src/leetcode/1251.average-selling-price/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/1251.average-selling-price/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/1251.average-selling-price/index.md b/src/leetcode/1251.average-selling-price/index.md deleted file mode 100644 index 845f8988..00000000 --- a/src/leetcode/1251.average-selling-price/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](https://leetcode.com/problems/) diff --git a/src/leetcode/1251.average-selling-price/migrations/.keep b/src/leetcode/1251.average-selling-price/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/1251.average-selling-price/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/1251.average-selling-price/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/1251.average-selling-price/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/1251.average-selling-price/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/1251.average-selling-price/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/1251.average-selling-price/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/1251.average-selling-price/migrations/2024-08-01-081930_prices/down.sql b/src/leetcode/1251.average-selling-price/migrations/2024-08-01-081930_prices/down.sql deleted file mode 100644 index 90744cfb..00000000 --- a/src/leetcode/1251.average-selling-price/migrations/2024-08-01-081930_prices/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE prices; diff --git a/src/leetcode/1251.average-selling-price/migrations/2024-08-01-081930_prices/up.sql b/src/leetcode/1251.average-selling-price/migrations/2024-08-01-081930_prices/up.sql deleted file mode 100644 index f2791946..00000000 --- a/src/leetcode/1251.average-selling-price/migrations/2024-08-01-081930_prices/up.sql +++ /dev/null @@ -1,14 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS prices ( - id SERIAL PRIMARY KEY, - product_id int NOT NULL, - start_date date NOT NULL, - end_date date NOT NULL, - price int NOT NULL, - UNIQUE(product_id, start_date, end_date) -); - -INSERT INTO prices (product_id, start_date, end_date, price) VALUES ('1', '2019-02-17', '2019-02-28', '5'); -INSERT INTO prices (product_id, start_date, end_date, price) VALUES ('1', '2019-03-01', '2019-03-22', '20'); -INSERT INTO prices (product_id, start_date, end_date, price) VALUES ('2', '2019-02-01', '2019-02-20', '15'); -INSERT INTO prices (product_id, start_date, end_date, price) VALUES ('2', '2019-02-21', '2019-03-31', '30'); diff --git a/src/leetcode/1251.average-selling-price/migrations/2024-08-01-082104_units_sold/down.sql b/src/leetcode/1251.average-selling-price/migrations/2024-08-01-082104_units_sold/down.sql deleted file mode 100644 index 6a3e576c..00000000 --- a/src/leetcode/1251.average-selling-price/migrations/2024-08-01-082104_units_sold/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE UnitsSold; diff --git a/src/leetcode/1251.average-selling-price/migrations/2024-08-01-082104_units_sold/up.sql b/src/leetcode/1251.average-selling-price/migrations/2024-08-01-082104_units_sold/up.sql deleted file mode 100644 index fb544051..00000000 --- a/src/leetcode/1251.average-selling-price/migrations/2024-08-01-082104_units_sold/up.sql +++ /dev/null @@ -1,12 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS UnitsSold ( - id SERIAL PRIMARY KEY, - product_id int NOT NULL, - purchase_date date NOT NULL, - units int NOT NULL -); - -INSERT INTO UnitsSold (product_id, purchase_date, units) VALUES ('1', '2019-02-25', '100'); -INSERT INTO UnitsSold (product_id, purchase_date, units) VALUES ('1', '2019-03-01', '15'); -INSERT INTO UnitsSold (product_id, purchase_date, units) VALUES ('2', '2019-02-10', '200'); -INSERT INTO UnitsSold (product_id, purchase_date, units) VALUES ('2', '2019-03-22', '30'); diff --git a/src/leetcode/1251.average-selling-price/query.sql b/src/leetcode/1251.average-selling-price/query.sql deleted file mode 100644 index df712066..00000000 --- a/src/leetcode/1251.average-selling-price/query.sql +++ /dev/null @@ -1,6 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - diff --git a/src/leetcode/1251.average-selling-price/solution.sql b/src/leetcode/1251.average-selling-price/solution.sql deleted file mode 100644 index aad1ae4f..00000000 --- a/src/leetcode/1251.average-selling-price/solution.sql +++ /dev/null @@ -1,10 +0,0 @@ - -SELECT prices.product_id, - COALESCE(ROUND(CAST(SUM(units * price) AS NUMERIC) / SUM(units), 2), 0) AS average_price -FROM prices -LEFT JOIN unitssold -ON unitssold.product_id = prices.product_id -AND unitssold.purchase_date >= prices.start_date -AND unitssold.purchase_date <= prices.end_date -GROUP BY prices.product_id -ORDER BY prices.product_id; diff --git a/src/leetcode/1251.average-selling-price/src/db.rs b/src/leetcode/1251.average-selling-price/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/1251.average-selling-price/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/1251.average-selling-price/src/error.rs b/src/leetcode/1251.average-selling-price/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/1251.average-selling-price/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/1251.average-selling-price/src/main.rs b/src/leetcode/1251.average-selling-price/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/1251.average-selling-price/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/1251.average-selling-price/src/schema.rs b/src/leetcode/1251.average-selling-price/src/schema.rs deleted file mode 100644 index 8f04a29d..00000000 --- a/src/leetcode/1251.average-selling-price/src/schema.rs +++ /dev/null @@ -1,25 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - prices (id) { - id -> Int4, - product_id -> Int4, - start_date -> Date, - end_date -> Date, - price -> Int4, - } -} - -diesel::table! { - unitssold (id) { - id -> Int4, - product_id -> Int4, - purchase_date -> Date, - units -> Int4, - } -} - -diesel::allow_tables_to_appear_in_same_query!( - prices, - unitssold, -); diff --git a/src/leetcode/1873.calculate-special-bonus/.env b/src/leetcode/1873.calculate-special-bonus/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/1873.calculate-special-bonus/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/1873.calculate-special-bonus/.gitignore b/src/leetcode/1873.calculate-special-bonus/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/1873.calculate-special-bonus/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/1873.calculate-special-bonus/Cargo.toml b/src/leetcode/1873.calculate-special-bonus/Cargo.toml deleted file mode 100644 index b6f0278b..00000000 --- a/src/leetcode/1873.calculate-special-bonus/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-1873-calculate-special-bonus" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/1873.calculate-special-bonus/diesel.toml b/src/leetcode/1873.calculate-special-bonus/diesel.toml deleted file mode 100644 index 0a982611..00000000 --- a/src/leetcode/1873.calculate-special-bonus/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/1873.calculate-special-bonus/migrations" diff --git a/src/leetcode/1873.calculate-special-bonus/docker-compose.yml b/src/leetcode/1873.calculate-special-bonus/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/1873.calculate-special-bonus/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/1873.calculate-special-bonus/index.md b/src/leetcode/1873.calculate-special-bonus/index.md deleted file mode 100644 index 845f8988..00000000 --- a/src/leetcode/1873.calculate-special-bonus/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](https://leetcode.com/problems/) diff --git a/src/leetcode/1873.calculate-special-bonus/migrations/.keep b/src/leetcode/1873.calculate-special-bonus/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/1873.calculate-special-bonus/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/1873.calculate-special-bonus/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/1873.calculate-special-bonus/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/1873.calculate-special-bonus/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/1873.calculate-special-bonus/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/1873.calculate-special-bonus/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/1873.calculate-special-bonus/migrations/2024-08-01-075842_employees/down.sql b/src/leetcode/1873.calculate-special-bonus/migrations/2024-08-01-075842_employees/down.sql deleted file mode 100644 index 48daa4ba..00000000 --- a/src/leetcode/1873.calculate-special-bonus/migrations/2024-08-01-075842_employees/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE employees; diff --git a/src/leetcode/1873.calculate-special-bonus/migrations/2024-08-01-075842_employees/up.sql b/src/leetcode/1873.calculate-special-bonus/migrations/2024-08-01-075842_employees/up.sql deleted file mode 100644 index 7540d67f..00000000 --- a/src/leetcode/1873.calculate-special-bonus/migrations/2024-08-01-075842_employees/up.sql +++ /dev/null @@ -1,13 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS employees ( - id SERIAL PRIMARY KEY, - employee_id int NOT NULL, - name varchar(30) NOT NULL, - salary int NOT NULL -); - -INSERT INTO employees (employee_id, name, salary) VALUES ('2', 'Meir', '3000'); -INSERT INTO employees (employee_id, name, salary) VALUES ('3', 'Michael', '3800'); -INSERT INTO employees (employee_id, name, salary) VALUES ('7', 'Addilyn', '7400'); -INSERT INTO employees (employee_id, name, salary) VALUES ('8', 'Juan', '6100'); -INSERT INTO employees (employee_id, name, salary) VALUES ('9', 'Kannon', '7700'); diff --git a/src/leetcode/1873.calculate-special-bonus/query.sql b/src/leetcode/1873.calculate-special-bonus/query.sql deleted file mode 100644 index df712066..00000000 --- a/src/leetcode/1873.calculate-special-bonus/query.sql +++ /dev/null @@ -1,6 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - diff --git a/src/leetcode/1873.calculate-special-bonus/solution.sql b/src/leetcode/1873.calculate-special-bonus/solution.sql deleted file mode 100644 index 956f430e..00000000 --- a/src/leetcode/1873.calculate-special-bonus/solution.sql +++ /dev/null @@ -1,9 +0,0 @@ - -SELECT employee_id - , CASE - WHEN employee_id % 2 = 1 AND name NOT LIKE 'M%' THEN salary - ELSE 0 - END - AS bonus -FROM employees -ORDER BY employee_id; diff --git a/src/leetcode/1873.calculate-special-bonus/src/db.rs b/src/leetcode/1873.calculate-special-bonus/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/1873.calculate-special-bonus/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/1873.calculate-special-bonus/src/error.rs b/src/leetcode/1873.calculate-special-bonus/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/1873.calculate-special-bonus/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/1873.calculate-special-bonus/src/main.rs b/src/leetcode/1873.calculate-special-bonus/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/1873.calculate-special-bonus/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/1873.calculate-special-bonus/src/schema.rs b/src/leetcode/1873.calculate-special-bonus/src/schema.rs deleted file mode 100644 index 4fb70015..00000000 --- a/src/leetcode/1873.calculate-special-bonus/src/schema.rs +++ /dev/null @@ -1,11 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - employees (id) { - id -> Int4, - employee_id -> Int4, - #[max_length = 30] - name -> Varchar, - salary -> Int4, - } -} diff --git a/src/leetcode/1890.the-latest-login-in-2020/.env b/src/leetcode/1890.the-latest-login-in-2020/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/1890.the-latest-login-in-2020/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/1890.the-latest-login-in-2020/.gitignore b/src/leetcode/1890.the-latest-login-in-2020/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/1890.the-latest-login-in-2020/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/1890.the-latest-login-in-2020/Cargo.toml b/src/leetcode/1890.the-latest-login-in-2020/Cargo.toml deleted file mode 100644 index 6e49d030..00000000 --- a/src/leetcode/1890.the-latest-login-in-2020/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-1890-the-latest-login-in-2020" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/1890.the-latest-login-in-2020/diesel.toml b/src/leetcode/1890.the-latest-login-in-2020/diesel.toml deleted file mode 100644 index c072cd38..00000000 --- a/src/leetcode/1890.the-latest-login-in-2020/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/1890.the-latest-login-in-2020/migrations" diff --git a/src/leetcode/1890.the-latest-login-in-2020/docker-compose.yml b/src/leetcode/1890.the-latest-login-in-2020/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/1890.the-latest-login-in-2020/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/1890.the-latest-login-in-2020/index.md b/src/leetcode/1890.the-latest-login-in-2020/index.md deleted file mode 100644 index 845f8988..00000000 --- a/src/leetcode/1890.the-latest-login-in-2020/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](https://leetcode.com/problems/) diff --git a/src/leetcode/1890.the-latest-login-in-2020/migrations/.keep b/src/leetcode/1890.the-latest-login-in-2020/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/1890.the-latest-login-in-2020/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/1890.the-latest-login-in-2020/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/1890.the-latest-login-in-2020/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/1890.the-latest-login-in-2020/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/1890.the-latest-login-in-2020/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/1890.the-latest-login-in-2020/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/1890.the-latest-login-in-2020/migrations/2024-08-01-074201_logins/down.sql b/src/leetcode/1890.the-latest-login-in-2020/migrations/2024-08-01-074201_logins/down.sql deleted file mode 100644 index 9eebfaa1..00000000 --- a/src/leetcode/1890.the-latest-login-in-2020/migrations/2024-08-01-074201_logins/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE logins; diff --git a/src/leetcode/1890.the-latest-login-in-2020/migrations/2024-08-01-074201_logins/up.sql b/src/leetcode/1890.the-latest-login-in-2020/migrations/2024-08-01-074201_logins/up.sql deleted file mode 100644 index f2bb449b..00000000 --- a/src/leetcode/1890.the-latest-login-in-2020/migrations/2024-08-01-074201_logins/up.sql +++ /dev/null @@ -1,17 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS logins ( - id SERIAL PRIMARY KEY, - user_id int, - time_stamp TIMESTAMP NOT NULL, - UNIQUE(user_id, time_stamp) -); - -INSERT INTO Logins (user_id, time_stamp) VALUES ('6', '2020-06-30 15:06:07'); -INSERT INTO Logins (user_id, time_stamp) VALUES ('6', '2021-04-21 14:06:06'); -INSERT INTO Logins (user_id, time_stamp) VALUES ('6', '2019-03-07 00:18:15'); -INSERT INTO Logins (user_id, time_stamp) VALUES ('8', '2020-02-01 05:10:53'); -INSERT INTO Logins (user_id, time_stamp) VALUES ('8', '2020-12-30 00:46:50'); -INSERT INTO Logins (user_id, time_stamp) VALUES ('2', '2020-01-16 02:49:50'); -INSERT INTO Logins (user_id, time_stamp) VALUES ('2', '2019-08-25 07:59:08'); -INSERT INTO Logins (user_id, time_stamp) VALUES ('14', '2019-07-14 09:00:00'); -INSERT INTO Logins (user_id, time_stamp) VALUES ('14', '2021-01-06 11:59:59'); diff --git a/src/leetcode/1890.the-latest-login-in-2020/query.sql b/src/leetcode/1890.the-latest-login-in-2020/query.sql deleted file mode 100644 index df712066..00000000 --- a/src/leetcode/1890.the-latest-login-in-2020/query.sql +++ /dev/null @@ -1,6 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - diff --git a/src/leetcode/1890.the-latest-login-in-2020/solution.sql b/src/leetcode/1890.the-latest-login-in-2020/solution.sql deleted file mode 100644 index 4684a56e..00000000 --- a/src/leetcode/1890.the-latest-login-in-2020/solution.sql +++ /dev/null @@ -1,14 +0,0 @@ - --- max -SELECT user_id, max(time_stamp) AS last_stamp -FROM logins -WHERE DATE_PART('year', time_stamp::date) = 2020 -GROUP BY user_id; - --- order by -SELECT - DISTINCT ON(user_id) - user_id, time_stamp as last_stamp -FROM logins -WHERE EXTRACT(YEAR FROM time_stamp) = 2020 -ORDER By user_id, time_stamp DESC; diff --git a/src/leetcode/1890.the-latest-login-in-2020/src/db.rs b/src/leetcode/1890.the-latest-login-in-2020/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/1890.the-latest-login-in-2020/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/1890.the-latest-login-in-2020/src/error.rs b/src/leetcode/1890.the-latest-login-in-2020/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/1890.the-latest-login-in-2020/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/1890.the-latest-login-in-2020/src/main.rs b/src/leetcode/1890.the-latest-login-in-2020/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/1890.the-latest-login-in-2020/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/1890.the-latest-login-in-2020/src/schema.rs b/src/leetcode/1890.the-latest-login-in-2020/src/schema.rs deleted file mode 100644 index 4a51d249..00000000 --- a/src/leetcode/1890.the-latest-login-in-2020/src/schema.rs +++ /dev/null @@ -1,9 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - logins (id) { - id -> Int4, - user_id -> Nullable, - time_stamp -> Timestamp, - } -} diff --git a/src/leetcode/1965.employees-with-missing-information/.env b/src/leetcode/1965.employees-with-missing-information/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/1965.employees-with-missing-information/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/1965.employees-with-missing-information/.gitignore b/src/leetcode/1965.employees-with-missing-information/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/1965.employees-with-missing-information/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/1965.employees-with-missing-information/Cargo.toml b/src/leetcode/1965.employees-with-missing-information/Cargo.toml deleted file mode 100644 index 927f434b..00000000 --- a/src/leetcode/1965.employees-with-missing-information/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-1965-employees-with-missing-information" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/1965.employees-with-missing-information/diesel.toml b/src/leetcode/1965.employees-with-missing-information/diesel.toml deleted file mode 100644 index 6592e063..00000000 --- a/src/leetcode/1965.employees-with-missing-information/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/1965.employees-with-missing-information/migrations" diff --git a/src/leetcode/1965.employees-with-missing-information/docker-compose.yml b/src/leetcode/1965.employees-with-missing-information/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/1965.employees-with-missing-information/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/1965.employees-with-missing-information/index.md b/src/leetcode/1965.employees-with-missing-information/index.md deleted file mode 100644 index 845f8988..00000000 --- a/src/leetcode/1965.employees-with-missing-information/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](https://leetcode.com/problems/) diff --git a/src/leetcode/1965.employees-with-missing-information/migrations/.keep b/src/leetcode/1965.employees-with-missing-information/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/1965.employees-with-missing-information/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/1965.employees-with-missing-information/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/1965.employees-with-missing-information/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/1965.employees-with-missing-information/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/1965.employees-with-missing-information/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/1965.employees-with-missing-information/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/1965.employees-with-missing-information/migrations/2024-08-01-071704_employees/down.sql b/src/leetcode/1965.employees-with-missing-information/migrations/2024-08-01-071704_employees/down.sql deleted file mode 100644 index 94a54786..00000000 --- a/src/leetcode/1965.employees-with-missing-information/migrations/2024-08-01-071704_employees/down.sql +++ /dev/null @@ -1,3 +0,0 @@ --- This file should undo anything in `up.sql` - -DROP TABLE employees; diff --git a/src/leetcode/1965.employees-with-missing-information/migrations/2024-08-01-071704_employees/up.sql b/src/leetcode/1965.employees-with-missing-information/migrations/2024-08-01-071704_employees/up.sql deleted file mode 100644 index daed5a49..00000000 --- a/src/leetcode/1965.employees-with-missing-information/migrations/2024-08-01-071704_employees/up.sql +++ /dev/null @@ -1,10 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS employees ( - id SERIAL PRIMARY KEY, - employee_id int UNIQUE NOT NULL, - name varchar(30) NOT NULL -); - -INSERT INTO employees (employee_id, name) VALUES ('2', 'Crew'); -INSERT INTO employees (employee_id, name) VALUES ('4', 'Haven'); -INSERT INTO employees (employee_id, name) VALUES ('5', 'Kristian'); diff --git a/src/leetcode/1965.employees-with-missing-information/migrations/2024-08-01-071836_salaries/down.sql b/src/leetcode/1965.employees-with-missing-information/migrations/2024-08-01-071836_salaries/down.sql deleted file mode 100644 index 82a4f087..00000000 --- a/src/leetcode/1965.employees-with-missing-information/migrations/2024-08-01-071836_salaries/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE salaries; diff --git a/src/leetcode/1965.employees-with-missing-information/migrations/2024-08-01-071836_salaries/up.sql b/src/leetcode/1965.employees-with-missing-information/migrations/2024-08-01-071836_salaries/up.sql deleted file mode 100644 index 9b02fc89..00000000 --- a/src/leetcode/1965.employees-with-missing-information/migrations/2024-08-01-071836_salaries/up.sql +++ /dev/null @@ -1,10 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS salaries ( - id SERIAL PRIMARY KEY, - employee_id int UNIQUE NOT NULL, - salary int NOT NULL -); - -INSERT INTO Salaries (employee_id, salary) VALUES ('5', '76071'); -INSERT INTO Salaries (employee_id, salary) VALUES ('1', '22517'); -INSERT INTO Salaries (employee_id, salary) VALUES ('4', '63539'); diff --git a/src/leetcode/1965.employees-with-missing-information/query.sql b/src/leetcode/1965.employees-with-missing-information/query.sql deleted file mode 100644 index df712066..00000000 --- a/src/leetcode/1965.employees-with-missing-information/query.sql +++ /dev/null @@ -1,6 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - diff --git a/src/leetcode/1965.employees-with-missing-information/solution.sql b/src/leetcode/1965.employees-with-missing-information/solution.sql deleted file mode 100644 index ea6020bf..00000000 --- a/src/leetcode/1965.employees-with-missing-information/solution.sql +++ /dev/null @@ -1,15 +0,0 @@ - --- union select - -SELECT employee_id FROM salaries WHERE employee_id NOT IN (SELECT employee_id FROM employees) -UNION -SELECT employee_id FROM employees WHERE employee_id NOT IN (SELECT employee_id FROM salaries) -ORDER BY employee_id; - --- full join - -SELECT employee_id FROM employees -FULL JOIN salaries - USING (employee_id) -WHERE salaries.salary is NULL OR employees.name is NULL; - diff --git a/src/leetcode/1965.employees-with-missing-information/src/db.rs b/src/leetcode/1965.employees-with-missing-information/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/1965.employees-with-missing-information/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/1965.employees-with-missing-information/src/error.rs b/src/leetcode/1965.employees-with-missing-information/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/1965.employees-with-missing-information/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/1965.employees-with-missing-information/src/main.rs b/src/leetcode/1965.employees-with-missing-information/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/1965.employees-with-missing-information/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/1965.employees-with-missing-information/src/schema.rs b/src/leetcode/1965.employees-with-missing-information/src/schema.rs deleted file mode 100644 index 9749b84f..00000000 --- a/src/leetcode/1965.employees-with-missing-information/src/schema.rs +++ /dev/null @@ -1,23 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - employees (id) { - id -> Int4, - employee_id -> Int4, - #[max_length = 30] - name -> Varchar, - } -} - -diesel::table! { - salaries (id) { - id -> Int4, - employee_id -> Int4, - salary -> Int4, - } -} - -diesel::allow_tables_to_appear_in_same_query!( - employees, - salaries, -); diff --git a/src/leetcode/1978.employees-whose-manager-left-the-company/.env b/src/leetcode/1978.employees-whose-manager-left-the-company/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/1978.employees-whose-manager-left-the-company/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/1978.employees-whose-manager-left-the-company/.gitignore b/src/leetcode/1978.employees-whose-manager-left-the-company/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/1978.employees-whose-manager-left-the-company/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/1978.employees-whose-manager-left-the-company/Cargo.toml b/src/leetcode/1978.employees-whose-manager-left-the-company/Cargo.toml deleted file mode 100644 index 0d38ca2f..00000000 --- a/src/leetcode/1978.employees-whose-manager-left-the-company/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-1978-employees-whose-manager-left-the-company" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/1978.employees-whose-manager-left-the-company/diesel.toml b/src/leetcode/1978.employees-whose-manager-left-the-company/diesel.toml deleted file mode 100644 index 80722471..00000000 --- a/src/leetcode/1978.employees-whose-manager-left-the-company/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/1978.employees-whose-manager-left-the-company/migrations" diff --git a/src/leetcode/1978.employees-whose-manager-left-the-company/docker-compose.yml b/src/leetcode/1978.employees-whose-manager-left-the-company/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/1978.employees-whose-manager-left-the-company/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/1978.employees-whose-manager-left-the-company/index.md b/src/leetcode/1978.employees-whose-manager-left-the-company/index.md deleted file mode 100644 index 845f8988..00000000 --- a/src/leetcode/1978.employees-whose-manager-left-the-company/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](https://leetcode.com/problems/) diff --git a/src/leetcode/1978.employees-whose-manager-left-the-company/migrations/.keep b/src/leetcode/1978.employees-whose-manager-left-the-company/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/1978.employees-whose-manager-left-the-company/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/1978.employees-whose-manager-left-the-company/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/1978.employees-whose-manager-left-the-company/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/1978.employees-whose-manager-left-the-company/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/1978.employees-whose-manager-left-the-company/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/1978.employees-whose-manager-left-the-company/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/1978.employees-whose-manager-left-the-company/migrations/2024-08-01-070219_employee/down.sql b/src/leetcode/1978.employees-whose-manager-left-the-company/migrations/2024-08-01-070219_employee/down.sql deleted file mode 100644 index 48daa4ba..00000000 --- a/src/leetcode/1978.employees-whose-manager-left-the-company/migrations/2024-08-01-070219_employee/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE employees; diff --git a/src/leetcode/1978.employees-whose-manager-left-the-company/migrations/2024-08-01-070219_employee/up.sql b/src/leetcode/1978.employees-whose-manager-left-the-company/migrations/2024-08-01-070219_employee/up.sql deleted file mode 100644 index 0680743c..00000000 --- a/src/leetcode/1978.employees-whose-manager-left-the-company/migrations/2024-08-01-070219_employee/up.sql +++ /dev/null @@ -1,15 +0,0 @@ --- Your SQL goes here -CREATE TABLE IF NOT EXISTS employees ( - id SERIAL PRIMARY KEY, - employee_id int UNIQUE NOT NULL, - name varchar(20) NOT NULL, - manager_id int, - salary int NOT NULL -); - -INSERT INTO employees (employee_id, name, manager_id, salary) VALUES ('3', 'Mila', '9', '60301'); -INSERT INTO employees (employee_id, name, manager_id, salary) VALUES ('12', 'Antonella', NULL, '31000'); -INSERT INTO employees (employee_id, name, manager_id, salary) VALUES ('13', 'Emery', NULL, '67084'); -INSERT INTO employees (employee_id, name, manager_id, salary) VALUES ('1', 'Kalel', '11', '21241'); -INSERT INTO employees (employee_id, name, manager_id, salary) VALUES ('9', 'Mikaela', NULL, '50937'); -INSERT INTO employees (employee_id, name, manager_id, salary) VALUES ('11', 'Joziah', '6', '28485'); diff --git a/src/leetcode/1978.employees-whose-manager-left-the-company/query.sql b/src/leetcode/1978.employees-whose-manager-left-the-company/query.sql deleted file mode 100644 index df712066..00000000 --- a/src/leetcode/1978.employees-whose-manager-left-the-company/query.sql +++ /dev/null @@ -1,6 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - diff --git a/src/leetcode/1978.employees-whose-manager-left-the-company/solution.sql b/src/leetcode/1978.employees-whose-manager-left-the-company/solution.sql deleted file mode 100644 index 9d887143..00000000 --- a/src/leetcode/1978.employees-whose-manager-left-the-company/solution.sql +++ /dev/null @@ -1,18 +0,0 @@ - -SELECT e1.employee_id AS "employee_id" -FROM employees e1 -WHERE e1.salary < 30000 - AND e1.manager_id IS NOT NULL - AND NOT EXISTS(SELECT 1 - FROM employees e2 - WHERE e1.manager_id = e2.employee_id) -ORDER BY e1.employee_id; - --- solution 2 -SELECT employee_id -FROM employees -WHERE salary < 30000 - AND manager_id NOT IN - (SELECT employee_id - FROM employees) -ORDER BY employee_id; diff --git a/src/leetcode/1978.employees-whose-manager-left-the-company/src/db.rs b/src/leetcode/1978.employees-whose-manager-left-the-company/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/1978.employees-whose-manager-left-the-company/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/1978.employees-whose-manager-left-the-company/src/error.rs b/src/leetcode/1978.employees-whose-manager-left-the-company/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/1978.employees-whose-manager-left-the-company/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/1978.employees-whose-manager-left-the-company/src/main.rs b/src/leetcode/1978.employees-whose-manager-left-the-company/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/1978.employees-whose-manager-left-the-company/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/1978.employees-whose-manager-left-the-company/src/schema.rs b/src/leetcode/1978.employees-whose-manager-left-the-company/src/schema.rs deleted file mode 100644 index cbce8697..00000000 --- a/src/leetcode/1978.employees-whose-manager-left-the-company/src/schema.rs +++ /dev/null @@ -1,12 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - employees (id) { - id -> Int4, - employee_id -> Int4, - #[max_length = 20] - name -> Varchar, - manager_id -> Nullable, - salary -> Int4, - } -} diff --git a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/.env b/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/.gitignore b/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/Cargo.toml b/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/Cargo.toml deleted file mode 100644 index b5804b84..00000000 --- a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-2356-number-of-unique-subjects-taught-by-each-teacher" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.4", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.5" -log = "0.4.22" -r2d2 = "0.8.10" diff --git a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/diesel.toml b/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/diesel.toml deleted file mode 100644 index e5c0f0d2..00000000 --- a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/diesel.toml +++ /dev/null @@ -1,9 +0,0 @@ -# For documentation on how to configure this file, -# see https://diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" -custom_type_derives = ["diesel::query_builder::QueryId", "Clone"] - -[migrations_directory] -dir = "/home/shaohua/dev/rust/TheAlgorithms/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/migrations" diff --git a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/docker-compose.yml b/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/index.md b/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/index.md deleted file mode 100644 index 845f8988..00000000 --- a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](https://leetcode.com/problems/) diff --git a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/migrations/.keep b/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/migrations/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/migrations/00000000000000_diesel_initial_setup/down.sql b/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/migrations/00000000000000_diesel_initial_setup/down.sql deleted file mode 100644 index a9f52609..00000000 --- a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/migrations/00000000000000_diesel_initial_setup/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - -DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); -DROP FUNCTION IF EXISTS diesel_set_updated_at(); diff --git a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/migrations/00000000000000_diesel_initial_setup/up.sql b/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/migrations/00000000000000_diesel_initial_setup/up.sql deleted file mode 100644 index d68895b1..00000000 --- a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/migrations/00000000000000_diesel_initial_setup/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- This file was automatically created by Diesel to setup helper functions --- and other internal bookkeeping. This file is safe to edit, any future --- changes will be added to existing projects as new migrations. - - - - --- Sets up a trigger for the given table to automatically set a column called --- `updated_at` whenever the row is modified (unless `updated_at` was included --- in the modified columns) --- --- # Example --- --- ```sql --- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); --- --- SELECT diesel_manage_updated_at('users'); --- ``` -CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ -BEGIN - EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s - FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ -BEGIN - IF ( - NEW IS DISTINCT FROM OLD AND - NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at - ) THEN - NEW.updated_at := current_timestamp; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/migrations/2024-08-01-064052_teacher/down.sql b/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/migrations/2024-08-01-064052_teacher/down.sql deleted file mode 100644 index 59ac8415..00000000 --- a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/migrations/2024-08-01-064052_teacher/down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- This file should undo anything in `up.sql` -DROP TABLE teacher; diff --git a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/migrations/2024-08-01-064052_teacher/up.sql b/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/migrations/2024-08-01-064052_teacher/up.sql deleted file mode 100644 index 3eb477fd..00000000 --- a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/migrations/2024-08-01-064052_teacher/up.sql +++ /dev/null @@ -1,21 +0,0 @@ --- Your SQL goes here - -CREATE TABLE IF NOT EXISTS teacher ( - id SERIAL PRIMARY KEY, - teacher_id int NOT NULL, - subject_id int NOT NULL, - dept_id int NOT NULL -); - -CREATE UNIQUE INDEX teacher_subj_dep ON teacher ( - subject_id, - dept_id -); - -insert into teacher (teacher_id, subject_id, dept_id) VALUES ('1', '2', '3'); -insert into teacher (teacher_id, subject_id, dept_id) VALUES ('1', '2', '4'); -insert into teacher (teacher_id, subject_id, dept_id) VALUES ('1', '3', '3'); -insert into teacher (teacher_id, subject_id, dept_id) VALUES ('2', '1', '1'); -insert into teacher (teacher_id, subject_id, dept_id) VALUES ('2', '2', '1'); -insert into teacher (teacher_id, subject_id, dept_id) VALUES ('2', '3', '1'); -insert into teacher (teacher_id, subject_id, dept_id) VALUES ('2', '4', '1'); diff --git a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/query.sql b/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/query.sql deleted file mode 100644 index df712066..00000000 --- a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/query.sql +++ /dev/null @@ -1,6 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - diff --git a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/solution.sql b/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/solution.sql deleted file mode 100644 index 6acc9f1c..00000000 --- a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/solution.sql +++ /dev/null @@ -1,4 +0,0 @@ - -SELECT teacher_id, COUNT(DISTINCT subject_id) AS cnt -FROM teacher -GROUP BY teacher_id; diff --git a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/src/db.rs b/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/src/error.rs b/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/src/main.rs b/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/src/schema.rs b/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/src/schema.rs deleted file mode 100644 index 049ca55c..00000000 --- a/src/leetcode/2356.number-of-unique-subjects-taught-by-each-teacher/src/schema.rs +++ /dev/null @@ -1,10 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - teacher (id) { - id -> Int4, - teacher_id -> Int4, - subject_id -> Int4, - dept_id -> Int4, - } -} diff --git a/src/leetcode/template-pgsql/.env b/src/leetcode/template-pgsql/.env deleted file mode 100644 index 453c39f8..00000000 --- a/src/leetcode/template-pgsql/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=postgres://leetcode:leetcode-password@localhost/leetcode diff --git a/src/leetcode/template-pgsql/.gitignore b/src/leetcode/template-pgsql/.gitignore deleted file mode 100644 index c2de89b2..00000000 --- a/src/leetcode/template-pgsql/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/db diff --git a/src/leetcode/template-pgsql/Cargo.toml b/src/leetcode/template-pgsql/Cargo.toml deleted file mode 100644 index b6ec28fd..00000000 --- a/src/leetcode/template-pgsql/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lc-0000-name" -version = "0.1.0" -edition = "2021" -publish = false - -[dependencies] -diesel = { version = "2.2.0", default-features = false, features = [ "chrono", "postgres", "r2d2" ] } -dotenvy = "0.15.7" -env_logger = "0.11.3" -log = "0.4.21" -r2d2 = "0.8.10" diff --git a/src/leetcode/template-pgsql/docker-compose.yml b/src/leetcode/template-pgsql/docker-compose.yml deleted file mode 100644 index afd296b1..00000000 --- a/src/leetcode/template-pgsql/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: "3.0" -services: - leetcode_db: - image: postgres:15.3 - restart: always - ports: - - 127.0.0.1:5432:5432 - environment: - POSTGRES_PASSWORD: leetcode-password - POSTGRES_USER: leetcode - POSTGRES_DB: leetcode - volumes: - - ./db:/var/lib/postgresql diff --git a/src/leetcode/template-pgsql/index.md b/src/leetcode/template-pgsql/index.md deleted file mode 100644 index 845f8988..00000000 --- a/src/leetcode/template-pgsql/index.md +++ /dev/null @@ -1,4 +0,0 @@ - -# - -[问题描述](https://leetcode.com/problems/) diff --git a/src/leetcode/template-pgsql/query.sql b/src/leetcode/template-pgsql/query.sql deleted file mode 100644 index df712066..00000000 --- a/src/leetcode/template-pgsql/query.sql +++ /dev/null @@ -1,6 +0,0 @@ -/* - * Copyright (c) 2024 Xu Shaohua . All rights reserved. - * Use of this source is governed by General Public License that can be found - * in the LICENSE file. - */ - diff --git a/src/leetcode/template-pgsql/src/db.rs b/src/leetcode/template-pgsql/src/db.rs deleted file mode 100644 index c8d1e3be..00000000 --- a/src/leetcode/template-pgsql/src/db.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::pg::PgConnection; -use diesel::r2d2::{ConnectionManager, Pool}; - -use crate::error::{Error, ErrorKind}; - -pub type DbPool = Pool>; - -/// Create postgres database connection pool. -/// -/// # Errors -/// -/// Returns error if: -/// - No `DATABASE_URL` is set in current environment. -/// - Failed to connect to database. -pub fn get_connection_pool() -> Result { - let url = std::env::var("DATABASE_URL").map_err(|err| { - Error::from_string( - ErrorKind::ConfigError, - format!("DATABASE_URL is not set in environment, err: {err:?}"), - ) - })?; - let manager = ConnectionManager::::new(&url); - - Pool::builder() - .test_on_check_out(true) - .build(manager) - .map_err(|err| { - Error::from_string( - ErrorKind::DbConnError, - format!("Failed to create connection pool, url: {url}, err: {err:?}"), - ) - }) -} diff --git a/src/leetcode/template-pgsql/src/error.rs b/src/leetcode/template-pgsql/src/error.rs deleted file mode 100644 index c9baa518..00000000 --- a/src/leetcode/template-pgsql/src/error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2022 Xu Shaohua . All rights reserved. -// Use of this source is governed by GNU General Public License -// that can be found in the LICENSE file. - -#![allow(clippy::enum_variant_names)] - -use diesel::result::DatabaseErrorKind; -use std::fmt::{Display, Formatter}; -use std::io; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ErrorKind { - ConfigError, - - DbConnError, - DbGeneralError, - DbUniqueViolationError, - DbForeignKeyViolationError, - DbNotFoundError, - - IoError, -} - -unsafe impl Send for ErrorKind {} - -#[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, - message: String, -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}: {}", self.kind, self.message) - } -} - -impl std::error::Error for Error {} - -#[allow(dead_code)] -impl Error { - #[must_use] - pub fn new(kind: ErrorKind, message: &str) -> Self { - Self { - kind, - message: message.to_owned(), - } - } - - #[must_use] - pub const fn from_string(kind: ErrorKind, message: String) -> Self { - Self { kind, message } - } - - #[must_use] - pub const fn kind(&self) -> ErrorKind { - self.kind - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } -} - -impl From for Error { - fn from(err: io::Error) -> Self { - Self::from_string(ErrorKind::IoError, err.to_string()) - } -} - -impl From for Error { - fn from(err: r2d2::Error) -> Self { - Self::from_string(ErrorKind::DbConnError, format!("r2d2 err: {err}")) - } -} - -impl From for Error { - fn from(err: diesel::result::Error) -> Self { - match &err { - diesel::result::Error::DatabaseError(kind, _info) => match kind { - DatabaseErrorKind::UniqueViolation => { - Self::from_string(ErrorKind::DbUniqueViolationError, err.to_string()) - } - DatabaseErrorKind::ForeignKeyViolation => { - Self::from_string(ErrorKind::DbForeignKeyViolationError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - }, - diesel::result::Error::NotFound => { - Self::from_string(ErrorKind::DbNotFoundError, err.to_string()) - } - _ => Self::from_string(ErrorKind::DbGeneralError, err.to_string()), - } - } -} - -impl From for Error { - fn from(err: std::num::ParseIntError) -> Self { - Self::from_string(ErrorKind::ConfigError, err.to_string()) - } -} - -impl From for Error { - fn from(err: std::ffi::OsString) -> Self { - Self::from_string( - ErrorKind::ConfigError, - format!("OsString to String err: {err:?}"), - ) - } -} - -impl From for Error { - fn from(err: dotenvy::Error) -> Self { - Self::from_string(ErrorKind::ConfigError, format!("dotenv err: {err:?}")) - } -} diff --git a/src/leetcode/template-pgsql/src/main.rs b/src/leetcode/template-pgsql/src/main.rs deleted file mode 100644 index 8ad13477..00000000 --- a/src/leetcode/template-pgsql/src/main.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2024 Xu Shaohua . All rights reserved. -// Use of this source is governed by General Public License that can be found -// in the LICENSE file. - -use diesel::connection::SimpleConnection; -use std::env; -use std::fs; - -mod db; -mod error; - -use error::Error; - -fn main() -> Result<(), Error> { - dotenvy::dotenv()?; - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - - let pool = db::get_connection_pool()?; - let mut conn = pool.get()?; - for arg in env::args().skip(1) { - let sql_content: String = fs::read_to_string(arg)?; - conn.batch_execute(&sql_content)?; - } - Ok(()) -} diff --git a/src/leetcode/template-pgsql/src/schema.rs b/src/leetcode/template-pgsql/src/schema.rs deleted file mode 100644 index 5dabb71a..00000000 --- a/src/leetcode/template-pgsql/src/schema.rs +++ /dev/null @@ -1,10 +0,0 @@ -// @generated automatically by Diesel CLI. - -diesel::table! { - activity (player_id, event_date) { - player_id -> Int4, - device_id -> Int4, - event_date -> Date, - games_played -> Int4, - } -}