Inserting and selecting PostGIS Geometry with Gorm
小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《Inserting and selecting PostGIS Geometry with Gorm》,就很适合你,本篇文章讲解的知识点主要包括golang。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!
问题内容
I've been trying to find a way to insert and retrieve geometric types using Golang, and specifically the library gorm. I'm also attempting to use the library orb that defines different types for geometries, and provides encoding/decoding between different formats.
Orb has Scan()
and Value()
methods already implemented for each type. This
allows go's Insert()
and Scan()
functions to work with types other than
primitives. Orb expects however to be using geometry represented in the well-
known binary (WKB) format.
The orb documentation shows that to accomplish this, you should simply wrap
the field in the PostGIS functions ST_AsBinary()
and ST_GeomFromWKB()
for
querying and inserting respectively. For example, with a table defined as:
_, err = db.Exec(` CREATE TABLE IF NOT EXISTS orbtest ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, geom geometry(POLYGON, 4326) NOT NULL ); `)
You can just do:
rows, err := db.Query("SELECT id, name, ST_AsBinary(geom) FROM orbtest LIMIT 1")
And for insert (where p is an orb.Point):
db.Exec("INSERT INTO orbtest (id, name, geom) VALUES ($1, $2, ST_GeomFromWKB($3))", 1, "Test", wkb.Value(p))
Here's my issue: By using GORM, I don't have the luxury of being able to build
those queries with those functions. GORM will automatically insert values into
the database given a struct, and will scan in data into the whole hierarchy of
the struct. Those Scan()
and Value()
methods are called behind the scenes,
without my control.
Trying to directly insert binary data into a geometry column won't work, and directly querying a geometry column will give the result in hex.
I've tried multiple database approaches to solve this. I've attempted creating views that automatically call the needed functions on the geometry columns. This worked for querying, but not inserting.
Is it possible to make some sort of trigger or rule that would automatically call the needed functions on the data coming in/out?
I should also note that the library I'm working on works completely independent of the data and schemas, so I don't have the luxury of hard coding any sort of query. I could of course write a function that scans the entire data model, and generates queries from scratch, but I'd prefer if there was a better option.
Does anyone know of a way of making this work in SQL? Being able to call functions on a column automatically by just querying the column itself?
Any advice would be greatly appreciated.
正确答案
Another solution, which I ended up using was with go-
geos, as I discovered I needed to use
the GEOS C library. With that, I am able to convert the struct into WKT
for
inserting (as postgis accepts it as regular text) and convert from WKB
when
scanning.
type Geometry4326 *geos.Geometry // Value converts the given Geometry4326 struct into WKT such that it can be stored in a // database. Implements Valuer interface for use with database operations. func (g Geometry4326) Value() (driver.Value, error) { str, err := g.ToWKT() if err != nil { return nil, err } return "SRID=4326;" + str, nil } // Scan converts the hexadecimal representation of geometry into the given Geometry4326 // struct. Implements Scanner interface for use with database operations. func (g *Geometry4326) Scan(value interface{}) error { bytes, ok := value.([]byte) if !ok { return errors.New("cannot convert database value to geometry") } str := string(bytes) geom, err := geos.FromHex(str) if err != nil { return errors.Wrap(err, "cannot get geometry from hex") } geometry := Geometry4326(geom) *g = geometry return nil }
This solution might not be ideal for everyone as not everyone needs to use the GEOS C library, which can be a pain to get working on windows. I'm sure though that the same thing can be accomplished using different libraries.
I additionally implemented UnmarshalJSON()
and MarshalJSON()
on the struct
so that it can automatically Marshal/Unmarshal GeoJSON, and then save/get from
the database seamlessly. I accomplished this using geojson-
go to convert GeoJSON to/from a
struct, and then [geojson-geos-go](https://github.com/venicegeo/geojson-geos-
go) to convert said struct into the go-
geos struct I was using. A little
convoluted, yes, but it works.
今天关于《Inserting and selecting PostGIS Geometry with Gorm》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于golang的内容请关注golang学习网公众号!

- 上一篇
- 无法在现有服务器上使用 go tool pprof

- 下一篇
- 如何从 JWT 令牌中提取声明
-
- 奋斗的龙猫
- 这篇博文出现的刚刚好,细节满满,真优秀,收藏了,关注大佬了!希望大佬能多写Golang相关的文章。
- 2023-05-14 14:59:21
-
- 火星上的凉面
- 真优秀,一直没懂这个问题,但其实工作中常常有遇到...不过今天到这,帮助很大,总算是懂了,感谢楼主分享博文!
- 2023-05-14 02:14:07
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 478浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 511次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 498次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 千音漫语
- 千音漫语,北京熠声科技倾力打造的智能声音创作助手,提供AI配音、音视频翻译、语音识别、声音克隆等强大功能,助力有声书制作、视频创作、教育培训等领域,官网:https://qianyin123.com
- 151次使用
-
- MiniWork
- MiniWork是一款智能高效的AI工具平台,专为提升工作与学习效率而设计。整合文本处理、图像生成、营销策划及运营管理等多元AI工具,提供精准智能解决方案,让复杂工作简单高效。
- 143次使用
-
- NoCode
- NoCode (nocode.cn)是领先的无代码开发平台,通过拖放、AI对话等简单操作,助您快速创建各类应用、网站与管理系统。无需编程知识,轻松实现个人生活、商业经营、企业管理多场景需求,大幅降低开发门槛,高效低成本。
- 157次使用
-
- 达医智影
- 达医智影,阿里巴巴达摩院医疗AI创新力作。全球率先利用平扫CT实现“一扫多筛”,仅一次CT扫描即可高效识别多种癌症、急症及慢病,为疾病早期发现提供智能、精准的AI影像早筛解决方案。
- 150次使用
-
- 智慧芽Eureka
- 智慧芽Eureka,专为技术创新打造的AI Agent平台。深度理解专利、研发、生物医药、材料、科创等复杂场景,通过专家级AI Agent精准执行任务,智能化工作流解放70%生产力,让您专注核心创新。
- 159次使用
-
- 老师代码没有自动跟踪?
- 2023-03-07 439浏览
-
- c程序fork并等待golang进程状态
- 2023-03-05 262浏览
-
- GOLANG使用Context管理关联goroutine的方法
- 2022-12-28 193浏览
-
- 怎么用Golang将MySQL表转储为JSON
- 2023-03-07 188浏览
-
- Golang 检查字符串是否为有效路径?
- 2023-03-10 500浏览