根据Go结构体生成SQL语句的GO工具:sqlgen

jopen 9年前

sqlgen 能够从你的Go结构体生成SQL语句和数据库帮助类函数。它可以代替一个简单的ORM或手写SQL使用。

安装

Install or upgrade with this command:

go get -u github.com/drone/sqlgen

使用

Usage of sqlgen:    -type string          type to generate; required    -file string          input file name; required    -o string          output file name    -pkg string          output package name    -db string          sql dialect; sqlite, postgres, mysql    -schema          generate sql schema and queries; default true    -funcs          generate sql helper functions; default true

Tutorial

First, let's start with a simpleUserstruct inuser.go:

type User struct { ID int64 Login string Email string }

We can run the following command:

sqlgen -file user.go -type User -pkg demo

The tool outputs the following generated code:

func ScanUser(row *sql.Row) (*User, error) {      var v0 int64      var v1 string      var v2 string        err := row.Scan(          &v0,          &v1,          &v2,      )      if err != nil {          return nil, err      }        v := &User{}      v.ID = v0      v.Login = v1      v.Email = v2        return v, nil  }    const CreateUserStmt = `  CREATE TABLE IF NOT EXISTS users (   user_id     INTEGER  ,user_login  TEXT  ,user_email  TEXT  );  `    const SelectUserStmt = `  SELECT    user_id  ,user_login  ,user_email  FROM users   `    const SelectUserRangeStmt = `  SELECT    user_id  ,user_login  ,user_email  FROM users   LIMIT ? OFFSET ?  `      // more functions and sql statements not displayed

项目主页:http://www.open-open.com/lib/view/home/1442136607516