The post has been translated automatically. Original language: Russian
How to use Cursor to develop and design databases on Golang
Most developers use Cursor as a substitute for code completion. In practice, it is much more useful at the architecture and database design stage.
Recently, when developing a CRM and loyalty system, I decided to completely go through the design path through Cursor. Instead of drawing diagrams and writing dozens of models manually, I started with a simple text query.:
Design a loyalty system on Golang. Use PostgreSQL. We need companies, clients, bonus cards, and a history of bonus accruals and debits.
After that, Cursor suggested the structure of the database, the relationships between the tables, and explained which entities are best separated.
For example, the client model for GORM looked like this:
type Customer struct {
ID uint `gorm:"primaryKey"`
FullName string
Phone string `gorm:"uniqueIndex"`
CompanyID uint
Company Company
CreatedAt time.Time
}
And for the bonus card:
type LoyaltyCard struct {
ID uint `gorm:"primaryKey"`
CustomerID uint
Customer Customer
Balance int64
}
But the most interesting part starts next.
Instead of creating tables through AutoMigrate, I prefer to use migrations. This allows you to control changes in the database structure and safely roll out updates to production.
In Cursor, you can write:
Create a PostgreSQL migration for Customer and LoyaltyCard.
And get ready-made SQL:
CREATE TABLE customers (
id BIGSERIAL PRIMARY KEY,
full_name TEXT NOT NULL,
phone TEXT UNIQUE,
company_id BIGINT NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE loyalty_cards (
id BIGSERIAL PRIMARY KEY,
customer_id BIGINT NOT NULL REFERENCES customers(id),
balance BIGINT DEFAULT 0
);
After that, you can ask:
Add indexes for frequent customer searches by phone number and company.
Cursor will complement migration:
CREATE INDEX idx_customers_phone
ON customers(phone);
CREATE INDEX idx_customers_company
ON customers(company_id);
Another useful scenario is the analysis of an existing database.
For example, if you upload a project diagram and write:
Check the architecture of PostgreSQL and find potential problems.
Cursor often finds:
- missing indexes;
- unnecessary JOIN operations;
- communication errors;
- duplication of data;
- scaling issues as the number of records grows.
Then you can proceed to the generation of business logic.
For example:
Create CRUD for Customer via GORM.
And get ready-made methods:
func (r *Repository) CreateCustomer(
customer *Customer,
) error {
return r.db.Create(customer).Error
}
func (r *Repository) GetCustomer(
id uint,
) (*Customer, error) {
var customer Customer
err := r.db.
Preload("Company").
First(&customer, id).
Error
return &customer, err
}
As a result, Cursor helps not only to write code, but also to make architectural decisions. This is especially noticeable in Golang projects, where it is important to properly design the database structure, migrations, indexes, and relationships between entities even before active development begins.
For me, the most effective bundle today looks like this:
• Golang• PostgreSQL• GORM• Goose or golang-migrate• Cursor AI
This approach allows you to reduce the time for design and routine development several times, while maintaining control over the architecture of the project.
Are you already using Cursor when designing databases and backend services?
Как использовать Cursor для разработки и проектирования БД на Golang
Большинство разработчиков используют Cursor как замену автодополнению кода. На практике он гораздо полезнее на этапе проектирования архитектуры и базы данных.
Недавно при разработке CRM и системы лояльности я решил полностью пройти путь проектирования через Cursor. Вместо рисования схем и написания десятков моделей вручную я начал с обычного текстового запроса:
Спроектируй систему лояльности на Golang. Используй PostgreSQL. Нужны компании, клиенты, бонусные карты, история начислений и списаний бонусов.
После этого Cursor предложил структуру БД, связи между таблицами и объяснил, какие сущности лучше разделить.
Например, модель клиента для GORM выглядела так:
type Customer struct {
ID uint `gorm:"primaryKey"`
FullName string
Phone string `gorm:"uniqueIndex"`
CompanyID uint
Company Company
CreatedAt time.Time
}
А для бонусной карты:
type LoyaltyCard struct {
ID uint `gorm:"primaryKey"`
CustomerID uint
Customer Customer
Balance int64
}
Но самое интересное начинается дальше.
Вместо создания таблиц через AutoMigrate я предпочитаю использовать миграции. Это позволяет контролировать изменения структуры базы данных и безопасно выкатывать обновления на продакшн.
В Cursor можно написать:
Создай миграцию PostgreSQL для Customer и LoyaltyCard.
И получить готовый SQL:
CREATE TABLE customers (
id BIGSERIAL PRIMARY KEY,
full_name TEXT NOT NULL,
phone TEXT UNIQUE,
company_id BIGINT NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE loyalty_cards (
id BIGSERIAL PRIMARY KEY,
customer_id BIGINT NOT NULL REFERENCES customers(id),
balance BIGINT DEFAULT 0
);
После этого можно попросить:
Добавь индексы для частого поиска клиентов по номеру телефона и компании.
Cursor дополнит миграцию:
CREATE INDEX idx_customers_phone
ON customers(phone);
CREATE INDEX idx_customers_company
ON customers(company_id);
Еще один полезный сценарий — анализ существующей БД.
Например, если загрузить схему проекта и написать:
Проверь архитектуру PostgreSQL и найди потенциальные проблемы.
Cursor часто находит:
- отсутствующие индексы;
- лишние JOIN-операции;
- ошибки в связях;
- дублирование данных;
- проблемы масштабирования при росте количества записей.
Дальше можно перейти к генерации бизнес-логики.
Например:
Создай CRUD для Customer через GORM.
И получить готовые методы:
func (r *Repository) CreateCustomer(
customer *Customer,
) error {
return r.db.Create(customer).Error
}
func (r *Repository) GetCustomer(
id uint,
) (*Customer, error) {
var customer Customer
err := r.db.
Preload("Company").
First(&customer, id).
Error
return &customer, err
}
В результате Cursor помогает не только писать код, но и принимать архитектурные решения. Особенно это заметно в проектах на Golang, где важно правильно спроектировать структуру БД, миграции, индексы и связи между сущностями еще до начала активной разработки.
Для меня наиболее эффективная связка сегодня выглядит так:
• Golang• PostgreSQL• GORM• Goose или golang-migrate• Cursor AI
Такой подход позволяет сократить время на проектирование и рутинную разработку в несколько раз, сохранив контроль над архитектурой проекта.
А вы уже используете Cursor при проектировании баз данных и backend-сервисов?