Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -160,4 +160,5 @@ cython_debug/
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/
.idea/
/pyproject.toml
25 changes: 25 additions & 0 deletions homework-1/create_tables.sql
Original file line number Diff line number Diff line change
@@ -1 +1,26 @@
-- SQL-команды для создания таблиц
CREATE TABLE employees
(
employee_id serial PRIMARY KEY, -- Используется 'serial' для автоматического увеличения значения
first_name varchar(20) NOT NULL,
last_name varchar(40) NOT NULL,
title text,
birth_date DATE,
notes text
);

CREATE TABLE customers
(
customer_id CHAR(5) PRIMARY KEY, -- Устанавливается 'PRIMARY KEY'
company_name varchar(60),
contact_name varchar(70)
);

CREATE TABLE orders
(
order_id serial PRIMARY KEY, -- Используется 'serial' для автоматического увеличения значения
customer_id CHAR(5) REFERENCES customers(customer_id),
employee_id int REFERENCES employees(employee_id),
order_date DATE,
ship_city varchar(30)
);
29 changes: 29 additions & 0 deletions homework-1/main.py
Original file line number Diff line number Diff line change
@@ -1 +1,30 @@
import psycopg2
import csv


def open_csv_file(file):
with open(file, 'r') as csv_file:
csv_reader = csv.reader(csv_file)
data = list(csv_reader)
return data


employees = open_csv_file('north_data/employees_data.csv')
customers = open_csv_file('north_data/customers_data.csv')
orders = open_csv_file('north_data/orders_data.csv')

"""Скрипт для заполнения данными таблиц в БД Postgres."""

db_config = {
'dbname': 'north',
'user': 'postgres',
'password': '1975',
'host': 'localhost'
}

with psycopg2.connect(**db_config) as conn:
with conn.cursor() as cur:
cur.executemany("INSERT INTRO employees VALUES(%s, %s, %s, %s, %s, %s)", [i for i in employees])
cur.executemany("INSERT INTRO customers VALUES(%s, %s, %s)", [i for i in customers])
cur.executemany("INSERT INTRO orders VALUES(%s, %s, %s, %s, %s)", [i for i in orders])
conn.close()
12 changes: 12 additions & 0 deletions homework-4/alter_northwind.sql
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
-- Подключиться к БД Northwind и сделать следующие изменения:
-- 1. Добавить ограничение на поле unit_price таблицы products (цена должна быть больше 0)

ALTER TABLE products ADD CONSTRAINT chk_products_unit_price CHECK (unit_price > 0);

-- 2. Добавить ограничение, что поле discontinued таблицы products может содержать только значения 0 или 1

ALTER TABLE products ADD CONSTRAINT chk_products_discontinued CHECK (discontinued IN (0, 1));

-- 3. Создать новую таблицу, содержащую все продукты, снятые с продажи (discontinued = 1)

SELECT * INTO discontinued_products FROM products WHERE discontinued = 1;

-- 4. Удалить из products товары, снятые с продажи (discontinued = 1)
-- Для 4-го пункта может потребоваться удаление ограничения, связанного с foreign_key. Подумайте, как это можно решить, чтобы связь с таблицей order_details все же осталась.

ALTER TABLE products DROP CONSTRAINT fk_details_products;
-- новое ограничение с ON DELETE CASCADE
ALTER TABLE products
ADD CONSTRAINT fk_details_products
FOREIGN KEY (product_id)
REFERENCES products (product_id)
ON DELETE CASCADE;
DELETE FROM products WHERE discontinued = 1;
23 changes: 23 additions & 0 deletions homework-4/alter_student.sql
Original file line number Diff line number Diff line change
@@ -1,19 +1,42 @@
-- 1. Создать таблицу student с полями student_id serial, first_name varchar, last_name varchar, birthday date, phone varchar

CREATE TABLE student
(
student_id serial,
first_name varchar,
last_name varchar,
birthday date,
phone varchar
);


-- 2. Добавить в таблицу student колонку middle_name varchar

ALTER TABLE student ADD COLUMN middle_name varchar;

-- 3. Удалить колонку middle_name

ALTER TABLE student DROP COLUMN middle_name;


-- 4. Переименовать колонку birthday в birth_date

ALTER TABLE student RENAME birthday TO birth_date;


-- 5. Изменить тип данных колонки phone на varchar(32)

ALTER TABLE student ALTER COLUMN phone SET DATA TYPE varchar(32);


-- 6. Вставить три любых записи с автогенерацией идентификатора

INSERT INTO student (student_id, first_name, last_name, birth_date, phone)
VALUES
(1, 'Jon', 'Jayson', '1970.01.02', '456123'),
(2, 'Shay', 'Son', '1985.09.29', '789123'),
(3, 'Valentin', 'Ivanov', '1979.10.04', '789456');

-- 7. Удалить все данные из таблицы со сбросом идентификатор в исходное состояние

TRUNCATE TABLE student RESTART IDENTITY