Skip to content

Commit

Permalink
add query device record api, support geo query (#62)
Browse files Browse the repository at this point in the history
  • Loading branch information
huangzhiran authored Jan 13, 2025
1 parent 5db3f55 commit 7f2f621
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion db/device_record.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package db

import (
"fmt"

"github.com/pkg/errors"
"gorm.io/gorm"
)
Expand Down Expand Up @@ -30,8 +32,22 @@ type DeviceRecord struct {
func (*DeviceRecord) TableName() string { return "device_record" }

func (d *DB) QueryDeviceRecord(latitude, longitude string) (*DeviceRecord, error) {
sql := `SELECT device_record_id FROM device_record_geo_locations
WHERE ST_DWithin(
geom,
ST_MakePoint(%s, %s)::geography,
5000
);`

ids := []string{}
if err := d.db.Exec(fmt.Sprintf(sql, longitude, latitude)).Find(&ids).Error; err != nil {
return nil, errors.Wrap(err, "failed to query device record geo data")
}
if len(ids) == 0 {
return nil, nil
}
t := &DeviceRecord{}
if err := d.db.Where("latitude = ?", latitude).Where("longitude = ?", longitude).Order("timestamp DESC").First(&t).Error; err != nil {
if err := d.db.Where("id IN ?", ids).Order("timestamp DESC").First(&t).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, nil
}
Expand Down

0 comments on commit 7f2f621

Please sign in to comment.