2025-08-05 10:51:35 +08:00
|
|
|
package actions
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
2025-12-26 16:43:08 +08:00
|
|
|
"jhman/model"
|
2025-08-09 16:17:41 +08:00
|
|
|
|
|
|
|
|
"gorm.io/gorm"
|
2025-08-05 10:51:35 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func FindCities(tx *gorm.DB) ([]model.City, error) {
|
|
|
|
|
var cities []model.City
|
|
|
|
|
if err := tx.Find(&cities, "label is not null").Error; err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to find cities: %w", err)
|
|
|
|
|
}
|
|
|
|
|
return cities, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func FindCitiesWithEdgesCount(tx *gorm.DB) ([]model.City, error) {
|
2025-08-09 16:17:41 +08:00
|
|
|
var datas []struct {
|
|
|
|
|
model.City
|
|
|
|
|
EdgesCount int `gorm:"column:edges_count"`
|
|
|
|
|
}
|
2025-08-16 18:38:29 +08:00
|
|
|
err := tx.
|
2025-08-09 16:17:41 +08:00
|
|
|
Select("cityhash.*, COUNT(edge.id) AS edges_count").
|
|
|
|
|
Joins("LEFT JOIN edge ON edge.city_id = cityhash.id").
|
|
|
|
|
Where("cityhash.label IS NOT NULL").
|
|
|
|
|
Group("cityhash.id").
|
|
|
|
|
Find(&datas).Error
|
2025-08-05 10:51:35 +08:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to find cities with edges count: %w", err)
|
|
|
|
|
}
|
2025-08-09 16:17:41 +08:00
|
|
|
var cities = make([]model.City, len(datas))
|
|
|
|
|
for i, data := range datas {
|
|
|
|
|
cities[i] = data.City
|
|
|
|
|
cities[i].EdgesCount = data.EdgesCount
|
|
|
|
|
}
|
2025-08-05 10:51:35 +08:00
|
|
|
return cities, nil
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-10 18:26:59 +08:00
|
|
|
func UpdateCitiesOffset(tx *gorm.DB, updates []model.City) error {
|
|
|
|
|
if len(updates) == 0 {
|
|
|
|
|
return nil
|
2025-08-05 10:51:35 +08:00
|
|
|
}
|
|
|
|
|
|
2025-09-10 18:26:59 +08:00
|
|
|
for _, city := range updates {
|
|
|
|
|
err := tx.Model(new(model.City)).
|
|
|
|
|
Where("id = ?", city.Id).
|
|
|
|
|
Update("offset", city.Offset).Error
|
|
|
|
|
if err != nil {
|
|
|
|
|
return fmt.Errorf("failed to update city id %d offset: %w", city.Id, err)
|
|
|
|
|
}
|
2025-08-05 10:51:35 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|