Files
prog-solomov/works/kyrsach/avtoshkola-db.sql
T

181 lines
7.1 KiB
PL/PgSQL
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
-- Соломов Богдан
CREATE TABLE employees (
id bigserial PRIMARY KEY,
full_name varchar(150) NOT NULL,
login varchar(50) NOT NULL UNIQUE,
password varchar(100) NOT NULL,
role varchar(20) NOT NULL CHECK (role IN ('admin', 'instructor'))
);
CREATE TABLE categories (
id bigserial PRIMARY KEY,
code varchar(10) NOT NULL UNIQUE,
name varchar(150) NOT NULL,
price numeric(10, 2) NOT NULL CHECK (price > 0)
);
CREATE TABLE groups (
id bigserial PRIMARY KEY,
group_number varchar(20) NOT NULL UNIQUE,
category_id int8 NOT NULL REFERENCES categories(id) ON DELETE RESTRICT,
start_date date NOT NULL,
end_date date NOT NULL,
CHECK (end_date > start_date)
);
CREATE TABLE students (
id bigserial PRIMARY KEY,
full_name varchar(150) NOT NULL,
phone varchar(20) NOT NULL UNIQUE,
birth_date date NOT NULL,
group_id int8 NOT NULL REFERENCES groups(id) ON DELETE RESTRICT,
has_medical_cert boolean DEFAULT false NOT NULL
);
CREATE TABLE instructors (
id bigserial PRIMARY KEY,
employee_id int8 NOT NULL UNIQUE REFERENCES employees(id) ON DELETE CASCADE,
license_number varchar(20) NOT NULL UNIQUE,
experience_years int4 NOT NULL CHECK (experience_years >= 3)
);
CREATE TABLE cars (
id bigserial PRIMARY KEY,
brand_model varchar(100) NOT NULL,
plate_number varchar(20) NOT NULL UNIQUE,
transmission varchar(15) NOT NULL CHECK (transmission IN ('МКПП', 'АКПП')),
instructor_id int8 UNIQUE REFERENCES instructors(id) ON DELETE SET NULL
);
CREATE TABLE driving_lessons (
id bigserial PRIMARY KEY,
student_id int8 NOT NULL REFERENCES students(id) ON DELETE CASCADE,
instructor_id int8 NOT NULL REFERENCES instructors(id) ON DELETE RESTRICT,
lesson_date timestamp NOT NULL,
status varchar(20) DEFAULT 'Запланировано' NOT NULL
CHECK (status IN ('Запланировано', 'Проведено', 'Отменено'))
);
CREATE TABLE exams (
id bigserial PRIMARY KEY,
student_id int8 NOT NULL REFERENCES students(id) ON DELETE CASCADE,
exam_type varchar(20) NOT NULL CHECK (exam_type IN ('Теория', 'Автодром', 'Город')),
exam_date date NOT NULL,
is_passed boolean DEFAULT false NOT NULL
);
CREATE TABLE payments (
id bigserial PRIMARY KEY,
student_id int8 NOT NULL REFERENCES students(id) ON DELETE CASCADE,
method varchar(20) NOT NULL CHECK (method IN ('Карта', 'Наличные', 'Онлайн')),
status varchar(20) DEFAULT 'Ожидает' NOT NULL CHECK (status IN ('Ожидает', 'Оплачено', 'Возврат')),
amount numeric(10, 2) NOT NULL CHECK (amount >= 0),
paid_at timestamp NULL
);
-- Представление 1: полный список курсантов с группой, категорией и суммой оплаты
CREATE VIEW v_students_info AS
SELECT
s.id,
s.full_name,
s.phone,
g.group_number,
c.code AS category,
c.price AS course_price,
COALESCE(SUM(p.amount) FILTER (WHERE p.status = 'Оплачено'), 0) AS total_paid,
s.has_medical_cert
FROM students s
JOIN groups g ON s.group_id = g.id
JOIN categories c ON g.category_id = c.id
LEFT JOIN payments p ON p.student_id = s.id
GROUP BY s.id, s.full_name, s.phone, g.group_number, c.code, c.price, s.has_medical_cert;
-- Представление 2: расписание занятий с ФИО курсанта, инструктора и машиной
CREATE VIEW v_schedule AS
SELECT
dl.id,
dl.lesson_date,
s.full_name AS student_name,
e.full_name AS instructor_name,
car.brand_model || ' (' || car.plate_number || ')' AS car_info,
dl.status
FROM driving_lessons dl
JOIN students s ON dl.student_id = s.id
JOIN instructors i ON dl.instructor_id = i.id
JOIN employees e ON i.employee_id = e.id
LEFT JOIN cars car ON car.instructor_id = i.id;
-- Триггер: не пускать на вождение курсанта без медсправки
CREATE OR REPLACE FUNCTION check_medical_cert()
RETURNS TRIGGER AS $$
BEGIN
IF NOT (SELECT has_medical_cert FROM students WHERE id = NEW.student_id) THEN
RAISE EXCEPTION 'Курсант не допущен к вождению: отсутствует медицинская справка';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_check_medical_cert
BEFORE INSERT ON driving_lessons
FOR EACH ROW
EXECUTE FUNCTION check_medical_cert();
-- Функция: отметить занятие как проведённое по его ID
CREATE OR REPLACE FUNCTION complete_lesson(p_lesson_id int8)
RETURNS void AS $$
BEGIN
UPDATE driving_lessons
SET status = 'Проведено'
WHERE id = p_lesson_id;
END;
$$ LANGUAGE plpgsql;
-- Тестовые данные
INSERT INTO employees (full_name, login, password, role) VALUES
('Кузнецова Елена Павловна', 'admin', 'admin123', 'admin'),
('Петров Алексей Викторович', 'petrov', 'inst123', 'instructor'),
('Смирнов Денис Николаевич', 'smirnov', 'inst123', 'instructor');
INSERT INTO categories (code, name, price) VALUES
('A', 'Мотоциклы', 22000.00),
('B', 'Легковые автомобили', 38000.00),
('C', 'Грузовые автомобили', 45000.00);
INSERT INTO groups (group_number, category_id, start_date, end_date) VALUES
('Б-101', 2, '2026-09-01', '2026-12-15'),
('Б-102', 2, '2026-10-01', '2027-01-20'),
('А-201', 1, '2026-09-15', '2026-11-15');
INSERT INTO students (full_name, phone, birth_date, group_id, has_medical_cert) VALUES
('Чичков Артём Дмитриевич', '+79112345671', '2006-04-12', 1, true),
('Цепь Алина Сергеевна', '+79112345672', '2005-11-23', 1, true),
('Волк Никита Андреевич', '+79112345673', '2007-02-08', 1, false),
('Соломов Богдан Егорович', '+79245632356', '2007-11-15', 2, true);
INSERT INTO instructors (employee_id, license_number, experience_years) VALUES
(2, '7812345678', 12),
(3, '7887654321', 7);
INSERT INTO cars (brand_model, plate_number, transmission, instructor_id) VALUES
('Lada Priora', 'А123ВС178', 'МКПП', 1),
('Hyundai Solaris', 'К456МН178', 'АКПП', 2);
INSERT INTO driving_lessons (student_id, instructor_id, lesson_date, status) VALUES
(1, 1, '2026-10-10 10:00:00', 'Проведено'),
(1, 1, '2026-10-12 10:00:00', 'Проведено'),
(2, 2, '2026-10-11 14:00:00', 'Проведено'),
(4, 2, '2026-11-29 11:00:00', 'Запланировано');
INSERT INTO exams (student_id, exam_type, exam_date, is_passed) VALUES
(1, 'Теория', '2026-11-20', true),
(1, 'Автодром', '2026-11-25', true),
(2, 'Теория', '2026-11-20', true),
(2, 'Автодром', '2026-11-25', false);
INSERT INTO payments (student_id, method, status, amount, paid_at) VALUES
(1, 'Карта', 'Оплачено', 38000.00, '2026-09-02 15:30:00'),
(2, 'Онлайн', 'Оплачено', 19000.00, '2026-09-03 12:10:00'),
(2, 'Онлайн', 'Ожидает', 19000.00, NULL),
(4, 'Карта', 'Оплачено', 38000.00, '2026-10-01 11:45:00');