SoFunction
Updated on 2025-03-05

xorm generates go model file according to the database

You know, it is boring to define a manual translation table to a go structure.

so, use xorm to do it.

go get /go-xorm/cmd/xorm

Install the following dependencies, which one is used to install which one is used.

/go-xorm/xorm

drive

Mysql: /go-sql-driver/mysql

Postgres: /lib/pq

SQLite: /mattn/go-sqlite3

MSSQL: /denisenkom/go-mssqldb

Reverse generation

The Reverse command can convert the database to the data structures of all supported languages. After installation, you can use xorm help reverse to view the help.

example:

cd $GOPATH/src//go-xorm/cmd/xorm
sqlite: xorm reverse sqite3  templates/goxorm
mysql: xorm reverse mysql root:root@/xorm_test?charset=utf8 templates/goxorm
mymysql: xorm reverse mymysql xorm_test2/root/ templates/goxorm
postgres: xorm reverse postgres "dbname=xorm_test sslmode=disable" templates/goxorm
mssql: xorm reverse mssql "server=test;user id=testid;password=testpwd;database=testdb" templates/goxorm

The go file will be generated in the ./model directory

pit

1. Be sure to run in the $GOPATH/src//go-xorm/cmd/xorm directory, because there are temples in this directory, which is useful when parsing the database structure. If you run it in another directory, the command will not report an error, but the corresponding structure file cannot be generated normally. If you have time, you can ask /go-xorm/cmd/xorm for a bug and add an error message.

2. Execute xorm reverse mysql root:[email protected]:3306/testdb?charset=utf8 templates/goxorm report error 2017/08/16 14:09:18 [Error] :176 default addr for network '127.0.0.1:3306' unknown

Solution:

xorm reverse mysql root:root@tcp(127.0.0.1:3306)/testdb?charset=utf8 templates/goxorm xorm reverse mysql root:root@tcp(127.0.0.1:3306)/testdb?charset=utf8 templates/goxorm

Added: "golang" xorm tool generates postgres model

The orm framework in golang generally uses xorm xorm tool to automatically generate struct files based on database tables.

xorm reverse postgres "dbname=queimsi sslmode=disable user=postgres password=123456 host=10.0.2.206 port=5432" /data/workspace/go/src//go-xorm/cmd/xorm/templates/goxorm

Then the struct file of the table will be automatically generated in the current directory

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.