-
Notifications
You must be signed in to change notification settings - Fork 0
Архитектура DB
- статус документа: формируется
- открытый вопрос: хранение учетных записей волонтёров
- добавить - таблицу сообщений пользователю
- Используемая СУБД - PostgresQL
- Имя базы данных - pet_shelter_bot
table dialog Таблица сообщений пользователю
Name | Type | Description |
---|---|---|
adopter_id | BIGINT | FK PRIMARY_KEY |
volunteer_id | BIGINT | NULLABLE |
queue_nb | TINYINT | ?MAYBE? |
Если запись в таблице для адоптера существует, то в подвале телеграма пользователя есть кнопка "завершить диалог" При вызове волонтера в таблица добавляется строка с адоптером, волонтер подтверждает начало диалога, и значение volunteer_id прописывается в строке с adopter_id => разговор счиается активным. При завершении диалога строка с adopter_id удаляется из таблицы, и удаляется кнопка "Завершить Диалог" у обоих собеседников.
table user_messages Таблица сообщений пользователю
Name | Type | Description |
---|---|---|
id | BIGINT | PRIMARY_KEY |
key | VARCHAR | //О чем сообщение ключ сообщения (особо актуален при мультиязыковой поддержке) |
message | CLOB | текст сообщения может быть большим |
table shelters Таблица шелтеров
Name | Type | Description |
---|---|---|
id | BIGINT | enum {CAT_SHELTER=0, DOG_SHELTER=1} |
name | VARCHAR | |
about | TEXT | о приюте |
schedule_and_address | TEXT | расписание работы приюта и адрес |
driving_directions | BLOB | схема проезда |
security_contacts | TEXT | контакты службы безопасности для оформления пропуска на машину |
safety_precautions | TEXT | техника безопасности на территории приюта |
Также опционально-вариативная информация посредством @Entity UserMessage
- Бот может выдать правила знакомства с животным до того, как забрать его из приюта.
- Бот может выдать список документов, необходимых для того, чтобы взять животное из приюта.
- Бот может выдать список рекомендаций по транспортировке животного.
- Бот может выдать список рекомендаций по обустройству дома для щенка/котенка.
- Бот может выдать список рекомендаций по обустройству дома для взрослого животного.
- Бот может выдать список рекомендаций по обустройству дома для животного с ограниченными возможностями (зрение, передвижение).
- Бот может выдать советы кинолога по первичному общению с собакой (неактуально для кошачьего приюта, реализовать только для приюта для собак).
table pets Таблица животных
Name | Type | Description |
---|---|---|
id | BIGINT | |
species | TINYINT | enum {CAT, DOG} NOT NULL |
name | VARCHAR | |
avatar | BLOB | a small size image |
disabled | BOOLEAN | true if the pet is with some kind of disabilities |
adoption_date | DATE | Date of adoption* could have the next values: |
-
Date of adoption could have the next values:
- null when the pet is in shelter or volunteer decided to cancel adopting trial;
- in the future when the pet is on trial;
- in the past when the pet is successfully adopted
прото-сущность для адоптера.
Исходя из того, что адоптеры для каждого из видов домашних животных хранятся
в отдельной таблицы, в нашем проекте есть таблицы cat_adopters и dog_adopters
Name | Type | Description |
---|---|---|
chat_id | BIGINT | Adopters are identified by their telegram chat id which is unique and persistent for a user contacting the bot |
name | VARCHAR | |
contacts | VARCHAR |
extends AbstractAdopter
table cat_adopters
Таблица адоптеров котов.
Сущность не содержит дополнительных полей к имеющимся в сущности AbstractAdopter.
Таблица котов и их адоптеров.
(скорее всего) Не предполагает наличие @Entity
Name | Type | Reference to | Description |
---|---|---|---|
cat_id | BIGINT | pets.id | PRIMARY KEY : конкретный кот может находиться только у одного адоптера |
cat_adopter_id | BIGINT | cat_adopters.chat_id | NOT NULL |
extends AbstractAdopter
table dog_adopters
Таблица адоптеров собак.
Сущность не содержит дополнительных полей к имеющимся в сущности AbstractAdopter.
Таблица собак и их адоптеров.
(скорее всего) Не предполагает наличие @Entity
Name | Type | Reference to | Description |
---|---|---|---|
dot_id | BIGINT | pets.id | PRIMARY KEY : конкретная собака может находиться только у одного адоптера |
dog_adopter_id | BIGINT | dog_adopters.chat_id | NOT NULL |
table reports Таблица отчетов пользователей
Name | Type | Reference to | Description |
---|---|---|---|
id | BIGINT | ||
pet_id | BIGINT | pets.id | |
receiving_time | TIMESTAMP | дата-время получения отчёта | |
photo_thumbnail | BLOB | photo preview | |
photo_file | VARCHAR | filename of the full-size photo | |
diet | VARCHAR | Рацион животного | |
accommodation | VARCHAR | Общее самочувствие и привыкание к новому месту | |
behaviour | VARCHAR | Изменение в поведении: отказ от старых привычек, приобретение новых |
Здесь я приведу мнение нашего эксперта относительно того, следует ли разделять сущности по видам деятельности, ими осуществляемых. Вот наш разговор с экспертом
[18:40, 04/07/2023] Serge.Gts: I'm developing database. There should be volunteers who manage customers of service. Both volunteers and customers are persons but they have different relations with other entities within database. Should I place volunteers and customers in the same table or it will be better to have two separate tables [18:41, 04/07/2023] : When designing a database, it is generally recommended to have separate tables for different entities that have distinct attributes and relationships. In your case, since volunteers and customers have different roles and relationships within the system, it would be more appropriate to have two separate tables.
By having separate tables for volunteers and customers, you can define specific attributes and relationships for each entity. This allows you to efficiently store and manage data related to volunteers and customers without mixing their information.
Here's a basic example of how you could structure your tables:
-
Volunteers Table:
- volunteer_id (Primary Key)
- volunteer_name
- volunteer_contact_info
- additional_volunteer_attributes
-
Customers Table:
- customer_id (Primary Key)
- customer_name
- customer_contact_info
- additional_customer_attributes
The specific attributes will depend on your requirements and the information you need to store for each entity. You can then establish relationships between these tables and other relevant tables in your database based on their interactions or any additional entities involved.
Separating volunteers and customers into different tables allows you to maintain data integrity, scalability, and enforce appropriate constraints and relationships within the database.
[18:43, 04/07/2023] Serge.Gts: thank u a lot [18:43, 04/07/2023] You're welcome! I'm glad I could help. If you have any more questions, feel free to ask. Good luck with your database development!
Also I asked him to act as the most experienced expert
[18:52, 04/07/2023] Certainly! As an experienced database expert, I would recommend following a slightly more advanced database design approach to handle the volunteers and customers entities.
To ensure a scalable and flexible database structure, I would suggest using a "supertype/subtype" design pattern, also known as inheritance or generalization/specialization. This pattern allows you to have a common supertype table that captures shared attributes between volunteers and customers, while also having separate subtype tables to handle the unique attributes and relationships for each entity.
Here's an example of how you could structure your tables using this approach:
-
Person (Supertype) Table:
- person_id (Primary Key)
- person_type (Volunteer or Customer)
- common_person_attributes (e.g., name, contact_info)
-
Volunteer (Subtype) Table:
- person_id (Foreign Key referencing Person.person_id)
- volunteer_specific_attributes
-
Customer (Subtype) Table:
- person_id (Foreign Key referencing Person.person_id)
- customer_specific_attributes
By introducing the supertype/subtype relationship, you can have a single "Person" table that captures shared attributes like name and contact information, while the subtype tables (Volunteer and Customer) store their respective specific attributes.
This approach allows for efficient querying and management of volunteers and customers while maintaining data integrity and flexibility. It also enables you to handle any future changes or additions to the volunteer and customer entities more easily.
Keep in mind that the specific attributes and relationships will depend on your requirements. You can establish additional tables to handle relationships with other entities, such as assignments, services, or schedules, as needed.
Implementing the supertype/subtype design pattern provides a more robust and extensible solution for managing volunteers and customers within your database.