├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── examples ├── bookstore │ ├── bookstore.go │ ├── sal_client.go │ └── sal_client_test.go └── profile │ ├── profile.go │ └── storage │ ├── client.go │ └── storage.go ├── go.mod ├── go.sum ├── looker ├── looker.go ├── looker_test.go ├── reflect.go ├── reflect_test.go └── testdata │ ├── foo-bar │ └── foo.go │ ├── interface.golden │ ├── package.golden │ ├── store_client.go │ └── testdata.go ├── sal.go ├── sal_test.go └── salgen ├── generator.go ├── generator_test.go └── main.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | .idea/ 15 | vendor/ -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: trusty 2 | sudo: false 3 | 4 | language: go 5 | go: [ "1.13" ] 6 | env: 7 | global: 8 | - PATH=$PATH:$HOME/gopath/bin 9 | 10 | script: 11 | - go test -race ./... 12 | 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Zaur Abasmirzoev 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # sal [![Build Status](https://travis-ci.org/go-gad/sal.svg?branch=master)](https://travis-ci.org/go-gad/sal) [![GoDoc](https://godoc.org/github.com/go-gad/sal?status.svg)](https://godoc.org/github.com/go-gad/sal) 2 | 3 | Generator client to the database on the Golang based on interface. 4 | 5 | ## Install 6 | 7 | ``` 8 | go get -u github.com/go-gad/sal/... 9 | ``` 10 | 11 | ## Usage 12 | 13 | Read article https://medium.com/@zaurio/generator-the-client-to-sql-database-on-golang-dccfeb4641c3 14 | 15 | ```sh 16 | salgen -h 17 | Usage: 18 | salgen [options...] 19 | 20 | Example: 21 | salgen -destination=./client.go -package=github.com/go-gad/sal/examples/profile/storage github.com/go-gad/sal/examples/profile/storage Store 22 | 23 | 24 | describes the complete package path where the interface is located. 25 | 26 | indicates the interface name itself. 27 | 28 | Options: 29 | -build_flags string 30 | Additional flags for go build. 31 | -destination string 32 | Output file; defaults to stdout. 33 | -package string 34 | The full import path of the library for the generated implementation 35 | ``` 36 | 37 | With go generate: 38 | ```go 39 | //go:generate salgen -destination=./client.go -package=github.com/go-gad/sal/examples/profile/storage github.com/go-gad/sal/examples/profile/storage Store 40 | type Store interface { 41 | CreateUser(ctx context.Context, req CreateUserReq) (*CreateUserResp, error) 42 | } 43 | 44 | type CreateUserReq struct { 45 | Name string `sql:"name"` 46 | Email string `sql:"email"` 47 | } 48 | 49 | func (r CreateUserReq) Query() string { 50 | return `INSERT INTO users(name, email, created_at) VALUES(@name, @email, now()) RETURNING id, created_at` 51 | } 52 | 53 | type CreateUserResp struct { 54 | ID int64 `sql:"id"` 55 | CreatedAt time.Time `sql:"created_at"` 56 | } 57 | ``` 58 | 59 | In your project run command 60 | ``` 61 | $ go generate ./... 62 | ``` 63 | File `client.go` will be generated. 64 | 65 | ## Command line args and options 66 | 67 | * flag `-destination` determines in which file the generated code will be written. 68 | * flag `-package` is the full import path of the library for the generated implementation. 69 | * first arg describes the complete package path where the interface is located. 70 | * second indicates the interface name itself. 71 | 72 | ## Possible definitions of methods 73 | 74 | ```go 75 | type Store interface { 76 | CreateAuthor(ctx context.Context, req CreateAuthorReq) (CreateAuthorResp, error) 77 | GetAuthors(ctx context.Context, req GetAuthorsReq) ([]*GetAuthorsResp, error) 78 | UpdateAuthor(ctx context.Context, req *UpdateAuthorReq) error 79 | DeleteAuthors(ctx context.Context, req *DeleteAuthorsReq) (sql.Result, error) 80 | } 81 | ``` 82 | 83 | * The number of arguments is always strictly two. 84 | * The first argument is the context. 85 | * The second argument contains the data to bind the variables and defines the query string. 86 | * The first output parameter can be an object, an array of objects, `sql.Result` or missing. 87 | * Last output parameter is always an error. 88 | 89 | The second argument expects a parameter with a base type of `struct` (or a pointer to a `struct`). The parameter must satisfy the following interface: 90 | ```go 91 | type Queryer interface { 92 | Query() string 93 | } 94 | ``` 95 | The string returned by method `Query` is used as a SQL query. 96 | 97 | ## Prepared statements 98 | 99 | The generated code supports prepared statements. 100 | Prepared statements are cached. 101 | After the first preparation of the statement, it is placed in the cache. 102 | The `database/sql` library itself ensures 103 | that prepared statements are transparently applied to the desired database connection, 104 | including the processing of closed connections. 105 | In turn, the `go-gad/sal` library cares about reusing the prepared statement 106 | in the context of a transaction. 107 | When the prepared statement is executed, the arguments are passed using variable binding, 108 | transparently to the developer. 109 | 110 | ## Map structs to response messages 111 | 112 | The `go-gad/sal` library cares about linking database response lines with response structures, table columns with structure fields: 113 | ```go 114 | type GetRubricsReq struct {} 115 | func (r GetRubricReq) Query() string { 116 | return `SELECT * FROM rubrics` 117 | } 118 | 119 | type Rubric struct { 120 | ID int64 `sql:"id"` 121 | CreateAt time.Time `sql:"created_at"` 122 | Title string `sql:"title"` 123 | } 124 | type GetRubricsResp []*Rubric 125 | 126 | type Store interface { 127 | GetRubrics(ctx context.Context, req GetRubricsReq) (GetRubricsResp, error) 128 | } 129 | ``` 130 | And if the database response is: 131 | ```sql 132 | dev > SELECT * FROM rubrics; 133 | id | created_at | title 134 | ----+-------------------------+------- 135 | 1 | 2012-03-13 11:17:23.609 | Tech 136 | 2 | 2015-07-21 18:05:43.412 | Style 137 | (2 rows) 138 | ``` 139 | Then the `GetRubricsResp` list will return to us, 140 | elements of which will be pointers to `Rubric`, 141 | where the fields are filled with values from the columns that correspond to the names of the tags. 142 | 143 | Unmapped columns will be skipped if database response contains more fields than defined in the structure. 144 | 145 | ## Value `in` list 146 | 147 | ```go 148 | type GetIDsReq struct { 149 | IDs pq.StringArray `sql:"ids"` 150 | } 151 | 152 | func (r *GetIDsReq) Query() string { 153 | return `SELECT * FROM rubrics WHERE id = ANY(@ids)` 154 | } 155 | ``` 156 | 157 | ## Multiple insert/update 158 | 159 | ```go 160 | type AddBooksToShelfReq struct { 161 | ShelfID int64 `sql:"shelf_id"` 162 | BookID pq.Int64Array `sql:"book_ids"` 163 | } 164 | 165 | func (c *AddBooksToShelfReq) Query() string { 166 | return `INSERT INTO shelf (shelf_id, book_id) 167 | SELECT @shelf_id, unnest(@book_ids);` 168 | } 169 | ``` 170 | 171 | ## Non-standard data types 172 | 173 | The `database/sql` package provides support for basic data types (strings, numbers). 174 | In order to handle data types such as an `array` or `json` in a request or response. 175 | 176 | ```go 177 | type DeleteAuthrosReq struct { 178 | Tags []int64 `sql:"tags"` 179 | } 180 | 181 | func (r *DeleteAuthorsReq) ProcessRow(rowMap sal.RowMap) { 182 | rowMap.Set("tags", pq.Array(r.Tags)) 183 | } 184 | 185 | func (r *DeleteAuthorsReq) Query() string { 186 | return `DELETE FROM authors WHERE tags=ANY(@tags::UUID[])` 187 | } 188 | ``` 189 | 190 | The same can be done with `sql` package predefined types 191 | 192 | ```go 193 | type DeleteAuthrosReq struct { 194 | Tags sql.Int64Array `sql:"tags"` 195 | } 196 | 197 | func (r *DeleteAuthorsReq) Query() string { 198 | return `DELETE FROM authors WHERE tags=ANY(@tags::UUID[])` 199 | } 200 | ``` 201 | 202 | ## Nested types 203 | 204 | Here we don't use struct tages because we map it in ProcessRow func to prevent misunderstanding for the same field names (`id` and `name` for `Book` and `Author` types) 205 | ```go 206 | type Author struct { 207 | ID int64 208 | Name string 209 | } 210 | 211 | type Book struct { 212 | ID int64 213 | Name string 214 | Description string 215 | Author Author 216 | } 217 | type CreateBookReq struct { 218 | Book Book 219 | } 220 | 221 | func (r *CreateBookReq) ProcessRow(rowMap sal.RowMap) { 222 | rowMap.Set("author_id", r.Book.Author.ID) 223 | rowMap.Set("book_id", r.Book.ID) 224 | rowMap.Set("book_name", r.Book.Name) 225 | rowMap.Set("book_descriprion", r.Book.Description) 226 | } 227 | 228 | func (r *CreateBookReq) Query() string { 229 | return `INSERT INTO books (id, author_id, name, description) 230 | VALUES (@book_id, @author_id, @book_name, @book_description)` 231 | } 232 | ``` 233 | 234 | ## Transactions 235 | 236 | To support transactions, the interface (Store) must be extended with the following methods: 237 | ```go 238 | type Store interface { 239 | BeginTx(ctx context.Context, opts *sql.TxOptions) (Store, error) 240 | sal.Txer 241 | ... 242 | ``` 243 | 244 | The implementation of the methods will be generated. The `BeginTx` method uses the connection from the current `sal.QueryHandler` object and opens the transaction `db.BeginTx(...)`; returns a new implementation object of the interface `Store`, but uses the resulting `*sql.Tx` object as a handle. 245 | 246 | ```go 247 | tx, err := client.BeginTx(ctx, nil) 248 | _, err = tx.CreateAuthor(ctx, req1) 249 | err = tx.UpdateAuthor(ctx, &req2) 250 | err = tx.Tx().Commit(ctx) 251 | ``` 252 | 253 | ## Middleware 254 | 255 | Hooks are provided for embedding tools. 256 | 257 | When the hooks are executed, the context is filled with service keys with the following values: 258 | * `ctx.Value(sal.ContextKeyTxOpened)`, boolean indicates whether the method is called in the context of a transaction or not. 259 | * `ctx.Value(sal.ContextKeyOperationType)`, the string value of the operation type, `"QueryRow"`, `"Query"`, `"Exec"`, `"Commit"`, etc. 260 | * `ctx.Value(sal.ContextKeyMethodName)`, the string value of the interface method, for example, `"GetAuthors"`. 261 | 262 | As arguments, the `BeforeQueryFunc` hook takes the sql string of the query and the argument `req` of the custom query method. The `FinalizerFunc` hook takes the variable` err` as an argument. 263 | 264 | ```go 265 | beforeHook := func(ctx context.Context, query string, req interface{}) (context.Context, sal.FinalizerFunc) { 266 | start := time.Now() 267 | return ctx, func(ctx context.Context, err error) { 268 | log.Printf( 269 | "%q > Opeartion %q: %q with req %#v took [%v] inTx[%v] Error: %+v", 270 | ctx.Value(sal.ContextKeyMethodName), 271 | ctx.Value(sal.ContextKeyOperationType), 272 | query, 273 | req, 274 | time.Since(start), 275 | ctx.Value(sal.ContextKeyTxOpened), 276 | err, 277 | ) 278 | } 279 | } 280 | 281 | client := NewStore(db, sal.BeforeQuery(beforeHook)) 282 | ``` 283 | 284 | ## Limitations 285 | 286 | Currently support only PostgreSQL. 287 | -------------------------------------------------------------------------------- /examples/bookstore/bookstore.go: -------------------------------------------------------------------------------- 1 | package bookstore 2 | 3 | import ( 4 | "context" 5 | "database/sql" 6 | "time" 7 | 8 | "github.com/go-gad/sal" 9 | "github.com/lib/pq" 10 | ) 11 | 12 | //go:generate salgen -destination=./sal_client.go -package=github.com/go-gad/sal/examples/bookstore github.com/go-gad/sal/examples/bookstore Store 13 | type Store interface { 14 | BeginTx(ctx context.Context, opts *sql.TxOptions) (Store, error) 15 | sal.Txer 16 | 17 | CreateAuthor(context.Context, CreateAuthorReq) (CreateAuthorResp, error) 18 | CreateAuthorPtr(context.Context, CreateAuthorReq) (*CreateAuthorResp, error) 19 | GetAuthors(context.Context, GetAuthorsReq) ([]*GetAuthorsResp, error) 20 | UpdateAuthor(context.Context, *UpdateAuthorReq) error 21 | UpdateAuthorResult(context.Context, *UpdateAuthorReq) (sql.Result, error) 22 | SameName(context.Context, SameNameReq) (*SameNameResp, error) 23 | GetBooks(context.Context, GetBooksReq) ([]*GetBooksResp, error) 24 | } 25 | 26 | type BaseAuthor struct { 27 | Name string 28 | Desc string 29 | } 30 | 31 | type CreateAuthorReq struct { 32 | BaseAuthor 33 | } 34 | 35 | func (cr *CreateAuthorReq) Query() string { 36 | return `INSERT INTO authors (Name, Desc, CreatedAt) VALUES(@Name, @Desc, now()) RETURNING ID, CreatedAt` 37 | } 38 | 39 | type CreateAuthorResp struct { 40 | ID int64 41 | CreatedAt time.Time 42 | } 43 | 44 | type Tags struct { 45 | Tags []int64 `sql:"tags"` 46 | } 47 | 48 | type GetAuthorsReq struct { 49 | ID int64 `sql:"id"` 50 | Tags 51 | } 52 | 53 | func (r GetAuthorsReq) ProcessRow(rowMap sal.RowMap) { 54 | rowMap.Set("tags", pq.Array(r.Tags.Tags)) 55 | } 56 | 57 | func (r *GetAuthorsReq) Query() string { 58 | return `SELECT id, created_at, name, desc, tags FROM authors WHERE id>@id AND tags @> @tags` 59 | } 60 | 61 | type GetAuthorsResp struct { 62 | ID int64 `sql:"id"` 63 | CreatedAt time.Time `sql:"created_at"` 64 | Name string `sql:"name"` 65 | Desc string `sql:"desc"` 66 | Tags 67 | } 68 | 69 | func (r *GetAuthorsResp) ProcessRow(rowMap sal.RowMap) { 70 | rowMap.Set("tags", pq.Array(&r.Tags.Tags)) 71 | } 72 | 73 | type UpdateAuthorReq struct { 74 | ID int64 75 | BaseAuthor 76 | } 77 | 78 | func (r *UpdateAuthorReq) Query() string { 79 | return `UPDATE authors SET Name=@Name, Desc=@Desc WHERE ID=@ID` 80 | } 81 | 82 | type SameNameReq struct{} 83 | 84 | func (r SameNameReq) Query() string { 85 | return `SELECT * FROM names LIMIT 1` 86 | } 87 | 88 | type SameNameResp struct { 89 | Bar string 90 | Foo 91 | } 92 | 93 | type Foo struct { 94 | Bar string 95 | } 96 | 97 | type GetBooksReq struct{} 98 | 99 | func (r *GetBooksReq) Query() string { 100 | return `SELECT * FROM books` 101 | } 102 | 103 | type GetBooksResp struct { 104 | ID int64 `sql:"id"` 105 | Title string `sql:"title"` 106 | } 107 | -------------------------------------------------------------------------------- /examples/bookstore/sal_client.go: -------------------------------------------------------------------------------- 1 | // Code generated by SalGen. DO NOT EDIT. 2 | package bookstore 3 | 4 | import ( 5 | "context" 6 | "database/sql" 7 | "github.com/go-gad/sal" 8 | "github.com/pkg/errors" 9 | ) 10 | 11 | type SalStore struct { 12 | Store 13 | handler sal.QueryHandler 14 | parent sal.QueryHandler 15 | ctrl *sal.Controller 16 | txOpened bool 17 | } 18 | 19 | func NewStore(h sal.QueryHandler, options ...sal.ClientOption) *SalStore { 20 | s := &SalStore{ 21 | handler: h, 22 | ctrl: sal.NewController(options...), 23 | txOpened: false, 24 | } 25 | 26 | return s 27 | } 28 | 29 | func (s *SalStore) BeginTx(ctx context.Context, opts *sql.TxOptions) (Store, error) { 30 | dbConn, ok := s.handler.(sal.TransactionBegin) 31 | if !ok { 32 | return nil, errors.New("handler doesn't satisfy the interface TransactionBegin") 33 | } 34 | var ( 35 | err error 36 | tx *sql.Tx 37 | ) 38 | 39 | ctx = context.WithValue(ctx, sal.ContextKeyTxOpened, s.txOpened) 40 | ctx = context.WithValue(ctx, sal.ContextKeyOperationType, "Begin") 41 | ctx = context.WithValue(ctx, sal.ContextKeyMethodName, "BeginTx") 42 | 43 | for _, fn := range s.ctrl.BeforeQuery { 44 | var fnz sal.FinalizerFunc 45 | ctx, fnz = fn(ctx, "BEGIN", nil) 46 | if fnz != nil { 47 | defer func() { fnz(ctx, err) }() 48 | } 49 | } 50 | 51 | tx, err = dbConn.BeginTx(ctx, opts) 52 | if err != nil { 53 | err = errors.Wrap(err, "failed to start tx") 54 | return nil, err 55 | } 56 | 57 | newClient := &SalStore{ 58 | handler: tx, 59 | parent: s.handler, 60 | ctrl: s.ctrl, 61 | txOpened: true, 62 | } 63 | 64 | return newClient, nil 65 | } 66 | 67 | func (s *SalStore) Tx() sal.Transaction { 68 | if tx, ok := s.handler.(sal.SqlTx); ok { 69 | return sal.NewWrappedTx(tx, s.ctrl) 70 | } 71 | return nil 72 | } 73 | 74 | func (s *SalStore) CreateAuthor(ctx context.Context, req CreateAuthorReq) (CreateAuthorResp, error) { 75 | var ( 76 | err error 77 | rawQuery = req.Query() 78 | reqMap = make(sal.RowMap) 79 | ) 80 | reqMap.AppendTo("Name", &req.BaseAuthor.Name) 81 | reqMap.AppendTo("Desc", &req.BaseAuthor.Desc) 82 | 83 | ctx = context.WithValue(ctx, sal.ContextKeyTxOpened, s.txOpened) 84 | ctx = context.WithValue(ctx, sal.ContextKeyOperationType, "QueryRow") 85 | ctx = context.WithValue(ctx, sal.ContextKeyMethodName, "CreateAuthor") 86 | 87 | pgQuery, args := sal.ProcessQueryAndArgs(rawQuery, reqMap) 88 | 89 | stmt, err := s.ctrl.PrepareStmt(ctx, s.parent, s.handler, pgQuery) 90 | if err != nil { 91 | return CreateAuthorResp{}, errors.WithStack(err) 92 | } 93 | 94 | for _, fn := range s.ctrl.BeforeQuery { 95 | var fnz sal.FinalizerFunc 96 | ctx, fnz = fn(ctx, rawQuery, req) 97 | if fnz != nil { 98 | defer func() { fnz(ctx, err) }() 99 | } 100 | } 101 | 102 | rows, err := stmt.QueryContext(ctx, args...) 103 | if err != nil { 104 | return CreateAuthorResp{}, errors.Wrap(err, "failed to execute Query") 105 | } 106 | defer rows.Close() 107 | 108 | cols, err := rows.Columns() 109 | if err != nil { 110 | return CreateAuthorResp{}, errors.Wrap(err, "failed to fetch columns") 111 | } 112 | 113 | if !rows.Next() { 114 | if err = rows.Err(); err != nil { 115 | return CreateAuthorResp{}, errors.Wrap(err, "rows error") 116 | } 117 | return CreateAuthorResp{}, sql.ErrNoRows 118 | } 119 | 120 | var resp CreateAuthorResp 121 | var respMap = make(sal.RowMap) 122 | respMap.AppendTo("ID", &resp.ID) 123 | respMap.AppendTo("CreatedAt", &resp.CreatedAt) 124 | 125 | dest := sal.GetDests(cols, respMap) 126 | 127 | if err = rows.Scan(dest...); err != nil { 128 | return CreateAuthorResp{}, errors.Wrap(err, "failed to scan row") 129 | } 130 | 131 | if err = rows.Err(); err != nil { 132 | return CreateAuthorResp{}, errors.Wrap(err, "something failed during iteration") 133 | } 134 | 135 | return resp, nil 136 | } 137 | 138 | func (s *SalStore) CreateAuthorPtr(ctx context.Context, req CreateAuthorReq) (*CreateAuthorResp, error) { 139 | var ( 140 | err error 141 | rawQuery = req.Query() 142 | reqMap = make(sal.RowMap) 143 | ) 144 | reqMap.AppendTo("Name", &req.BaseAuthor.Name) 145 | reqMap.AppendTo("Desc", &req.BaseAuthor.Desc) 146 | 147 | ctx = context.WithValue(ctx, sal.ContextKeyTxOpened, s.txOpened) 148 | ctx = context.WithValue(ctx, sal.ContextKeyOperationType, "QueryRow") 149 | ctx = context.WithValue(ctx, sal.ContextKeyMethodName, "CreateAuthorPtr") 150 | 151 | pgQuery, args := sal.ProcessQueryAndArgs(rawQuery, reqMap) 152 | 153 | stmt, err := s.ctrl.PrepareStmt(ctx, s.parent, s.handler, pgQuery) 154 | if err != nil { 155 | return nil, errors.WithStack(err) 156 | } 157 | 158 | for _, fn := range s.ctrl.BeforeQuery { 159 | var fnz sal.FinalizerFunc 160 | ctx, fnz = fn(ctx, rawQuery, req) 161 | if fnz != nil { 162 | defer func() { fnz(ctx, err) }() 163 | } 164 | } 165 | 166 | rows, err := stmt.QueryContext(ctx, args...) 167 | if err != nil { 168 | return nil, errors.Wrap(err, "failed to execute Query") 169 | } 170 | defer rows.Close() 171 | 172 | cols, err := rows.Columns() 173 | if err != nil { 174 | return nil, errors.Wrap(err, "failed to fetch columns") 175 | } 176 | 177 | if !rows.Next() { 178 | if err = rows.Err(); err != nil { 179 | return nil, errors.Wrap(err, "rows error") 180 | } 181 | return nil, sql.ErrNoRows 182 | } 183 | 184 | var resp CreateAuthorResp 185 | var respMap = make(sal.RowMap) 186 | respMap.AppendTo("ID", &resp.ID) 187 | respMap.AppendTo("CreatedAt", &resp.CreatedAt) 188 | 189 | dest := sal.GetDests(cols, respMap) 190 | 191 | if err = rows.Scan(dest...); err != nil { 192 | return nil, errors.Wrap(err, "failed to scan row") 193 | } 194 | 195 | if err = rows.Err(); err != nil { 196 | return nil, errors.Wrap(err, "something failed during iteration") 197 | } 198 | 199 | return &resp, nil 200 | } 201 | 202 | func (s *SalStore) GetAuthors(ctx context.Context, req GetAuthorsReq) ([]*GetAuthorsResp, error) { 203 | var ( 204 | err error 205 | rawQuery = req.Query() 206 | reqMap = make(sal.RowMap) 207 | ) 208 | reqMap.AppendTo("id", &req.ID) 209 | reqMap.AppendTo("tags", &req.Tags.Tags) 210 | 211 | req.ProcessRow(reqMap) 212 | 213 | ctx = context.WithValue(ctx, sal.ContextKeyTxOpened, s.txOpened) 214 | ctx = context.WithValue(ctx, sal.ContextKeyOperationType, "Query") 215 | ctx = context.WithValue(ctx, sal.ContextKeyMethodName, "GetAuthors") 216 | 217 | pgQuery, args := sal.ProcessQueryAndArgs(rawQuery, reqMap) 218 | 219 | stmt, err := s.ctrl.PrepareStmt(ctx, s.parent, s.handler, pgQuery) 220 | if err != nil { 221 | return nil, errors.WithStack(err) 222 | } 223 | 224 | for _, fn := range s.ctrl.BeforeQuery { 225 | var fnz sal.FinalizerFunc 226 | ctx, fnz = fn(ctx, rawQuery, req) 227 | if fnz != nil { 228 | defer func() { fnz(ctx, err) }() 229 | } 230 | } 231 | 232 | rows, err := stmt.QueryContext(ctx, args...) 233 | if err != nil { 234 | return nil, errors.Wrap(err, "failed to execute Query") 235 | } 236 | defer rows.Close() 237 | 238 | cols, err := rows.Columns() 239 | if err != nil { 240 | return nil, errors.Wrap(err, "failed to fetch columns") 241 | } 242 | 243 | var list = make([]*GetAuthorsResp, 0) 244 | 245 | for rows.Next() { 246 | var resp GetAuthorsResp 247 | var respMap = make(sal.RowMap) 248 | respMap.AppendTo("id", &resp.ID) 249 | respMap.AppendTo("created_at", &resp.CreatedAt) 250 | respMap.AppendTo("name", &resp.Name) 251 | respMap.AppendTo("desc", &resp.Desc) 252 | respMap.AppendTo("tags", &resp.Tags.Tags) 253 | 254 | resp.ProcessRow(respMap) 255 | 256 | dest := sal.GetDests(cols, respMap) 257 | 258 | if err = rows.Scan(dest...); err != nil { 259 | return nil, errors.Wrap(err, "failed to scan row") 260 | } 261 | 262 | list = append(list, &resp) 263 | } 264 | 265 | if err = rows.Err(); err != nil { 266 | return nil, errors.Wrap(err, "something failed during iteration") 267 | } 268 | 269 | return list, nil 270 | } 271 | 272 | func (s *SalStore) GetBooks(ctx context.Context, req GetBooksReq) ([]*GetBooksResp, error) { 273 | var ( 274 | err error 275 | rawQuery = req.Query() 276 | reqMap = make(sal.RowMap) 277 | ) 278 | 279 | ctx = context.WithValue(ctx, sal.ContextKeyTxOpened, s.txOpened) 280 | ctx = context.WithValue(ctx, sal.ContextKeyOperationType, "Query") 281 | ctx = context.WithValue(ctx, sal.ContextKeyMethodName, "GetBooks") 282 | 283 | pgQuery, args := sal.ProcessQueryAndArgs(rawQuery, reqMap) 284 | 285 | stmt, err := s.ctrl.PrepareStmt(ctx, s.parent, s.handler, pgQuery) 286 | if err != nil { 287 | return nil, errors.WithStack(err) 288 | } 289 | 290 | for _, fn := range s.ctrl.BeforeQuery { 291 | var fnz sal.FinalizerFunc 292 | ctx, fnz = fn(ctx, rawQuery, req) 293 | if fnz != nil { 294 | defer func() { fnz(ctx, err) }() 295 | } 296 | } 297 | 298 | rows, err := stmt.QueryContext(ctx, args...) 299 | if err != nil { 300 | return nil, errors.Wrap(err, "failed to execute Query") 301 | } 302 | defer rows.Close() 303 | 304 | cols, err := rows.Columns() 305 | if err != nil { 306 | return nil, errors.Wrap(err, "failed to fetch columns") 307 | } 308 | 309 | var list = make([]*GetBooksResp, 0) 310 | 311 | for rows.Next() { 312 | var resp GetBooksResp 313 | var respMap = make(sal.RowMap) 314 | respMap.AppendTo("id", &resp.ID) 315 | respMap.AppendTo("title", &resp.Title) 316 | 317 | dest := sal.GetDests(cols, respMap) 318 | 319 | if err = rows.Scan(dest...); err != nil { 320 | return nil, errors.Wrap(err, "failed to scan row") 321 | } 322 | 323 | list = append(list, &resp) 324 | } 325 | 326 | if err = rows.Err(); err != nil { 327 | return nil, errors.Wrap(err, "something failed during iteration") 328 | } 329 | 330 | return list, nil 331 | } 332 | 333 | func (s *SalStore) SameName(ctx context.Context, req SameNameReq) (*SameNameResp, error) { 334 | var ( 335 | err error 336 | rawQuery = req.Query() 337 | reqMap = make(sal.RowMap) 338 | ) 339 | 340 | ctx = context.WithValue(ctx, sal.ContextKeyTxOpened, s.txOpened) 341 | ctx = context.WithValue(ctx, sal.ContextKeyOperationType, "QueryRow") 342 | ctx = context.WithValue(ctx, sal.ContextKeyMethodName, "SameName") 343 | 344 | pgQuery, args := sal.ProcessQueryAndArgs(rawQuery, reqMap) 345 | 346 | stmt, err := s.ctrl.PrepareStmt(ctx, s.parent, s.handler, pgQuery) 347 | if err != nil { 348 | return nil, errors.WithStack(err) 349 | } 350 | 351 | for _, fn := range s.ctrl.BeforeQuery { 352 | var fnz sal.FinalizerFunc 353 | ctx, fnz = fn(ctx, rawQuery, req) 354 | if fnz != nil { 355 | defer func() { fnz(ctx, err) }() 356 | } 357 | } 358 | 359 | rows, err := stmt.QueryContext(ctx, args...) 360 | if err != nil { 361 | return nil, errors.Wrap(err, "failed to execute Query") 362 | } 363 | defer rows.Close() 364 | 365 | cols, err := rows.Columns() 366 | if err != nil { 367 | return nil, errors.Wrap(err, "failed to fetch columns") 368 | } 369 | 370 | if !rows.Next() { 371 | if err = rows.Err(); err != nil { 372 | return nil, errors.Wrap(err, "rows error") 373 | } 374 | return nil, sql.ErrNoRows 375 | } 376 | 377 | var resp SameNameResp 378 | var respMap = make(sal.RowMap) 379 | respMap.AppendTo("Bar", &resp.Bar) 380 | respMap.AppendTo("Bar", &resp.Foo.Bar) 381 | 382 | dest := sal.GetDests(cols, respMap) 383 | 384 | if err = rows.Scan(dest...); err != nil { 385 | return nil, errors.Wrap(err, "failed to scan row") 386 | } 387 | 388 | if err = rows.Err(); err != nil { 389 | return nil, errors.Wrap(err, "something failed during iteration") 390 | } 391 | 392 | return &resp, nil 393 | } 394 | 395 | func (s *SalStore) UpdateAuthor(ctx context.Context, req *UpdateAuthorReq) error { 396 | var ( 397 | err error 398 | rawQuery = req.Query() 399 | reqMap = make(sal.RowMap) 400 | ) 401 | reqMap.AppendTo("ID", &req.ID) 402 | reqMap.AppendTo("Name", &req.BaseAuthor.Name) 403 | reqMap.AppendTo("Desc", &req.BaseAuthor.Desc) 404 | 405 | ctx = context.WithValue(ctx, sal.ContextKeyTxOpened, s.txOpened) 406 | ctx = context.WithValue(ctx, sal.ContextKeyOperationType, "Exec") 407 | ctx = context.WithValue(ctx, sal.ContextKeyMethodName, "UpdateAuthor") 408 | 409 | pgQuery, args := sal.ProcessQueryAndArgs(rawQuery, reqMap) 410 | 411 | stmt, err := s.ctrl.PrepareStmt(ctx, s.parent, s.handler, pgQuery) 412 | if err != nil { 413 | return errors.WithStack(err) 414 | } 415 | 416 | for _, fn := range s.ctrl.BeforeQuery { 417 | var fnz sal.FinalizerFunc 418 | ctx, fnz = fn(ctx, rawQuery, req) 419 | if fnz != nil { 420 | defer func() { fnz(ctx, err) }() 421 | } 422 | } 423 | 424 | _, err = stmt.ExecContext(ctx, args...) 425 | if err != nil { 426 | return errors.Wrap(err, "failed to execute Exec") 427 | } 428 | 429 | return nil 430 | } 431 | 432 | func (s *SalStore) UpdateAuthorResult(ctx context.Context, req *UpdateAuthorReq) (sql.Result, error) { 433 | var ( 434 | err error 435 | rawQuery = req.Query() 436 | reqMap = make(sal.RowMap) 437 | ) 438 | reqMap.AppendTo("ID", &req.ID) 439 | reqMap.AppendTo("Name", &req.BaseAuthor.Name) 440 | reqMap.AppendTo("Desc", &req.BaseAuthor.Desc) 441 | 442 | ctx = context.WithValue(ctx, sal.ContextKeyTxOpened, s.txOpened) 443 | ctx = context.WithValue(ctx, sal.ContextKeyOperationType, "Exec") 444 | ctx = context.WithValue(ctx, sal.ContextKeyMethodName, "UpdateAuthorResult") 445 | 446 | pgQuery, args := sal.ProcessQueryAndArgs(rawQuery, reqMap) 447 | 448 | stmt, err := s.ctrl.PrepareStmt(ctx, s.parent, s.handler, pgQuery) 449 | if err != nil { 450 | return nil, errors.WithStack(err) 451 | } 452 | 453 | for _, fn := range s.ctrl.BeforeQuery { 454 | var fnz sal.FinalizerFunc 455 | ctx, fnz = fn(ctx, rawQuery, req) 456 | if fnz != nil { 457 | defer func() { fnz(ctx, err) }() 458 | } 459 | } 460 | 461 | res, err := stmt.ExecContext(ctx, args...) 462 | if err != nil { 463 | return nil, errors.Wrap(err, "failed to execute Exec") 464 | } 465 | 466 | return res, nil 467 | } 468 | 469 | // compile time checks 470 | var _ Store = &SalStore{} 471 | -------------------------------------------------------------------------------- /examples/bookstore/sal_client_test.go: -------------------------------------------------------------------------------- 1 | package bookstore 2 | 3 | import ( 4 | "context" 5 | "database/sql/driver" 6 | "testing" 7 | "time" 8 | 9 | "github.com/go-gad/sal" 10 | "github.com/lib/pq" 11 | "github.com/stretchr/testify/assert" 12 | "gopkg.in/DATA-DOG/go-sqlmock.v1" 13 | ) 14 | 15 | func TestSalStore_CreateAuthor(t *testing.T) { 16 | db, mock, err := sqlmock.New() 17 | if err != nil { 18 | t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) 19 | } 20 | defer db.Close() 21 | b1 := func(ctx context.Context, query string, req interface{}) (context.Context, sal.FinalizerFunc) { 22 | start := time.Now() 23 | return ctx, func(ctx context.Context, err error) { 24 | t.Logf( 25 | "%q > Opeartion %q: %q with req %#v took [%v] inTx[%v] Error: %+v", 26 | ctx.Value(sal.ContextKeyMethodName), 27 | ctx.Value(sal.ContextKeyOperationType), 28 | query, 29 | req, 30 | time.Since(start), 31 | ctx.Value(sal.ContextKeyTxOpened), 32 | err, 33 | ) 34 | } 35 | } 36 | 37 | client := NewStore(db, sal.BeforeQuery(b1)) 38 | 39 | req := CreateAuthorReq{BaseAuthor{Name: "foo", Desc: "Bar"}} 40 | 41 | expResp := CreateAuthorResp{ID: 1, CreatedAt: time.Now().Truncate(time.Millisecond)} 42 | rows := sqlmock.NewRows([]string{"ID", "CreatedAt"}).AddRow(expResp.ID, expResp.CreatedAt) 43 | mock.ExpectPrepare(`INSERT INTO authors .+`) 44 | mock.ExpectQuery(`INSERT INTO authors .+`).WithArgs(req.Name, req.Desc).WillReturnRows(rows) 45 | 46 | resp, err := client.CreateAuthor(context.Background(), req) 47 | assert.Equal(t, expResp, resp) 48 | assert.Nil(t, mock.ExpectationsWereMet()) 49 | } 50 | 51 | func dv(a []int64) driver.Value { 52 | v, _ := pq.Int64Array(a).Value() 53 | return v 54 | } 55 | 56 | func TestSalStore_GetAuthors(t *testing.T) { 57 | db, mock, err := sqlmock.New() 58 | if err != nil { 59 | t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) 60 | } 61 | defer db.Close() 62 | client := NewStore(db) 63 | 64 | req := GetAuthorsReq{ID: 123, Tags: Tags{Tags: []int64{33, 44, 55}}} 65 | 66 | expResp := []*GetAuthorsResp{ 67 | &GetAuthorsResp{ID: 10, Name: "Bob", Desc: "d1", Tags: Tags{Tags: []int64{1, 2, 3}}, CreatedAt: time.Now().Truncate(time.Millisecond)}, 68 | &GetAuthorsResp{ID: 20, Name: "Jhn", Desc: "d2", Tags: Tags{Tags: []int64{4, 5, 6}}, CreatedAt: time.Now().Truncate(time.Millisecond)}, 69 | &GetAuthorsResp{ID: 30, Name: "Max", Desc: "d3", Tags: Tags{Tags: []int64{6, 7, 8}}, CreatedAt: time.Now().Truncate(time.Millisecond)}, 70 | } 71 | 72 | rows := sqlmock.NewRows([]string{"id", "created_at", "name", "desc", "tags"}) 73 | for _, v := range expResp { 74 | rows = rows.AddRow(v.ID, v.CreatedAt, v.Name, v.Desc, dv(v.Tags.Tags)) 75 | } 76 | 77 | mock.ExpectPrepare(`SELECT id, created_at, name,.+`) 78 | mock.ExpectQuery(`SELECT id, created_at, name,.+`).WithArgs(req.ID, pq.Array(req.Tags.Tags)).WillReturnRows(rows) 79 | 80 | resp, err := client.GetAuthors(context.Background(), req) 81 | assert.Equal(t, expResp, resp) 82 | assert.Nil(t, err) 83 | assert.Nil(t, mock.ExpectationsWereMet()) 84 | } 85 | 86 | func TestSalStore_SameName(t *testing.T) { 87 | db, mock, err := sqlmock.New() 88 | if err != nil { 89 | t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) 90 | } 91 | defer db.Close() 92 | client := NewStore(db) 93 | 94 | req := SameNameReq{} 95 | 96 | expResp := SameNameResp{ 97 | Bar: "val level 1", 98 | Foo: Foo{ 99 | Bar: "val level 2", 100 | }, 101 | } 102 | var rows *sqlmock.Rows 103 | { 104 | rows = sqlmock.NewRows([]string{"Bar", "Bar"}) 105 | rows = rows.AddRow(expResp.Bar, expResp.Foo.Bar) 106 | } 107 | 108 | mock.ExpectPrepare(`SELECT.+`) 109 | mock.ExpectQuery(`SELECT.+`).WithArgs().WillReturnRows(rows) 110 | 111 | resp, err := client.SameName(context.Background(), req) 112 | assert.Equal(t, &expResp, resp) 113 | assert.Nil(t, err) 114 | assert.Nil(t, mock.ExpectationsWereMet()) 115 | } 116 | 117 | func TestSalStore_UpdateAuthor(t *testing.T) { 118 | db, mock, err := sqlmock.New() 119 | if err != nil { 120 | t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) 121 | } 122 | defer db.Close() 123 | client := NewStore(db) 124 | 125 | req := UpdateAuthorReq{ID: 123, BaseAuthor: BaseAuthor{Name: "John", Desc: "foo-bar"}} 126 | 127 | mock.ExpectPrepare("UPDATE authors SET.+") 128 | mock.ExpectExec("UPDATE authors SET.+").WithArgs(req.Name, req.Desc, req.ID).WillReturnResult(sqlmock.NewResult(0, 1)) 129 | 130 | err = client.UpdateAuthor(context.Background(), &req) 131 | assert.Nil(t, err) 132 | assert.Nil(t, mock.ExpectationsWereMet()) 133 | } 134 | 135 | func TestNewStoreController(t *testing.T) { 136 | db, mock, err := sqlmock.New() 137 | if err != nil { 138 | t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) 139 | } 140 | defer db.Close() 141 | b1 := func(ctx context.Context, query string, req interface{}) (context.Context, sal.FinalizerFunc) { 142 | start := time.Now() 143 | return ctx, func(ctx context.Context, err error) { 144 | t.Logf( 145 | "%q > Opeartion %q: %q with req %#v took [%v] inTx[%v] Error: %+v", 146 | ctx.Value(sal.ContextKeyMethodName), 147 | ctx.Value(sal.ContextKeyOperationType), 148 | query, 149 | req, 150 | time.Since(start), 151 | ctx.Value(sal.ContextKeyTxOpened), 152 | err, 153 | ) 154 | } 155 | } 156 | client := NewStore(db, sal.BeforeQuery(b1)) 157 | 158 | req1 := CreateAuthorReq{BaseAuthor{Name: "foo", Desc: "Bar"}} 159 | rows := sqlmock.NewRows([]string{"ID", "CreatedAt"}).AddRow(int64(1), time.Now().Truncate(time.Millisecond)) 160 | 161 | req2 := UpdateAuthorReq{ID: 123, BaseAuthor: BaseAuthor{Name: "John", Desc: "foo-bar"}} 162 | 163 | mock.ExpectBegin() 164 | mock.ExpectPrepare(`INSERT INTO authors .+`) // on connection 165 | mock.ExpectPrepare(`INSERT INTO authors .+`) // on transaction 166 | mock.ExpectQuery(`INSERT INTO authors .+`).WithArgs(req1.Name, req1.Desc).WillReturnRows(rows) 167 | mock.ExpectPrepare("UPDATE authors SET.+") // on connection 168 | mock.ExpectPrepare("UPDATE authors SET.+") // on transaction 169 | mock.ExpectExec("UPDATE authors SET.+").WithArgs(req2.Name, req2.Desc, req2.ID).WillReturnResult(sqlmock.NewResult(0, 1)) 170 | mock.ExpectCommit() 171 | 172 | ctx := context.Background() 173 | 174 | tx, err := client.BeginTx(ctx, nil) 175 | assert.Nil(t, err) 176 | 177 | _, err = tx.CreateAuthor(ctx, req1) 178 | assert.Nil(t, err) 179 | 180 | err = tx.UpdateAuthor(ctx, &req2) 181 | assert.Nil(t, err) 182 | 183 | err = tx.Tx().Commit(ctx) 184 | assert.Nil(t, err) 185 | assert.Nil(t, mock.ExpectationsWereMet()) 186 | 187 | } 188 | 189 | func TestSalStore_GetBooks(t *testing.T) { 190 | db, mock, err := sqlmock.New() 191 | if err != nil { 192 | t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) 193 | } 194 | defer db.Close() 195 | client := NewStore(db) 196 | 197 | req := GetBooksReq{} 198 | // time.Now().Truncate(time.Millisecond) 199 | expResp := []*GetBooksResp{ 200 | &GetBooksResp{ID: 10, Title: "foo-10"}, 201 | &GetBooksResp{ID: 20, Title: "foo-20"}, 202 | &GetBooksResp{ID: 30, Title: "foo-30"}, 203 | } 204 | //Scan(&id, nil, &title, nil) 205 | rows := sqlmock.NewRows([]string{"id", "created_at", "title", "desc"}) 206 | for _, v := range expResp { 207 | rows = rows.AddRow(v.ID, time.Now().Truncate(time.Millisecond), v.Title, "trash") 208 | } 209 | 210 | mock.ExpectPrepare(`SELECT \* FROM books`) 211 | mock.ExpectQuery(`SELECT \* FROM books`).WillReturnRows(rows) 212 | 213 | resp, err := client.GetBooks(context.Background(), req) 214 | assert.Equal(t, expResp, resp) 215 | assert.Nil(t, err) 216 | assert.Nil(t, mock.ExpectationsWereMet()) 217 | } 218 | -------------------------------------------------------------------------------- /examples/profile/profile.go: -------------------------------------------------------------------------------- 1 | package profile 2 | 3 | import ( 4 | "context" 5 | "time" 6 | 7 | "github.com/go-gad/sal/examples/profile/storage" 8 | ) 9 | 10 | type UserService struct { 11 | store storage.Store 12 | } 13 | 14 | func NewUserService(store storage.Store) *UserService { 15 | return &UserService{store: store} 16 | } 17 | 18 | func (s *UserService) CreateUser(ctx context.Context, name, email string) (*User, error) { 19 | req := storage.CreateUserReq{ 20 | Name: name, 21 | Email: email, 22 | } 23 | 24 | resp, err := s.store.CreateUser(ctx, req) 25 | if err != nil { 26 | return nil, err 27 | } 28 | 29 | return &User{ 30 | ID: resp.ID, 31 | Name: name, 32 | Email: email, 33 | CreatedAt: resp.CreatedAt, 34 | }, nil 35 | } 36 | 37 | func (s *UserService) AllUsers(ctx context.Context) (Users, error) { 38 | resp, err := s.store.AllUsers(ctx, storage.AllUsersReq{}) 39 | if err != nil { 40 | return nil, err 41 | } 42 | users := make(Users, 0, len(resp)) 43 | for _, v := range resp { 44 | users = append(users, &User{ 45 | ID: v.ID, 46 | Name: v.Name, 47 | Email: v.Email, 48 | CreatedAt: v.CreatedAt, 49 | }) 50 | } 51 | 52 | return users, nil 53 | } 54 | 55 | type User struct { 56 | ID int64 57 | Name string 58 | Email string 59 | CreatedAt time.Time 60 | } 61 | 62 | type Users []*User 63 | -------------------------------------------------------------------------------- /examples/profile/storage/client.go: -------------------------------------------------------------------------------- 1 | // Code generated by SalGen. DO NOT EDIT. 2 | package storage 3 | 4 | import ( 5 | "context" 6 | "database/sql" 7 | "github.com/go-gad/sal" 8 | "github.com/pkg/errors" 9 | ) 10 | 11 | type SalStore struct { 12 | Store 13 | handler sal.QueryHandler 14 | parent sal.QueryHandler 15 | ctrl *sal.Controller 16 | txOpened bool 17 | } 18 | 19 | func NewStore(h sal.QueryHandler, options ...sal.ClientOption) *SalStore { 20 | s := &SalStore{ 21 | handler: h, 22 | ctrl: sal.NewController(options...), 23 | txOpened: false, 24 | } 25 | 26 | return s 27 | } 28 | 29 | func (s *SalStore) BeginTx(ctx context.Context, opts *sql.TxOptions) (Store, error) { 30 | dbConn, ok := s.handler.(sal.TransactionBegin) 31 | if !ok { 32 | return nil, errors.New("handler doesn't satisfy the interface TransactionBegin") 33 | } 34 | var ( 35 | err error 36 | tx *sql.Tx 37 | ) 38 | 39 | ctx = context.WithValue(ctx, sal.ContextKeyTxOpened, s.txOpened) 40 | ctx = context.WithValue(ctx, sal.ContextKeyOperationType, "Begin") 41 | ctx = context.WithValue(ctx, sal.ContextKeyMethodName, "BeginTx") 42 | 43 | for _, fn := range s.ctrl.BeforeQuery { 44 | var fnz sal.FinalizerFunc 45 | ctx, fnz = fn(ctx, "BEGIN", nil) 46 | if fnz != nil { 47 | defer func() { fnz(ctx, err) }() 48 | } 49 | } 50 | 51 | tx, err = dbConn.BeginTx(ctx, opts) 52 | if err != nil { 53 | err = errors.Wrap(err, "failed to start tx") 54 | return nil, err 55 | } 56 | 57 | newClient := &SalStore{ 58 | handler: tx, 59 | parent: s.handler, 60 | ctrl: s.ctrl, 61 | txOpened: true, 62 | } 63 | 64 | return newClient, nil 65 | } 66 | 67 | func (s *SalStore) Tx() sal.Transaction { 68 | if tx, ok := s.handler.(sal.SqlTx); ok { 69 | return sal.NewWrappedTx(tx, s.ctrl) 70 | } 71 | return nil 72 | } 73 | func (s *SalStore) AllUsers(ctx context.Context, req AllUsersReq) ([]*AllUsersResp, error) { 74 | var ( 75 | err error 76 | rawQuery = req.Query() 77 | reqMap = make(sal.RowMap) 78 | ) 79 | 80 | ctx = context.WithValue(ctx, sal.ContextKeyTxOpened, s.txOpened) 81 | ctx = context.WithValue(ctx, sal.ContextKeyOperationType, "Query") 82 | ctx = context.WithValue(ctx, sal.ContextKeyMethodName, "AllUsers") 83 | 84 | pgQuery, args := sal.ProcessQueryAndArgs(rawQuery, reqMap) 85 | 86 | stmt, err := s.ctrl.PrepareStmt(ctx, s.parent, s.handler, pgQuery) 87 | if err != nil { 88 | return nil, errors.WithStack(err) 89 | } 90 | 91 | for _, fn := range s.ctrl.BeforeQuery { 92 | var fnz sal.FinalizerFunc 93 | ctx, fnz = fn(ctx, rawQuery, req) 94 | if fnz != nil { 95 | defer func() { fnz(ctx, err) }() 96 | } 97 | } 98 | 99 | rows, err := stmt.QueryContext(ctx, args...) 100 | if err != nil { 101 | return nil, errors.Wrap(err, "failed to execute Query") 102 | } 103 | defer rows.Close() 104 | 105 | cols, err := rows.Columns() 106 | if err != nil { 107 | return nil, errors.Wrap(err, "failed to fetch columns") 108 | } 109 | 110 | var list = make([]*AllUsersResp, 0) 111 | 112 | for rows.Next() { 113 | var resp AllUsersResp 114 | var respMap = make(sal.RowMap) 115 | respMap.AppendTo("id", &resp.ID) 116 | respMap.AppendTo("name", &resp.Name) 117 | respMap.AppendTo("email", &resp.Email) 118 | respMap.AppendTo("created_at", &resp.CreatedAt) 119 | 120 | dest := sal.GetDests(cols, respMap) 121 | 122 | if err = rows.Scan(dest...); err != nil { 123 | return nil, errors.Wrap(err, "failed to scan row") 124 | } 125 | 126 | list = append(list, &resp) 127 | } 128 | 129 | if err = rows.Err(); err != nil { 130 | return nil, errors.Wrap(err, "something failed during iteration") 131 | } 132 | 133 | return list, nil 134 | } 135 | 136 | func (s *SalStore) CreateUser(ctx context.Context, req CreateUserReq) (*CreateUserResp, error) { 137 | var ( 138 | err error 139 | rawQuery = req.Query() 140 | reqMap = make(sal.RowMap) 141 | ) 142 | reqMap.AppendTo("name", &req.Name) 143 | reqMap.AppendTo("email", &req.Email) 144 | 145 | ctx = context.WithValue(ctx, sal.ContextKeyTxOpened, s.txOpened) 146 | ctx = context.WithValue(ctx, sal.ContextKeyOperationType, "QueryRow") 147 | ctx = context.WithValue(ctx, sal.ContextKeyMethodName, "CreateUser") 148 | 149 | pgQuery, args := sal.ProcessQueryAndArgs(rawQuery, reqMap) 150 | 151 | stmt, err := s.ctrl.PrepareStmt(ctx, s.parent, s.handler, pgQuery) 152 | if err != nil { 153 | return nil, errors.WithStack(err) 154 | } 155 | 156 | for _, fn := range s.ctrl.BeforeQuery { 157 | var fnz sal.FinalizerFunc 158 | ctx, fnz = fn(ctx, rawQuery, req) 159 | if fnz != nil { 160 | defer func() { fnz(ctx, err) }() 161 | } 162 | } 163 | 164 | rows, err := stmt.QueryContext(ctx, args...) 165 | if err != nil { 166 | return nil, errors.Wrap(err, "failed to execute Query") 167 | } 168 | defer rows.Close() 169 | 170 | cols, err := rows.Columns() 171 | if err != nil { 172 | return nil, errors.Wrap(err, "failed to fetch columns") 173 | } 174 | 175 | if !rows.Next() { 176 | if err = rows.Err(); err != nil { 177 | return nil, errors.Wrap(err, "rows error") 178 | } 179 | return nil, sql.ErrNoRows 180 | } 181 | 182 | var resp CreateUserResp 183 | var respMap = make(sal.RowMap) 184 | respMap.AppendTo("id", &resp.ID) 185 | respMap.AppendTo("created_at", &resp.CreatedAt) 186 | 187 | dest := sal.GetDests(cols, respMap) 188 | 189 | if err = rows.Scan(dest...); err != nil { 190 | return nil, errors.Wrap(err, "failed to scan row") 191 | } 192 | 193 | if err = rows.Err(); err != nil { 194 | return nil, errors.Wrap(err, "something failed during iteration") 195 | } 196 | 197 | return &resp, nil 198 | } 199 | 200 | // compile time checks 201 | var _ Store = &SalStore{} 202 | -------------------------------------------------------------------------------- /examples/profile/storage/storage.go: -------------------------------------------------------------------------------- 1 | package storage 2 | 3 | import ( 4 | "context" 5 | "time" 6 | ) 7 | 8 | //go:generate salgen -destination=./client.go -package=github.com/go-gad/sal/examples/profile/storage github.com/go-gad/sal/examples/profile/storage Store 9 | type Store interface { 10 | CreateUser(ctx context.Context, req CreateUserReq) (*CreateUserResp, error) 11 | AllUsers(ctx context.Context, req AllUsersReq) ([]*AllUsersResp, error) 12 | } 13 | 14 | type CreateUserReq struct { 15 | Name string `sql:"name"` 16 | Email string `sql:"email"` 17 | } 18 | 19 | func (r CreateUserReq) Query() string { 20 | return `INSERT INTO users(name, email, created_at) VALUES(@name, @email, now()) RETURNING id, created_at` 21 | } 22 | 23 | type CreateUserResp struct { 24 | ID int64 `sql:"id"` 25 | CreatedAt time.Time `sql:"created_at"` 26 | } 27 | 28 | type AllUsersReq struct{} 29 | 30 | func (AllUsersReq) Query() string { 31 | return `SELECT id, name, email, created_at FROM users` 32 | } 33 | 34 | type AllUsersResp struct { 35 | ID int64 `sql:"id"` 36 | Name string `sql:"name"` 37 | Email string `sql:"email"` 38 | CreatedAt time.Time `sql:"created_at"` 39 | } 40 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/go-gad/sal 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/davecgh/go-spew v1.1.0 // indirect 7 | github.com/kr/pretty v0.1.0 8 | github.com/lib/pq v0.0.0-20180523175426-90697d60dd84 9 | github.com/pkg/errors v0.8.0 10 | github.com/pmezard/go-difflib v1.0.0 // indirect 11 | github.com/sergi/go-diff v1.0.0 12 | github.com/stretchr/testify v1.2.1 13 | gopkg.in/DATA-DOG/go-sqlmock.v1 v1.3.0 14 | ) 15 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= 4 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 5 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 6 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= 7 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 8 | github.com/lib/pq v0.0.0-20180523175426-90697d60dd84 h1:it29sI2IM490luSc3RAhp5WuCYnc6RtbfLVAB7nmC5M= 9 | github.com/lib/pq v0.0.0-20180523175426-90697d60dd84/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= 10 | github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw= 11 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 12 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 13 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 14 | github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= 15 | github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= 16 | github.com/stretchr/testify v1.2.1 h1:52QO5WkIUcHGIR7EnGagH88x1bUzqGXTC5/1bDTUQ7U= 17 | github.com/stretchr/testify v1.2.1/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 18 | gopkg.in/DATA-DOG/go-sqlmock.v1 v1.3.0 h1:FVCohIoYO7IJoDDVpV2pdq7SgrMH6wHnuTyrdrxJNoY= 19 | gopkg.in/DATA-DOG/go-sqlmock.v1 v1.3.0/go.mod h1:OdE7CF6DbADk7lN8LIKRzRJTTZXIjtWgA5THM5lhBAw= 20 | -------------------------------------------------------------------------------- /looker/looker.go: -------------------------------------------------------------------------------- 1 | package looker 2 | 3 | import ( 4 | "path" 5 | "reflect" 6 | "strings" 7 | "unicode" 8 | 9 | "github.com/go-gad/sal" 10 | ) 11 | 12 | type Package struct { 13 | ImportPath ImportElement 14 | Interfaces Interfaces 15 | } 16 | 17 | func (p *Package) ImportPaths() []string { 18 | list := make([]string, 0) 19 | if p.ImportPath.Path != "" { 20 | list = append(list, p.ImportPath.Path) 21 | } 22 | for _, intf := range p.Interfaces { 23 | list = append(list, intf.ImportPaths()...) 24 | } 25 | return list 26 | } 27 | 28 | // ImportElement represents the imported package. 29 | // Attribute `Alias` represents the optional alias for the package. 30 | // import foo "github.com/fooooo/baaaar-pppkkkkggg" 31 | type ImportElement struct { 32 | Path string 33 | Alias string 34 | } 35 | 36 | func (ie ImportElement) Name() string { 37 | if ie.Alias != "" { 38 | return ie.Alias 39 | } 40 | if ie.Path == "" { 41 | return "" 42 | } 43 | 44 | return path.Base(ie.Path) 45 | } 46 | 47 | func LookAtInterfaces(pkgPath string, is []reflect.Type) *Package { 48 | pkg := Package{ 49 | ImportPath: ImportElement{Path: pkgPath}, 50 | Interfaces: make(Interfaces, 0, len(is)), 51 | } 52 | for _, it := range is { 53 | intf := LookAtInterface(it) 54 | pkg.Interfaces = append(pkg.Interfaces, intf) 55 | } 56 | 57 | return &pkg 58 | } 59 | 60 | type Interface struct { 61 | ImportPath ImportElement 62 | UserType string 63 | Methods Methods 64 | } 65 | 66 | func (intf *Interface) Name(dstPath string) string { 67 | if dstPath == intf.ImportPath.Path { 68 | return intf.UserType 69 | } 70 | return intf.ImportPath.Name() + "." + intf.UserType 71 | } 72 | 73 | func (intf *Interface) ImplementationName(prefix string) string { 74 | return prefix + intf.UserType 75 | } 76 | 77 | func (intf *Interface) ImportPaths() []string { 78 | list := make([]string, 0) 79 | if intf.ImportPath.Path != "" { 80 | list = append(list, intf.ImportPath.Path) 81 | } 82 | 83 | for _, m := range intf.Methods { 84 | if m.Name == "Tx" || m.Name == "BeginTx" { 85 | continue 86 | } 87 | list = append(list, m.ImportPaths()...) 88 | } 89 | return list 90 | } 91 | 92 | type Interfaces []*Interface 93 | 94 | func LookAtInterface(typ reflect.Type) *Interface { 95 | intf := &Interface{ 96 | ImportPath: ImportElement{Path: typ.PkgPath()}, 97 | UserType: typ.Name(), 98 | Methods: make(Methods, 0, typ.NumMethod()), 99 | } 100 | 101 | for i := 0; i < typ.NumMethod(); i++ { 102 | mt := typ.Method(i) 103 | m := Method{ 104 | Name: mt.Name, 105 | } 106 | in, out := LookAtFuncParameters(typ.Method(i).Type) 107 | m.In = in 108 | m.Out = out 109 | 110 | intf.Methods = append(intf.Methods, &m) 111 | } 112 | return intf 113 | } 114 | 115 | type Method struct { 116 | Name string 117 | In Parameters 118 | Out Parameters 119 | } 120 | 121 | func (m *Method) ImportPaths() []string { 122 | list := make([]string, 0) 123 | for _, prm := range m.In { 124 | list = append(list, prm.ImportPaths()...) 125 | } 126 | for _, prm := range m.Out { 127 | list = append(list, prm.ImportPaths()...) 128 | } 129 | return list 130 | } 131 | 132 | type Methods []*Method 133 | 134 | type Parameter interface { 135 | Kind() string 136 | Name(dstPath string) string 137 | Pointer() bool 138 | ImportPaths() []string 139 | } 140 | 141 | type Parameters []Parameter 142 | 143 | func LookAtFuncParameters(mt reflect.Type) (Parameters, Parameters) { 144 | var in = make(Parameters, 0) 145 | for i := 0; i < mt.NumIn(); i++ { 146 | in = append(in, LookAtParameter(mt.In(i))) 147 | } 148 | 149 | var out = make(Parameters, 0) 150 | for i := 0; i < mt.NumOut(); i++ { 151 | out = append(out, LookAtParameter(mt.Out(i))) 152 | } 153 | 154 | return in, out 155 | } 156 | 157 | // Use exported fields because god.Encoder 158 | type StructElement struct { 159 | ImportPath ImportElement 160 | UserType string 161 | IsPointer bool 162 | Fields Fields 163 | ProcessRower bool 164 | } 165 | 166 | func (prm *StructElement) Kind() string { 167 | return reflect.Struct.String() 168 | } 169 | 170 | func (prm *StructElement) Name(dstPath string) string { 171 | if dstPath == prm.ImportPath.Path { 172 | return prm.UserType 173 | } 174 | return prm.ImportPath.Name() + "." + prm.UserType 175 | } 176 | 177 | func (prm *StructElement) Pointer() bool { 178 | return prm.IsPointer 179 | } 180 | 181 | // todo: import path for fields 182 | func (prm *StructElement) ImportPaths() []string { 183 | if prm.ImportPath.Path != "" { 184 | return []string{prm.ImportPath.Path} 185 | } 186 | return []string{} 187 | } 188 | 189 | type SliceElement struct { 190 | ImportPath ImportElement 191 | UserType string 192 | Item Parameter 193 | IsPointer bool 194 | } 195 | 196 | func (prm *SliceElement) Kind() string { 197 | return reflect.Slice.String() 198 | } 199 | 200 | func (prm *SliceElement) Name(dstPath string) string { 201 | if prm.UserType != "" { 202 | if dstPath == prm.ImportPath.Path { 203 | return prm.UserType 204 | } 205 | return prm.ImportPath.Name() + "." + prm.UserType 206 | } 207 | 208 | var ptr string 209 | if prm.Item.Pointer() { 210 | ptr = "*" 211 | } 212 | return "[]" + ptr + prm.Item.Name(dstPath) 213 | } 214 | 215 | func (prm *SliceElement) Pointer() bool { 216 | return prm.IsPointer 217 | } 218 | 219 | func (prm *SliceElement) ImportPaths() []string { 220 | if prm.ImportPath.Path != "" { 221 | return []string{prm.ImportPath.Path} 222 | } 223 | return []string{} 224 | } 225 | 226 | type InterfaceElement struct { 227 | ImportPath ImportElement 228 | UserType string 229 | } 230 | 231 | func (prm *InterfaceElement) Kind() string { 232 | return reflect.Interface.String() 233 | } 234 | 235 | func (prm *InterfaceElement) Name(dstPath string) string { 236 | if prm.ImportPath.Path == "" { 237 | return prm.UserType 238 | } 239 | if dstPath == prm.ImportPath.Path { 240 | return prm.UserType 241 | } 242 | return prm.ImportPath.Name() + "." + prm.UserType 243 | } 244 | 245 | func (prm *InterfaceElement) Pointer() bool { 246 | return false 247 | } 248 | 249 | func (prm *InterfaceElement) ImportPaths() []string { 250 | if prm.ImportPath.Path != "" { 251 | return []string{prm.ImportPath.Path} 252 | } 253 | return []string{} 254 | } 255 | 256 | type UnsupportedElement struct { 257 | ImportPath ImportElement 258 | UserType string 259 | BaseType string 260 | IsPointer bool 261 | } 262 | 263 | func (prm *UnsupportedElement) Kind() string { 264 | return prm.BaseType 265 | } 266 | 267 | func (prm *UnsupportedElement) Name(dstPath string) string { 268 | if dstPath == prm.ImportPath.Path { 269 | return prm.UserType 270 | } 271 | return prm.ImportPath.Name() + "." + prm.UserType 272 | } 273 | 274 | func (prm *UnsupportedElement) Pointer() bool { 275 | return prm.IsPointer 276 | } 277 | 278 | func (prm *UnsupportedElement) ImportPaths() []string { 279 | if prm.ImportPath.Path != "" { 280 | return []string{prm.ImportPath.Path} 281 | } 282 | return []string{} 283 | } 284 | 285 | func LookAtParameter(at reflect.Type) Parameter { 286 | var pointer bool 287 | if at.Kind() == reflect.Ptr { 288 | at = at.Elem() 289 | pointer = true 290 | } 291 | var prm Parameter 292 | 293 | im := GetImportElement(at) 294 | 295 | switch at.Kind() { 296 | case reflect.Struct: 297 | prm = &StructElement{ 298 | ImportPath: im, 299 | UserType: at.Name(), 300 | IsPointer: pointer, 301 | Fields: LookAtFields(at), 302 | ProcessRower: IsProcessRower(reflect.New(at).Interface()), 303 | } 304 | case reflect.Slice: 305 | prm = &SliceElement{ 306 | ImportPath: im, 307 | UserType: at.Name(), 308 | IsPointer: pointer, 309 | Item: LookAtParameter(at.Elem()), 310 | } 311 | case reflect.Interface: 312 | prm = &InterfaceElement{ 313 | ImportPath: im, 314 | UserType: at.Name(), 315 | } 316 | default: 317 | prm = &UnsupportedElement{ 318 | ImportPath: im, 319 | UserType: at.Name(), 320 | BaseType: at.Kind().String(), 321 | IsPointer: pointer, 322 | } 323 | } 324 | 325 | return prm 326 | } 327 | 328 | func IsProcessRower(s interface{}) bool { 329 | _, ok := s.(sal.ProcessRower) 330 | 331 | return ok 332 | } 333 | 334 | // Field describes the fields of struct after reflection. 335 | type Field struct { 336 | // See the fields that describe Req struct. 337 | // type Req struct { 338 | // ID int64 `sql:"id"` 339 | // } 340 | // for Req.ID Name contains `ID`. 341 | Name string 342 | // ImportPath contains ImportElement. 343 | ImportPath ImportElement 344 | // for Req.ID BaseType contains `int64`. 345 | BaseType string 346 | // UserType contains type other then basic if it's defined otherwise basic. 347 | UserType string 348 | // Anonymous sets to true if field contains anonymous nested struct. 349 | Anonymous bool 350 | // Tag contains the value for tag with name `sql` if it's presented. 351 | Tag string 352 | // todo 353 | Parents []string 354 | } 355 | 356 | // ColumnName returns the column name to use for mapping with sql response. 357 | func (f Field) ColumnName() string { 358 | if f.Tag == "" { 359 | return f.Name 360 | } 361 | return f.Tag 362 | } 363 | 364 | func (f Field) Path() string { 365 | path := append(f.Parents, f.Name) 366 | return strings.Join(path, ".") 367 | } 368 | 369 | // Fields is alias for slice of Field. 370 | type Fields []Field 371 | 372 | // tagName contains the name of tag of struct field to make mapping with sql response. 373 | const tagName = "sql" 374 | 375 | // LookAtFields receives the reflect.Type object of struct and returns the Fields. 376 | func LookAtFields(st reflect.Type) Fields { 377 | fields := make(Fields, 0, st.NumField()) 378 | for i := 0; i < st.NumField(); i++ { 379 | ft := st.Field(i) 380 | fields = append(fields, LookAtField(ft)...) 381 | } 382 | return fields 383 | } 384 | 385 | // LookAtField receive the reflected object of struct field and return Fields. 386 | // If field points to anonymous struct then LookAtFields will be called. 387 | func LookAtField(ft reflect.StructField) Fields { 388 | if ft.Anonymous && ft.Type.Kind() == reflect.Struct { 389 | // going to analyze embedded struct 390 | list := LookAtFields(ft.Type) 391 | for i := range list { 392 | list[i].Parents = append([]string{ft.Name}, list[i].Parents...) 393 | } 394 | return list 395 | } 396 | f := Field{ 397 | Name: ft.Name, 398 | ImportPath: ImportElement{Path: ft.Type.PkgPath()}, 399 | BaseType: ft.Type.Kind().String(), 400 | UserType: ft.Type.Name(), 401 | Anonymous: ft.Anonymous, 402 | Tag: ft.Tag.Get(tagName), 403 | Parents: make([]string, 0), 404 | } 405 | return []Field{f} 406 | } 407 | 408 | func GetImportElement(typ reflect.Type) ImportElement { 409 | alias := getAlias(typ.String()) 410 | im := ImportElement{Path: typ.PkgPath()} 411 | if alias != "" && im.Name() != alias { 412 | im.Alias = alias 413 | } 414 | return im 415 | } 416 | 417 | // return on []*foo.Body the string foo 418 | func getAlias(str string) string { 419 | f := func(c rune) bool { 420 | return !unicode.IsLetter(c) && !unicode.IsNumber(c) 421 | } 422 | ar := strings.FieldsFunc(str, f) 423 | if len(ar) == 2 { 424 | return ar[0] 425 | } 426 | return "" 427 | } 428 | -------------------------------------------------------------------------------- /looker/looker_test.go: -------------------------------------------------------------------------------- 1 | package looker_test 2 | 3 | import ( 4 | "context" 5 | "database/sql" 6 | "fmt" 7 | "io/ioutil" 8 | "reflect" 9 | "testing" 10 | 11 | pkg_ "github.com/go-gad/sal/examples/bookstore" 12 | "github.com/go-gad/sal/looker" 13 | "github.com/go-gad/sal/looker/testdata" 14 | "github.com/go-gad/sal/looker/testdata/foo-bar" 15 | "github.com/kr/pretty" 16 | "github.com/sergi/go-diff/diffmatchpatch" 17 | "github.com/stretchr/testify/assert" 18 | ) 19 | 20 | var update bool = false 21 | 22 | func TestLookAtInterfaces(t *testing.T) { 23 | pkgPath := "github.com/go-gad/sal/examples/bookstore" 24 | var list = []reflect.Type{ 25 | reflect.TypeOf((*pkg_.Store)(nil)).Elem(), 26 | } 27 | pkg := looker.LookAtInterfaces(pkgPath, list) 28 | 29 | //t.Logf("package %# v", pretty.Formatter(pkg)) 30 | 31 | act := fmt.Sprintf("%# v", pretty.Formatter(pkg)) 32 | if update { 33 | if err := ioutil.WriteFile("testdata/package.golden", []byte(act), 0666); err != nil { 34 | t.Fatal(err) 35 | } 36 | } 37 | exp, err := ioutil.ReadFile("testdata/package.golden") 38 | if err != nil { 39 | t.Fatal(err) 40 | } 41 | if string(exp) != act { 42 | t.Error("actual package is not equal to expected") 43 | dmp := diffmatchpatch.New() 44 | diffs := dmp.DiffMain(string(exp), act, true) 45 | t.Log(dmp.DiffPrettyText(diffs)) 46 | } 47 | } 48 | 49 | func TestLookAtInterface(t *testing.T) { 50 | var typ reflect.Type = reflect.TypeOf((*pkg_.Store)(nil)).Elem() 51 | intf := looker.LookAtInterface(typ) 52 | //t.Logf("Interface %# v", pretty.Formatter(intf)) 53 | act := fmt.Sprintf("%# v", pretty.Formatter(intf)) 54 | if update { 55 | if err := ioutil.WriteFile("testdata/interface.golden", []byte(act), 0666); err != nil { 56 | t.Fatal(err) 57 | } 58 | } 59 | 60 | exp, err := ioutil.ReadFile("testdata/interface.golden") 61 | if err != nil { 62 | t.Fatal(err) 63 | } 64 | if string(exp) != act { 65 | t.Error("actual interface is not equal to expected") 66 | dmp := diffmatchpatch.New() 67 | diffs := dmp.DiffMain(string(exp), act, true) 68 | t.Log(dmp.DiffPrettyText(diffs)) 69 | } 70 | } 71 | 72 | func TestLookAtParameter(t *testing.T) { 73 | for _, tc := range []struct { 74 | test string 75 | typ reflect.Type 76 | prm looker.Parameter 77 | kind string 78 | name string 79 | ptr bool 80 | }{ 81 | { 82 | test: "user struct", 83 | typ: reflect.TypeOf(testdata.Req1{}), 84 | prm: &looker.StructElement{ 85 | ImportPath: looker.ImportElement{Path: "github.com/go-gad/sal/looker/testdata"}, 86 | UserType: "Req1", 87 | IsPointer: false, 88 | }, 89 | kind: reflect.Struct.String(), 90 | name: "testdata.Req1", 91 | ptr: false, 92 | }, { 93 | test: "slice of user structs", 94 | typ: reflect.TypeOf([]*testdata.Req1{}), 95 | prm: &looker.StructElement{ 96 | ImportPath: looker.ImportElement{Path: "github.com/go-gad/sal/looker/testdata"}, 97 | UserType: "Req1", 98 | IsPointer: false, 99 | }, 100 | kind: reflect.Slice.String(), 101 | name: "[]*testdata.Req1", 102 | ptr: false, 103 | }, { 104 | test: "user type of slice", 105 | typ: reflect.TypeOf(testdata.List1{}), 106 | prm: &looker.StructElement{ 107 | ImportPath: looker.ImportElement{Path: "github.com/go-gad/sal/looker/testdata"}, 108 | UserType: "List1", 109 | IsPointer: false, 110 | }, 111 | kind: reflect.Slice.String(), 112 | name: "testdata.List1", 113 | ptr: false, 114 | }, { 115 | test: "context", 116 | typ: reflect.TypeOf((*context.Context)(nil)).Elem(), 117 | prm: &looker.InterfaceElement{ 118 | ImportPath: looker.ImportElement{Path: "context"}, 119 | UserType: "Context", 120 | }, 121 | kind: reflect.Interface.String(), 122 | name: "context.Context", 123 | ptr: false, 124 | }, { 125 | test: "error", 126 | typ: reflect.TypeOf((*error)(nil)).Elem(), 127 | prm: &looker.InterfaceElement{ 128 | ImportPath: looker.ImportElement{Path: ""}, 129 | UserType: "error", 130 | }, 131 | kind: reflect.Interface.String(), 132 | name: "error", 133 | ptr: false, 134 | }, { 135 | test: "alias", 136 | typ: reflect.TypeOf(foo.Body{}), 137 | prm: &looker.StructElement{ 138 | ImportPath: looker.ImportElement{Path: "github.com/go-gad/sal/looker/testdata/foo-bar", Alias: "foo"}, 139 | UserType: "Body", 140 | IsPointer: false, 141 | }, 142 | kind: reflect.Struct.String(), 143 | name: "foo.Body", 144 | ptr: false, 145 | }, { 146 | test: "alias for slice", 147 | typ: reflect.TypeOf(foo.List{}), 148 | prm: &looker.SliceElement{ 149 | ImportPath: looker.ImportElement{Path: "github.com/go-gad/sal/looker/testdata/foo-bar", Alias: "foo"}, 150 | UserType: "List", 151 | Item: &looker.StructElement{ 152 | ImportPath: looker.ImportElement{Path: "github.com/go-gad/sal/looker/testdata/foo-bar", Alias: "foo"}, 153 | UserType: "Body", 154 | IsPointer: true, 155 | ProcessRower: false, 156 | }, 157 | IsPointer: false, 158 | }, 159 | kind: reflect.Slice.String(), 160 | name: "foo.List", 161 | ptr: false, 162 | }, { 163 | test: "result", 164 | typ: reflect.TypeOf((*sql.Result)(nil)).Elem(), 165 | prm: &looker.InterfaceElement{}, 166 | kind: reflect.Interface.String(), 167 | name: "sql.Result", 168 | ptr: false, 169 | }, 170 | } { 171 | t.Run(tc.test, func(t *testing.T) { 172 | dstPkg := looker.ImportElement{Path: "github.com/go-gad/sal/looker"} 173 | assert := assert.New(t) 174 | prm := looker.LookAtParameter(tc.typ) 175 | assert.Equal(tc.kind, prm.Kind()) 176 | assert.Equal(tc.name, prm.Name(dstPkg.Path)) 177 | assert.Equal(tc.ptr, prm.Pointer()) 178 | //t.Logf("element %# v", pretty.Formatter(prm)) 179 | }) 180 | } 181 | } 182 | 183 | func TestLookAtFields(t *testing.T) { 184 | t.Run("common", func(t *testing.T) { 185 | var typ reflect.Type = reflect.TypeOf(testdata.Req1{}) 186 | actFields := looker.LookAtFields(typ) 187 | expFields := looker.Fields{ 188 | { 189 | Name: "ID", 190 | ImportPath: looker.ImportElement{}, 191 | BaseType: "int64", 192 | UserType: "int64", 193 | Anonymous: false, 194 | Tag: "id", 195 | Parents: []string{}, 196 | }, 197 | { 198 | Name: "Name", 199 | ImportPath: looker.ImportElement{}, 200 | BaseType: "string", 201 | UserType: "string", 202 | Anonymous: false, 203 | Tag: "", 204 | Parents: []string{}, 205 | }, 206 | } 207 | assert.Equal(t, expFields, actFields) 208 | t.Logf("struct field %# v", pretty.Formatter(actFields)) 209 | }) 210 | 211 | t.Run("nested", func(t *testing.T) { 212 | var typ reflect.Type = reflect.TypeOf(testdata.Lvl1{}) 213 | actFields := looker.LookAtFields(typ) 214 | expFields := looker.Fields{ 215 | { 216 | Name: "Name", 217 | ImportPath: looker.ImportElement{}, 218 | BaseType: "string", 219 | UserType: "string", 220 | Anonymous: false, 221 | Tag: "", 222 | Parents: []string{}, 223 | }, 224 | { 225 | Name: "Desc", 226 | ImportPath: looker.ImportElement{}, 227 | BaseType: "string", 228 | UserType: "string", 229 | Anonymous: false, 230 | Tag: "", 231 | Parents: []string{}, 232 | }, 233 | { 234 | Name: "Foo", 235 | ImportPath: looker.ImportElement{}, 236 | BaseType: "string", 237 | UserType: "string", 238 | Anonymous: false, 239 | Tag: "", 240 | Parents: []string{"Lvl21"}, 241 | }, 242 | { 243 | Name: "Bar", 244 | ImportPath: looker.ImportElement{}, 245 | BaseType: "string", 246 | UserType: "string", 247 | Anonymous: false, 248 | Tag: "", 249 | Parents: []string{"Lvl21"}, 250 | }, 251 | { 252 | Name: "Foo", 253 | ImportPath: looker.ImportElement{}, 254 | BaseType: "string", 255 | UserType: "string", 256 | Anonymous: false, 257 | Tag: "", 258 | Parents: []string{"Lvl22"}, 259 | }, 260 | { 261 | Name: "Bar", 262 | ImportPath: looker.ImportElement{}, 263 | BaseType: "string", 264 | UserType: "string", 265 | Anonymous: false, 266 | Tag: "", 267 | Parents: []string{"Lvl22"}, 268 | }, 269 | { 270 | Name: "Foo", 271 | ImportPath: looker.ImportElement{}, 272 | BaseType: "string", 273 | UserType: "string", 274 | Anonymous: false, 275 | Tag: "", 276 | Parents: []string{"Lvl22", "Lvl3"}, 277 | }, 278 | { 279 | Name: "Bar", 280 | ImportPath: looker.ImportElement{}, 281 | BaseType: "string", 282 | UserType: "string", 283 | Anonymous: false, 284 | Tag: "", 285 | Parents: []string{"Lvl22", "Lvl3"}, 286 | }, 287 | } 288 | assert.Equal(t, expFields, actFields) 289 | t.Logf("struct field %# v", pretty.Formatter(actFields)) 290 | }) 291 | } 292 | 293 | func TestField_Path(t *testing.T) { 294 | f := looker.Field{ 295 | Name: "Bar", 296 | ImportPath: looker.ImportElement{}, 297 | BaseType: "string", 298 | UserType: "string", 299 | Anonymous: false, 300 | Tag: "", 301 | Parents: []string{"Lvl22", "Lvl3"}, 302 | } 303 | assert.Equal(t, "Lvl22.Lvl3.Bar", f.Path()) 304 | f.Parents = []string{} 305 | assert.Equal(t, "Bar", f.Path()) 306 | } 307 | 308 | func TestIsProcessRower(t *testing.T) { 309 | for _, tc := range []struct { 310 | typ reflect.Type 311 | exp bool 312 | }{ 313 | {reflect.TypeOf(testdata.Req1{}), false}, 314 | {reflect.TypeOf(&testdata.Req1{}), false}, 315 | {reflect.TypeOf(testdata.Req2{}), true}, 316 | {reflect.TypeOf(&testdata.Req2{}), true}, 317 | } { 318 | var typ reflect.Type = tc.typ 319 | if tc.typ.Kind() == reflect.Ptr { 320 | typ = tc.typ.Elem() 321 | } 322 | assert.Equal(t, tc.exp, looker.IsProcessRower(reflect.New(typ).Interface()), "input typ %q", typ.String()) 323 | } 324 | } 325 | -------------------------------------------------------------------------------- /looker/reflect.go: -------------------------------------------------------------------------------- 1 | package looker 2 | 3 | import ( 4 | "bytes" 5 | "encoding/gob" 6 | "flag" 7 | "fmt" 8 | "go/build" 9 | "io/ioutil" 10 | "os" 11 | "os/exec" 12 | "path/filepath" 13 | "runtime" 14 | "text/template" 15 | 16 | "github.com/pkg/errors" 17 | ) 18 | 19 | var ( 20 | buildFlags = flag.String("build_flags", "", "Additional flags for go build.") 21 | ) 22 | 23 | func Reflect(importPath string, symbols []string) (*Package, error) { 24 | program, err := writeProgram(importPath, symbols) 25 | if err != nil { 26 | return nil, err 27 | } 28 | //fmt.Printf("PROGRAMM \n%s\n----------\n", string(program)) 29 | 30 | wd, _ := os.Getwd() 31 | 32 | // Try to run the program in the same directory as the input package. 33 | if p, err := build.Import(importPath, wd, build.FindOnly); err == nil { 34 | dir := p.Dir 35 | if p, err := buildAndRun(program, dir); err == nil { 36 | return p, nil 37 | } 38 | } 39 | 40 | // Since that didn't work, try to run it in the current working directory. 41 | if p, err := buildAndRun(program, wd); err == nil { 42 | return p, nil 43 | } 44 | 45 | // Since that didn't work, try to run it in a standard temp directory. 46 | return buildAndRun(program, "") 47 | } 48 | 49 | // run the given program and parse the output as a model.Package. 50 | func run(program string) (*Package, error) { 51 | f, err := ioutil.TempFile("", "") 52 | if err != nil { 53 | return nil, errors.Wrap(err, "failed to create temp file") 54 | } 55 | filename := f.Name() 56 | defer os.Remove(filename) 57 | if err := f.Close(); err != nil { 58 | return nil, err 59 | } 60 | 61 | // Run the program. 62 | cmd := exec.Command(program, "-output", filename) 63 | cmd.Stdout = os.Stdout 64 | cmd.Stderr = os.Stderr 65 | if err := cmd.Run(); err != nil { 66 | return nil, err 67 | } 68 | 69 | f, err = os.Open(filename) 70 | if err != nil { 71 | return nil, errors.Wrapf(err, "failed to open file %s", filename) 72 | } 73 | 74 | // Process output. 75 | var pkg Package 76 | gob.Register(&StructElement{}) 77 | gob.Register(&SliceElement{}) 78 | gob.Register(&InterfaceElement{}) 79 | 80 | if err := gob.NewDecoder(f).Decode(&pkg); err != nil { 81 | return nil, errors.Wrap(err, "failed to decode pkg") 82 | } 83 | 84 | if err := f.Close(); err != nil { 85 | return nil, errors.Wrap(err, "failed to close file") 86 | } 87 | 88 | return &pkg, nil 89 | } 90 | 91 | func buildAndRun(program []byte, dir string) (*Package, error) { 92 | // We use TempDir instead of TempFile so we can control the filename. 93 | tmpDir, err := ioutil.TempDir(dir, "sal_reflect_") 94 | if err != nil { 95 | return nil, fmt.Errorf("failed to create tmp dir: %s", err) 96 | } 97 | defer os.RemoveAll(tmpDir) 98 | const progSource = "prog.go" 99 | var progBinary = "prog.bin" 100 | if runtime.GOOS == "windows" { 101 | // Windows won't execute a program unless it has a ".exe" suffix. 102 | progBinary += ".exe" 103 | } 104 | 105 | if err := ioutil.WriteFile(filepath.Join(tmpDir, progSource), program, 0600); err != nil { 106 | return nil, err 107 | } 108 | 109 | cmdArgs := []string{} 110 | cmdArgs = append(cmdArgs, "build") 111 | if *buildFlags != "" { 112 | cmdArgs = append(cmdArgs, *buildFlags) 113 | } 114 | cmdArgs = append(cmdArgs, "-o", progBinary, progSource) 115 | 116 | // Build the program. 117 | cmd := exec.Command("go", cmdArgs...) 118 | cmd.Dir = tmpDir 119 | cmd.Stdout = os.Stdout 120 | cmd.Stderr = os.Stderr 121 | if err := cmd.Run(); err != nil { 122 | return nil, fmt.Errorf("failed to run cmd %v: %s", cmdArgs, err) 123 | } 124 | return run(filepath.Join(tmpDir, progBinary)) 125 | } 126 | 127 | func writeProgram(importPath string, symbols []string) ([]byte, error) { 128 | var program bytes.Buffer 129 | data := reflectData{ 130 | ImportPath: importPath, 131 | Symbols: symbols, 132 | } 133 | if err := reflectProgram.Execute(&program, &data); err != nil { 134 | return nil, err 135 | } 136 | return program.Bytes(), nil 137 | } 138 | 139 | type reflectData struct { 140 | ImportPath string 141 | Symbols []string 142 | } 143 | 144 | func EncodeGob(output string, pkg *Package) error { 145 | outfile := os.Stdout 146 | 147 | if len(output) != 0 { 148 | var err error 149 | if outfile, err = os.Create(output); err != nil { 150 | return fmt.Errorf("failed to open output file %q: %s", output, err) 151 | } 152 | defer func() { 153 | if err := outfile.Close(); err != nil { 154 | fmt.Errorf("failed to close output file %q: %s", output, err) 155 | } 156 | }() 157 | } 158 | 159 | gob.Register(&StructElement{}) 160 | gob.Register(&SliceElement{}) 161 | gob.Register(&InterfaceElement{}) 162 | //gob.Register(Parameters{}) 163 | //gob.Register(Field{}) 164 | //gob.Register(Fields{}) 165 | 166 | if err := gob.NewEncoder(outfile).Encode(pkg); err != nil { 167 | fmt.Errorf("gob encode: %s", err) 168 | } 169 | 170 | return nil 171 | } 172 | 173 | // This program reflects on an interface value, and prints the 174 | // gob encoding of a model.Package to standard output. 175 | // JSON doesn't work because of the model.Type interface. 176 | var reflectProgram = template.Must(template.New("program").Parse(` 177 | package main 178 | 179 | import ( 180 | "flag" 181 | "fmt" 182 | "os" 183 | "reflect" 184 | 185 | "github.com/go-gad/sal/looker" 186 | 187 | pkg_ {{printf "%q" .ImportPath}} 188 | ) 189 | 190 | var output = flag.String("output", "", "The output file name, or empty to use stdout.") 191 | 192 | func main() { 193 | flag.Parse() 194 | 195 | pkgPath := {{printf "%q" .ImportPath}} 196 | var list = []reflect.Type{ 197 | {{range .Symbols}} 198 | reflect.TypeOf((*pkg_.{{.}})(nil)).Elem(), 199 | {{end}} 200 | } 201 | 202 | pkg := looker.LookAtInterfaces(pkgPath, list) 203 | 204 | if err := looker.EncodeGob(*output, pkg); err != nil { 205 | fmt.Fprintf(os.Stderr, "failed EncodeGob: %s\n", err) 206 | os.Exit(1) 207 | } 208 | } 209 | `)) 210 | -------------------------------------------------------------------------------- /looker/reflect_test.go: -------------------------------------------------------------------------------- 1 | package looker_test 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "testing" 7 | 8 | "bytes" 9 | "encoding/gob" 10 | 11 | "github.com/go-gad/sal/looker" 12 | "github.com/kr/pretty" 13 | ) 14 | 15 | func TestReflect(t *testing.T) { 16 | pkg, err := looker.Reflect("github.com/go-gad/sal/examples/bookstore", []string{"Store"}) 17 | if err != nil { 18 | t.Fatal(err) 19 | } 20 | 21 | t.Logf("Package %# v", pretty.Formatter(pkg)) 22 | } 23 | 24 | func TestEncodeGob(t *testing.T) { 25 | f, err := ioutil.TempFile("", "") 26 | if err != nil { 27 | t.Fatal(err) 28 | } 29 | filename := f.Name() 30 | //t.Log("filename ", filename) 31 | defer os.Remove(filename) 32 | if err := f.Close(); err != nil { 33 | t.Fatal(err) 34 | } 35 | pkg, err := looker.Reflect("github.com/go-gad/sal/examples/bookstore", []string{"Store"}) 36 | if err != nil { 37 | t.Fatal(err) 38 | } 39 | 40 | if err := looker.EncodeGob(filename, pkg); err != nil { 41 | t.Fatal(err) 42 | } 43 | 44 | fb, _ := ioutil.ReadFile(filename) 45 | t.Logf("File content:\n%s", string(fb)) 46 | 47 | gb := bytes.NewBuffer(fb) 48 | var pkgD looker.Package 49 | if err := gob.NewDecoder(gb).Decode(&pkgD); err != nil { 50 | t.Fatal(err) 51 | } 52 | t.Logf("Package %# v", pretty.Formatter(pkg)) 53 | } 54 | -------------------------------------------------------------------------------- /looker/testdata/foo-bar/foo.go: -------------------------------------------------------------------------------- 1 | package foo 2 | 3 | type Body struct{} 4 | 5 | func (b Body) Query() string { return `` } 6 | 7 | type List []*Body 8 | -------------------------------------------------------------------------------- /looker/testdata/interface.golden: -------------------------------------------------------------------------------- 1 | &looker.Interface{ 2 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 3 | UserType: "Store", 4 | Methods: { 5 | &looker.Method{ 6 | Name: "BeginTx", 7 | In: { 8 | &looker.InterfaceElement{ 9 | ImportPath: looker.ImportElement{Path:"context", Alias:""}, 10 | UserType: "Context", 11 | }, 12 | &looker.StructElement{ 13 | ImportPath: looker.ImportElement{Path:"database/sql", Alias:""}, 14 | UserType: "TxOptions", 15 | IsPointer: true, 16 | Fields: { 17 | { 18 | Name: "Isolation", 19 | ImportPath: looker.ImportElement{Path:"database/sql", Alias:""}, 20 | BaseType: "int", 21 | UserType: "IsolationLevel", 22 | Anonymous: false, 23 | Tag: "", 24 | Parents: {}, 25 | }, 26 | { 27 | Name: "ReadOnly", 28 | ImportPath: looker.ImportElement{}, 29 | BaseType: "bool", 30 | UserType: "bool", 31 | Anonymous: false, 32 | Tag: "", 33 | Parents: {}, 34 | }, 35 | }, 36 | ProcessRower: false, 37 | }, 38 | }, 39 | Out: { 40 | &looker.InterfaceElement{ 41 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 42 | UserType: "Store", 43 | }, 44 | &looker.InterfaceElement{ 45 | ImportPath: looker.ImportElement{}, 46 | UserType: "error", 47 | }, 48 | }, 49 | }, 50 | &looker.Method{ 51 | Name: "CreateAuthor", 52 | In: { 53 | &looker.InterfaceElement{ 54 | ImportPath: looker.ImportElement{Path:"context", Alias:""}, 55 | UserType: "Context", 56 | }, 57 | &looker.StructElement{ 58 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 59 | UserType: "CreateAuthorReq", 60 | IsPointer: false, 61 | Fields: { 62 | { 63 | Name: "Name", 64 | ImportPath: looker.ImportElement{}, 65 | BaseType: "string", 66 | UserType: "string", 67 | Anonymous: false, 68 | Tag: "", 69 | Parents: {"BaseAuthor"}, 70 | }, 71 | { 72 | Name: "Desc", 73 | ImportPath: looker.ImportElement{}, 74 | BaseType: "string", 75 | UserType: "string", 76 | Anonymous: false, 77 | Tag: "", 78 | Parents: {"BaseAuthor"}, 79 | }, 80 | }, 81 | ProcessRower: false, 82 | }, 83 | }, 84 | Out: { 85 | &looker.StructElement{ 86 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 87 | UserType: "CreateAuthorResp", 88 | IsPointer: false, 89 | Fields: { 90 | { 91 | Name: "ID", 92 | ImportPath: looker.ImportElement{}, 93 | BaseType: "int64", 94 | UserType: "int64", 95 | Anonymous: false, 96 | Tag: "", 97 | Parents: {}, 98 | }, 99 | { 100 | Name: "CreatedAt", 101 | ImportPath: looker.ImportElement{Path:"time", Alias:""}, 102 | BaseType: "struct", 103 | UserType: "Time", 104 | Anonymous: false, 105 | Tag: "", 106 | Parents: {}, 107 | }, 108 | }, 109 | ProcessRower: false, 110 | }, 111 | &looker.InterfaceElement{ 112 | ImportPath: looker.ImportElement{}, 113 | UserType: "error", 114 | }, 115 | }, 116 | }, 117 | &looker.Method{ 118 | Name: "CreateAuthorPtr", 119 | In: { 120 | &looker.InterfaceElement{ 121 | ImportPath: looker.ImportElement{Path:"context", Alias:""}, 122 | UserType: "Context", 123 | }, 124 | &looker.StructElement{ 125 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 126 | UserType: "CreateAuthorReq", 127 | IsPointer: false, 128 | Fields: { 129 | { 130 | Name: "Name", 131 | ImportPath: looker.ImportElement{}, 132 | BaseType: "string", 133 | UserType: "string", 134 | Anonymous: false, 135 | Tag: "", 136 | Parents: {"BaseAuthor"}, 137 | }, 138 | { 139 | Name: "Desc", 140 | ImportPath: looker.ImportElement{}, 141 | BaseType: "string", 142 | UserType: "string", 143 | Anonymous: false, 144 | Tag: "", 145 | Parents: {"BaseAuthor"}, 146 | }, 147 | }, 148 | ProcessRower: false, 149 | }, 150 | }, 151 | Out: { 152 | &looker.StructElement{ 153 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 154 | UserType: "CreateAuthorResp", 155 | IsPointer: true, 156 | Fields: { 157 | { 158 | Name: "ID", 159 | ImportPath: looker.ImportElement{}, 160 | BaseType: "int64", 161 | UserType: "int64", 162 | Anonymous: false, 163 | Tag: "", 164 | Parents: {}, 165 | }, 166 | { 167 | Name: "CreatedAt", 168 | ImportPath: looker.ImportElement{Path:"time", Alias:""}, 169 | BaseType: "struct", 170 | UserType: "Time", 171 | Anonymous: false, 172 | Tag: "", 173 | Parents: {}, 174 | }, 175 | }, 176 | ProcessRower: false, 177 | }, 178 | &looker.InterfaceElement{ 179 | ImportPath: looker.ImportElement{}, 180 | UserType: "error", 181 | }, 182 | }, 183 | }, 184 | &looker.Method{ 185 | Name: "GetAuthors", 186 | In: { 187 | &looker.InterfaceElement{ 188 | ImportPath: looker.ImportElement{Path:"context", Alias:""}, 189 | UserType: "Context", 190 | }, 191 | &looker.StructElement{ 192 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 193 | UserType: "GetAuthorsReq", 194 | IsPointer: false, 195 | Fields: { 196 | { 197 | Name: "ID", 198 | ImportPath: looker.ImportElement{}, 199 | BaseType: "int64", 200 | UserType: "int64", 201 | Anonymous: false, 202 | Tag: "id", 203 | Parents: {}, 204 | }, 205 | { 206 | Name: "Tags", 207 | ImportPath: looker.ImportElement{}, 208 | BaseType: "slice", 209 | UserType: "", 210 | Anonymous: false, 211 | Tag: "tags", 212 | Parents: {"Tags"}, 213 | }, 214 | }, 215 | ProcessRower: true, 216 | }, 217 | }, 218 | Out: { 219 | &looker.SliceElement{ 220 | ImportPath: looker.ImportElement{Path:"", Alias:"bookstore"}, 221 | UserType: "", 222 | Item: &looker.StructElement{ 223 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 224 | UserType: "GetAuthorsResp", 225 | IsPointer: true, 226 | Fields: { 227 | { 228 | Name: "ID", 229 | ImportPath: looker.ImportElement{}, 230 | BaseType: "int64", 231 | UserType: "int64", 232 | Anonymous: false, 233 | Tag: "id", 234 | Parents: {}, 235 | }, 236 | { 237 | Name: "CreatedAt", 238 | ImportPath: looker.ImportElement{Path:"time", Alias:""}, 239 | BaseType: "struct", 240 | UserType: "Time", 241 | Anonymous: false, 242 | Tag: "created_at", 243 | Parents: {}, 244 | }, 245 | { 246 | Name: "Name", 247 | ImportPath: looker.ImportElement{}, 248 | BaseType: "string", 249 | UserType: "string", 250 | Anonymous: false, 251 | Tag: "name", 252 | Parents: {}, 253 | }, 254 | { 255 | Name: "Desc", 256 | ImportPath: looker.ImportElement{}, 257 | BaseType: "string", 258 | UserType: "string", 259 | Anonymous: false, 260 | Tag: "desc", 261 | Parents: {}, 262 | }, 263 | { 264 | Name: "Tags", 265 | ImportPath: looker.ImportElement{}, 266 | BaseType: "slice", 267 | UserType: "", 268 | Anonymous: false, 269 | Tag: "tags", 270 | Parents: {"Tags"}, 271 | }, 272 | }, 273 | ProcessRower: true, 274 | }, 275 | IsPointer: false, 276 | }, 277 | &looker.InterfaceElement{ 278 | ImportPath: looker.ImportElement{}, 279 | UserType: "error", 280 | }, 281 | }, 282 | }, 283 | &looker.Method{ 284 | Name: "GetBooks", 285 | In: { 286 | &looker.InterfaceElement{ 287 | ImportPath: looker.ImportElement{Path:"context", Alias:""}, 288 | UserType: "Context", 289 | }, 290 | &looker.StructElement{ 291 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 292 | UserType: "GetBooksReq", 293 | IsPointer: false, 294 | Fields: { 295 | }, 296 | ProcessRower: false, 297 | }, 298 | }, 299 | Out: { 300 | &looker.SliceElement{ 301 | ImportPath: looker.ImportElement{Path:"", Alias:"bookstore"}, 302 | UserType: "", 303 | Item: &looker.StructElement{ 304 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 305 | UserType: "GetBooksResp", 306 | IsPointer: true, 307 | Fields: { 308 | { 309 | Name: "ID", 310 | ImportPath: looker.ImportElement{}, 311 | BaseType: "int64", 312 | UserType: "int64", 313 | Anonymous: false, 314 | Tag: "id", 315 | Parents: {}, 316 | }, 317 | { 318 | Name: "Title", 319 | ImportPath: looker.ImportElement{}, 320 | BaseType: "string", 321 | UserType: "string", 322 | Anonymous: false, 323 | Tag: "title", 324 | Parents: {}, 325 | }, 326 | }, 327 | ProcessRower: false, 328 | }, 329 | IsPointer: false, 330 | }, 331 | &looker.InterfaceElement{ 332 | ImportPath: looker.ImportElement{}, 333 | UserType: "error", 334 | }, 335 | }, 336 | }, 337 | &looker.Method{ 338 | Name: "SameName", 339 | In: { 340 | &looker.InterfaceElement{ 341 | ImportPath: looker.ImportElement{Path:"context", Alias:""}, 342 | UserType: "Context", 343 | }, 344 | &looker.StructElement{ 345 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 346 | UserType: "SameNameReq", 347 | IsPointer: false, 348 | Fields: { 349 | }, 350 | ProcessRower: false, 351 | }, 352 | }, 353 | Out: { 354 | &looker.StructElement{ 355 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 356 | UserType: "SameNameResp", 357 | IsPointer: true, 358 | Fields: { 359 | { 360 | Name: "Bar", 361 | ImportPath: looker.ImportElement{}, 362 | BaseType: "string", 363 | UserType: "string", 364 | Anonymous: false, 365 | Tag: "", 366 | Parents: {}, 367 | }, 368 | { 369 | Name: "Bar", 370 | ImportPath: looker.ImportElement{}, 371 | BaseType: "string", 372 | UserType: "string", 373 | Anonymous: false, 374 | Tag: "", 375 | Parents: {"Foo"}, 376 | }, 377 | }, 378 | ProcessRower: false, 379 | }, 380 | &looker.InterfaceElement{ 381 | ImportPath: looker.ImportElement{}, 382 | UserType: "error", 383 | }, 384 | }, 385 | }, 386 | &looker.Method{ 387 | Name: "Tx", 388 | In: { 389 | }, 390 | Out: { 391 | &looker.InterfaceElement{ 392 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal", Alias:""}, 393 | UserType: "Transaction", 394 | }, 395 | }, 396 | }, 397 | &looker.Method{ 398 | Name: "UpdateAuthor", 399 | In: { 400 | &looker.InterfaceElement{ 401 | ImportPath: looker.ImportElement{Path:"context", Alias:""}, 402 | UserType: "Context", 403 | }, 404 | &looker.StructElement{ 405 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 406 | UserType: "UpdateAuthorReq", 407 | IsPointer: true, 408 | Fields: { 409 | { 410 | Name: "ID", 411 | ImportPath: looker.ImportElement{}, 412 | BaseType: "int64", 413 | UserType: "int64", 414 | Anonymous: false, 415 | Tag: "", 416 | Parents: {}, 417 | }, 418 | { 419 | Name: "Name", 420 | ImportPath: looker.ImportElement{}, 421 | BaseType: "string", 422 | UserType: "string", 423 | Anonymous: false, 424 | Tag: "", 425 | Parents: {"BaseAuthor"}, 426 | }, 427 | { 428 | Name: "Desc", 429 | ImportPath: looker.ImportElement{}, 430 | BaseType: "string", 431 | UserType: "string", 432 | Anonymous: false, 433 | Tag: "", 434 | Parents: {"BaseAuthor"}, 435 | }, 436 | }, 437 | ProcessRower: false, 438 | }, 439 | }, 440 | Out: { 441 | &looker.InterfaceElement{ 442 | ImportPath: looker.ImportElement{}, 443 | UserType: "error", 444 | }, 445 | }, 446 | }, 447 | &looker.Method{ 448 | Name: "UpdateAuthorResult", 449 | In: { 450 | &looker.InterfaceElement{ 451 | ImportPath: looker.ImportElement{Path:"context", Alias:""}, 452 | UserType: "Context", 453 | }, 454 | &looker.StructElement{ 455 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 456 | UserType: "UpdateAuthorReq", 457 | IsPointer: true, 458 | Fields: { 459 | { 460 | Name: "ID", 461 | ImportPath: looker.ImportElement{}, 462 | BaseType: "int64", 463 | UserType: "int64", 464 | Anonymous: false, 465 | Tag: "", 466 | Parents: {}, 467 | }, 468 | { 469 | Name: "Name", 470 | ImportPath: looker.ImportElement{}, 471 | BaseType: "string", 472 | UserType: "string", 473 | Anonymous: false, 474 | Tag: "", 475 | Parents: {"BaseAuthor"}, 476 | }, 477 | { 478 | Name: "Desc", 479 | ImportPath: looker.ImportElement{}, 480 | BaseType: "string", 481 | UserType: "string", 482 | Anonymous: false, 483 | Tag: "", 484 | Parents: {"BaseAuthor"}, 485 | }, 486 | }, 487 | ProcessRower: false, 488 | }, 489 | }, 490 | Out: { 491 | &looker.InterfaceElement{ 492 | ImportPath: looker.ImportElement{Path:"database/sql", Alias:""}, 493 | UserType: "Result", 494 | }, 495 | &looker.InterfaceElement{ 496 | ImportPath: looker.ImportElement{}, 497 | UserType: "error", 498 | }, 499 | }, 500 | }, 501 | }, 502 | } -------------------------------------------------------------------------------- /looker/testdata/package.golden: -------------------------------------------------------------------------------- 1 | &looker.Package{ 2 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 3 | Interfaces: { 4 | &looker.Interface{ 5 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 6 | UserType: "Store", 7 | Methods: { 8 | &looker.Method{ 9 | Name: "BeginTx", 10 | In: { 11 | &looker.InterfaceElement{ 12 | ImportPath: looker.ImportElement{Path:"context", Alias:""}, 13 | UserType: "Context", 14 | }, 15 | &looker.StructElement{ 16 | ImportPath: looker.ImportElement{Path:"database/sql", Alias:""}, 17 | UserType: "TxOptions", 18 | IsPointer: true, 19 | Fields: { 20 | { 21 | Name: "Isolation", 22 | ImportPath: looker.ImportElement{Path:"database/sql", Alias:""}, 23 | BaseType: "int", 24 | UserType: "IsolationLevel", 25 | Anonymous: false, 26 | Tag: "", 27 | Parents: {}, 28 | }, 29 | { 30 | Name: "ReadOnly", 31 | ImportPath: looker.ImportElement{}, 32 | BaseType: "bool", 33 | UserType: "bool", 34 | Anonymous: false, 35 | Tag: "", 36 | Parents: {}, 37 | }, 38 | }, 39 | ProcessRower: false, 40 | }, 41 | }, 42 | Out: { 43 | &looker.InterfaceElement{ 44 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 45 | UserType: "Store", 46 | }, 47 | &looker.InterfaceElement{ 48 | ImportPath: looker.ImportElement{}, 49 | UserType: "error", 50 | }, 51 | }, 52 | }, 53 | &looker.Method{ 54 | Name: "CreateAuthor", 55 | In: { 56 | &looker.InterfaceElement{ 57 | ImportPath: looker.ImportElement{Path:"context", Alias:""}, 58 | UserType: "Context", 59 | }, 60 | &looker.StructElement{ 61 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 62 | UserType: "CreateAuthorReq", 63 | IsPointer: false, 64 | Fields: { 65 | { 66 | Name: "Name", 67 | ImportPath: looker.ImportElement{}, 68 | BaseType: "string", 69 | UserType: "string", 70 | Anonymous: false, 71 | Tag: "", 72 | Parents: {"BaseAuthor"}, 73 | }, 74 | { 75 | Name: "Desc", 76 | ImportPath: looker.ImportElement{}, 77 | BaseType: "string", 78 | UserType: "string", 79 | Anonymous: false, 80 | Tag: "", 81 | Parents: {"BaseAuthor"}, 82 | }, 83 | }, 84 | ProcessRower: false, 85 | }, 86 | }, 87 | Out: { 88 | &looker.StructElement{ 89 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 90 | UserType: "CreateAuthorResp", 91 | IsPointer: false, 92 | Fields: { 93 | { 94 | Name: "ID", 95 | ImportPath: looker.ImportElement{}, 96 | BaseType: "int64", 97 | UserType: "int64", 98 | Anonymous: false, 99 | Tag: "", 100 | Parents: {}, 101 | }, 102 | { 103 | Name: "CreatedAt", 104 | ImportPath: looker.ImportElement{Path:"time", Alias:""}, 105 | BaseType: "struct", 106 | UserType: "Time", 107 | Anonymous: false, 108 | Tag: "", 109 | Parents: {}, 110 | }, 111 | }, 112 | ProcessRower: false, 113 | }, 114 | &looker.InterfaceElement{ 115 | ImportPath: looker.ImportElement{}, 116 | UserType: "error", 117 | }, 118 | }, 119 | }, 120 | &looker.Method{ 121 | Name: "CreateAuthorPtr", 122 | In: { 123 | &looker.InterfaceElement{ 124 | ImportPath: looker.ImportElement{Path:"context", Alias:""}, 125 | UserType: "Context", 126 | }, 127 | &looker.StructElement{ 128 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 129 | UserType: "CreateAuthorReq", 130 | IsPointer: false, 131 | Fields: { 132 | { 133 | Name: "Name", 134 | ImportPath: looker.ImportElement{}, 135 | BaseType: "string", 136 | UserType: "string", 137 | Anonymous: false, 138 | Tag: "", 139 | Parents: {"BaseAuthor"}, 140 | }, 141 | { 142 | Name: "Desc", 143 | ImportPath: looker.ImportElement{}, 144 | BaseType: "string", 145 | UserType: "string", 146 | Anonymous: false, 147 | Tag: "", 148 | Parents: {"BaseAuthor"}, 149 | }, 150 | }, 151 | ProcessRower: false, 152 | }, 153 | }, 154 | Out: { 155 | &looker.StructElement{ 156 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 157 | UserType: "CreateAuthorResp", 158 | IsPointer: true, 159 | Fields: { 160 | { 161 | Name: "ID", 162 | ImportPath: looker.ImportElement{}, 163 | BaseType: "int64", 164 | UserType: "int64", 165 | Anonymous: false, 166 | Tag: "", 167 | Parents: {}, 168 | }, 169 | { 170 | Name: "CreatedAt", 171 | ImportPath: looker.ImportElement{Path:"time", Alias:""}, 172 | BaseType: "struct", 173 | UserType: "Time", 174 | Anonymous: false, 175 | Tag: "", 176 | Parents: {}, 177 | }, 178 | }, 179 | ProcessRower: false, 180 | }, 181 | &looker.InterfaceElement{ 182 | ImportPath: looker.ImportElement{}, 183 | UserType: "error", 184 | }, 185 | }, 186 | }, 187 | &looker.Method{ 188 | Name: "GetAuthors", 189 | In: { 190 | &looker.InterfaceElement{ 191 | ImportPath: looker.ImportElement{Path:"context", Alias:""}, 192 | UserType: "Context", 193 | }, 194 | &looker.StructElement{ 195 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 196 | UserType: "GetAuthorsReq", 197 | IsPointer: false, 198 | Fields: { 199 | { 200 | Name: "ID", 201 | ImportPath: looker.ImportElement{}, 202 | BaseType: "int64", 203 | UserType: "int64", 204 | Anonymous: false, 205 | Tag: "id", 206 | Parents: {}, 207 | }, 208 | { 209 | Name: "Tags", 210 | ImportPath: looker.ImportElement{}, 211 | BaseType: "slice", 212 | UserType: "", 213 | Anonymous: false, 214 | Tag: "tags", 215 | Parents: {"Tags"}, 216 | }, 217 | }, 218 | ProcessRower: true, 219 | }, 220 | }, 221 | Out: { 222 | &looker.SliceElement{ 223 | ImportPath: looker.ImportElement{Path:"", Alias:"bookstore"}, 224 | UserType: "", 225 | Item: &looker.StructElement{ 226 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 227 | UserType: "GetAuthorsResp", 228 | IsPointer: true, 229 | Fields: { 230 | { 231 | Name: "ID", 232 | ImportPath: looker.ImportElement{}, 233 | BaseType: "int64", 234 | UserType: "int64", 235 | Anonymous: false, 236 | Tag: "id", 237 | Parents: {}, 238 | }, 239 | { 240 | Name: "CreatedAt", 241 | ImportPath: looker.ImportElement{Path:"time", Alias:""}, 242 | BaseType: "struct", 243 | UserType: "Time", 244 | Anonymous: false, 245 | Tag: "created_at", 246 | Parents: {}, 247 | }, 248 | { 249 | Name: "Name", 250 | ImportPath: looker.ImportElement{}, 251 | BaseType: "string", 252 | UserType: "string", 253 | Anonymous: false, 254 | Tag: "name", 255 | Parents: {}, 256 | }, 257 | { 258 | Name: "Desc", 259 | ImportPath: looker.ImportElement{}, 260 | BaseType: "string", 261 | UserType: "string", 262 | Anonymous: false, 263 | Tag: "desc", 264 | Parents: {}, 265 | }, 266 | { 267 | Name: "Tags", 268 | ImportPath: looker.ImportElement{}, 269 | BaseType: "slice", 270 | UserType: "", 271 | Anonymous: false, 272 | Tag: "tags", 273 | Parents: {"Tags"}, 274 | }, 275 | }, 276 | ProcessRower: true, 277 | }, 278 | IsPointer: false, 279 | }, 280 | &looker.InterfaceElement{ 281 | ImportPath: looker.ImportElement{}, 282 | UserType: "error", 283 | }, 284 | }, 285 | }, 286 | &looker.Method{ 287 | Name: "GetBooks", 288 | In: { 289 | &looker.InterfaceElement{ 290 | ImportPath: looker.ImportElement{Path:"context", Alias:""}, 291 | UserType: "Context", 292 | }, 293 | &looker.StructElement{ 294 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 295 | UserType: "GetBooksReq", 296 | IsPointer: false, 297 | Fields: { 298 | }, 299 | ProcessRower: false, 300 | }, 301 | }, 302 | Out: { 303 | &looker.SliceElement{ 304 | ImportPath: looker.ImportElement{Path:"", Alias:"bookstore"}, 305 | UserType: "", 306 | Item: &looker.StructElement{ 307 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 308 | UserType: "GetBooksResp", 309 | IsPointer: true, 310 | Fields: { 311 | { 312 | Name: "ID", 313 | ImportPath: looker.ImportElement{}, 314 | BaseType: "int64", 315 | UserType: "int64", 316 | Anonymous: false, 317 | Tag: "id", 318 | Parents: {}, 319 | }, 320 | { 321 | Name: "Title", 322 | ImportPath: looker.ImportElement{}, 323 | BaseType: "string", 324 | UserType: "string", 325 | Anonymous: false, 326 | Tag: "title", 327 | Parents: {}, 328 | }, 329 | }, 330 | ProcessRower: false, 331 | }, 332 | IsPointer: false, 333 | }, 334 | &looker.InterfaceElement{ 335 | ImportPath: looker.ImportElement{}, 336 | UserType: "error", 337 | }, 338 | }, 339 | }, 340 | &looker.Method{ 341 | Name: "SameName", 342 | In: { 343 | &looker.InterfaceElement{ 344 | ImportPath: looker.ImportElement{Path:"context", Alias:""}, 345 | UserType: "Context", 346 | }, 347 | &looker.StructElement{ 348 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 349 | UserType: "SameNameReq", 350 | IsPointer: false, 351 | Fields: { 352 | }, 353 | ProcessRower: false, 354 | }, 355 | }, 356 | Out: { 357 | &looker.StructElement{ 358 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 359 | UserType: "SameNameResp", 360 | IsPointer: true, 361 | Fields: { 362 | { 363 | Name: "Bar", 364 | ImportPath: looker.ImportElement{}, 365 | BaseType: "string", 366 | UserType: "string", 367 | Anonymous: false, 368 | Tag: "", 369 | Parents: {}, 370 | }, 371 | { 372 | Name: "Bar", 373 | ImportPath: looker.ImportElement{}, 374 | BaseType: "string", 375 | UserType: "string", 376 | Anonymous: false, 377 | Tag: "", 378 | Parents: {"Foo"}, 379 | }, 380 | }, 381 | ProcessRower: false, 382 | }, 383 | &looker.InterfaceElement{ 384 | ImportPath: looker.ImportElement{}, 385 | UserType: "error", 386 | }, 387 | }, 388 | }, 389 | &looker.Method{ 390 | Name: "Tx", 391 | In: { 392 | }, 393 | Out: { 394 | &looker.InterfaceElement{ 395 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal", Alias:""}, 396 | UserType: "Transaction", 397 | }, 398 | }, 399 | }, 400 | &looker.Method{ 401 | Name: "UpdateAuthor", 402 | In: { 403 | &looker.InterfaceElement{ 404 | ImportPath: looker.ImportElement{Path:"context", Alias:""}, 405 | UserType: "Context", 406 | }, 407 | &looker.StructElement{ 408 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 409 | UserType: "UpdateAuthorReq", 410 | IsPointer: true, 411 | Fields: { 412 | { 413 | Name: "ID", 414 | ImportPath: looker.ImportElement{}, 415 | BaseType: "int64", 416 | UserType: "int64", 417 | Anonymous: false, 418 | Tag: "", 419 | Parents: {}, 420 | }, 421 | { 422 | Name: "Name", 423 | ImportPath: looker.ImportElement{}, 424 | BaseType: "string", 425 | UserType: "string", 426 | Anonymous: false, 427 | Tag: "", 428 | Parents: {"BaseAuthor"}, 429 | }, 430 | { 431 | Name: "Desc", 432 | ImportPath: looker.ImportElement{}, 433 | BaseType: "string", 434 | UserType: "string", 435 | Anonymous: false, 436 | Tag: "", 437 | Parents: {"BaseAuthor"}, 438 | }, 439 | }, 440 | ProcessRower: false, 441 | }, 442 | }, 443 | Out: { 444 | &looker.InterfaceElement{ 445 | ImportPath: looker.ImportElement{}, 446 | UserType: "error", 447 | }, 448 | }, 449 | }, 450 | &looker.Method{ 451 | Name: "UpdateAuthorResult", 452 | In: { 453 | &looker.InterfaceElement{ 454 | ImportPath: looker.ImportElement{Path:"context", Alias:""}, 455 | UserType: "Context", 456 | }, 457 | &looker.StructElement{ 458 | ImportPath: looker.ImportElement{Path:"github.com/go-gad/sal/examples/bookstore", Alias:""}, 459 | UserType: "UpdateAuthorReq", 460 | IsPointer: true, 461 | Fields: { 462 | { 463 | Name: "ID", 464 | ImportPath: looker.ImportElement{}, 465 | BaseType: "int64", 466 | UserType: "int64", 467 | Anonymous: false, 468 | Tag: "", 469 | Parents: {}, 470 | }, 471 | { 472 | Name: "Name", 473 | ImportPath: looker.ImportElement{}, 474 | BaseType: "string", 475 | UserType: "string", 476 | Anonymous: false, 477 | Tag: "", 478 | Parents: {"BaseAuthor"}, 479 | }, 480 | { 481 | Name: "Desc", 482 | ImportPath: looker.ImportElement{}, 483 | BaseType: "string", 484 | UserType: "string", 485 | Anonymous: false, 486 | Tag: "", 487 | Parents: {"BaseAuthor"}, 488 | }, 489 | }, 490 | ProcessRower: false, 491 | }, 492 | }, 493 | Out: { 494 | &looker.InterfaceElement{ 495 | ImportPath: looker.ImportElement{Path:"database/sql", Alias:""}, 496 | UserType: "Result", 497 | }, 498 | &looker.InterfaceElement{ 499 | ImportPath: looker.ImportElement{}, 500 | UserType: "error", 501 | }, 502 | }, 503 | }, 504 | }, 505 | }, 506 | }, 507 | } -------------------------------------------------------------------------------- /looker/testdata/store_client.go: -------------------------------------------------------------------------------- 1 | // Code generated by SalGen. DO NOT EDIT. 2 | package testdata 3 | 4 | import ( 5 | "context" 6 | "database/sql" 7 | "github.com/go-gad/sal" 8 | "github.com/go-gad/sal/looker/testdata/foo-bar" 9 | "github.com/pkg/errors" 10 | ) 11 | 12 | type SalStore struct { 13 | Store 14 | handler sal.QueryHandler 15 | parent sal.QueryHandler 16 | ctrl *sal.Controller 17 | txOpened bool 18 | } 19 | 20 | func NewStore(h sal.QueryHandler, options ...sal.ClientOption) *SalStore { 21 | s := &SalStore{ 22 | handler: h, 23 | ctrl: sal.NewController(options...), 24 | txOpened: false, 25 | } 26 | 27 | return s 28 | } 29 | 30 | func (s *SalStore) BeginTx(ctx context.Context, opts *sql.TxOptions) (Store, error) { 31 | dbConn, ok := s.handler.(sal.TransactionBegin) 32 | if !ok { 33 | return nil, errors.New("handler doesn't satisfy the interface TransactionBegin") 34 | } 35 | var ( 36 | err error 37 | tx *sql.Tx 38 | ) 39 | 40 | ctx = context.WithValue(ctx, sal.ContextKeyTxOpened, s.txOpened) 41 | ctx = context.WithValue(ctx, sal.ContextKeyOperationType, "Begin") 42 | ctx = context.WithValue(ctx, sal.ContextKeyMethodName, "BeginTx") 43 | 44 | for _, fn := range s.ctrl.BeforeQuery { 45 | var fnz sal.FinalizerFunc 46 | ctx, fnz = fn(ctx, "BEGIN", nil) 47 | if fnz != nil { 48 | defer func() { fnz(ctx, err) }() 49 | } 50 | } 51 | 52 | tx, err = dbConn.BeginTx(ctx, opts) 53 | if err != nil { 54 | err = errors.Wrap(err, "failed to start tx") 55 | return nil, err 56 | } 57 | 58 | newClient := &SalStore{ 59 | handler: tx, 60 | parent: s.handler, 61 | ctrl: s.ctrl, 62 | txOpened: true, 63 | } 64 | 65 | return newClient, nil 66 | } 67 | 68 | func (s *SalStore) Tx() sal.Transaction { 69 | if tx, ok := s.handler.(sal.SqlTx); ok { 70 | return sal.NewWrappedTx(tx, s.ctrl) 71 | } 72 | return nil 73 | } 74 | func (s *SalStore) UpdateAuthor(ctx context.Context, req *foo.Body) error { 75 | var ( 76 | err error 77 | rawQuery = req.Query() 78 | reqMap = make(sal.RowMap) 79 | ) 80 | 81 | ctx = context.WithValue(ctx, sal.ContextKeyTxOpened, s.txOpened) 82 | ctx = context.WithValue(ctx, sal.ContextKeyOperationType, "Exec") 83 | ctx = context.WithValue(ctx, sal.ContextKeyMethodName, "UpdateAuthor") 84 | 85 | pgQuery, args := sal.ProcessQueryAndArgs(rawQuery, reqMap) 86 | 87 | stmt, err := s.ctrl.PrepareStmt(ctx, s.parent, s.handler, pgQuery) 88 | if err != nil { 89 | return errors.WithStack(err) 90 | } 91 | 92 | for _, fn := range s.ctrl.BeforeQuery { 93 | var fnz sal.FinalizerFunc 94 | ctx, fnz = fn(ctx, rawQuery, req) 95 | if fnz != nil { 96 | defer func() { fnz(ctx, err) }() 97 | } 98 | } 99 | 100 | _, err = stmt.ExecContext(ctx, args...) 101 | if err != nil { 102 | return errors.Wrap(err, "failed to execute Exec") 103 | } 104 | 105 | return nil 106 | } 107 | 108 | // compile time checks 109 | var _ Store = &SalStore{} 110 | -------------------------------------------------------------------------------- /looker/testdata/testdata.go: -------------------------------------------------------------------------------- 1 | package testdata 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/go-gad/sal" 7 | "github.com/go-gad/sal/looker/testdata/foo-bar" 8 | ) 9 | 10 | type Req1 struct { 11 | ID int64 `sql:"id"` 12 | Name string 13 | } 14 | 15 | type List1 []*Req1 16 | 17 | func Foo(ctx context.Context, req []*Req1) error { return nil } 18 | 19 | type Req2 struct { 20 | ID int64 `sql:"id"` 21 | } 22 | 23 | func (r *Req2) ProcessRow(rm sal.RowMap) {} 24 | 25 | type Lvl1 struct { 26 | Name string 27 | Desc string 28 | Lvl21 29 | Lvl22 30 | } 31 | 32 | type Lvl21 struct { 33 | Foo string 34 | Bar string 35 | } 36 | type Lvl22 struct { 37 | Foo string 38 | Bar string 39 | Lvl3 40 | } 41 | 42 | type Lvl3 struct { 43 | Foo string 44 | Bar string 45 | } 46 | 47 | type Store interface { 48 | UpdateAuthor(context.Context, *foo.Body) error 49 | } 50 | -------------------------------------------------------------------------------- /sal.go: -------------------------------------------------------------------------------- 1 | package sal 2 | 3 | import ( 4 | "context" 5 | "database/sql" 6 | "fmt" 7 | "regexp" 8 | "sync" 9 | 10 | "github.com/pkg/errors" 11 | ) 12 | 13 | // reQueryArgs represents the regexp to define named args in query. 14 | var reQueryArgs = regexp.MustCompile("@[A-Za-z0-9_]+") 15 | 16 | // QueryArgs receives the query with named arguments 17 | // and returns a query with posgtresql placeholders and a ordered slice named args. 18 | // 19 | // Naive implementation. 20 | func QueryArgs(query string) (string, []string) { 21 | var args = make([]string, 0) 22 | pgQuery := reQueryArgs.ReplaceAllStringFunc(query, func(arg string) string { 23 | args = append(args, arg[1:]) 24 | return fmt.Sprintf("$%d", len(args)) 25 | }) 26 | return pgQuery, args 27 | } 28 | 29 | // RowMap contains mapping between column name in database and interface of value. 30 | type RowMap map[string][]interface{} 31 | 32 | func (rm RowMap) AppendTo(key string, val interface{}) { 33 | rm[key] = append(rm[key], val) 34 | } 35 | 36 | func (rm RowMap) Get(key string) interface{} { 37 | v := rm[key] 38 | if len(v) == 0 { 39 | return nil 40 | } 41 | return v[0] 42 | } 43 | 44 | func (rm RowMap) Set(key string, val interface{}) { 45 | if _, ok := rm[key]; ok { 46 | rm[key][0] = val 47 | } 48 | rm[key] = []interface{}{val} 49 | } 50 | 51 | func (rm RowMap) GetByIndex(key string, index int) interface{} { 52 | v := rm[key] 53 | if len(v) == 0 || len(v) < index+1 { 54 | return nil 55 | } 56 | return v[index] 57 | } 58 | 59 | type mapIndex map[string]int 60 | 61 | func (m mapIndex) NextVal(key string) int { 62 | v, ok := m[key] 63 | if !ok { 64 | m[key] = 1 65 | return 0 66 | } 67 | m[key] = v + 1 68 | return v 69 | } 70 | 71 | // ProcessQueryAndArgs process query with named args to driver specific query. 72 | func ProcessQueryAndArgs(query string, reqMap RowMap) (string, []interface{}) { 73 | pgQuery, argsNames := QueryArgs(query) 74 | var args = make([]interface{}, 0, len(argsNames)) 75 | for _, name := range argsNames { 76 | args = append(args, reqMap.Get(name)) 77 | } 78 | return pgQuery, args 79 | } 80 | 81 | type skippedField interface{} 82 | 83 | func GetDests(cols []string, respMap RowMap) []interface{} { 84 | var ( 85 | ind = make(mapIndex) 86 | dest = make([]interface{}, 0, len(cols)) 87 | ) 88 | var n skippedField 89 | for _, v := range cols { 90 | d := respMap.GetByIndex(v, ind.NextVal(v)) 91 | if d == nil { 92 | d = &n 93 | } 94 | dest = append(dest, d) 95 | } 96 | 97 | return dest 98 | } 99 | 100 | // ProcessRower is an interface that defines the signature of method of request or response 101 | // that can allow to write pre processor of RowMap values. 102 | // type GetAuthorsReq struct { 103 | // ID int64 `sql:"id"` 104 | // Tags []int64 `sql:"tags"` 105 | // } 106 | // 107 | // func (r GetAuthorsReq) ProcessRow(rowMap sal.RowMap) { 108 | // rowMap.Set("tags", pq.Array(r.Tags)) 109 | // } 110 | // As an argument method receives the RowMap object. 111 | type ProcessRower interface { 112 | ProcessRow(rowMap RowMap) 113 | } 114 | 115 | // QueryHandler describes the methods that are required to pass to constructor of the object 116 | // implementation of user interface. 117 | type QueryHandler interface { 118 | QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) 119 | ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) 120 | PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) 121 | } 122 | 123 | // TransactionBegin describes the signature of method of user interface to start transaction. 124 | type TransactionBegin interface { 125 | BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) 126 | } 127 | 128 | // Txer describes the method to return implementation of Transaction interface. 129 | type Txer interface { 130 | Tx() Transaction 131 | } 132 | 133 | type SqlTx interface { 134 | QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) 135 | ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) 136 | PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) 137 | StmtContext(ctx context.Context, stmt *sql.Stmt) *sql.Stmt 138 | Commit() error 139 | Rollback() error 140 | } 141 | 142 | // Transaction is an interface that describes the method to work with transaction object. 143 | // Signature is similar to sql.Tx. The difference is Commit and Rollback methods. 144 | // Its methods work with context. 145 | type Transaction interface { 146 | QueryHandler 147 | StmtContext(ctx context.Context, stmt *sql.Stmt) *sql.Stmt 148 | Commit(ctx context.Context) error 149 | Rollback(ctx context.Context) error 150 | } 151 | 152 | // WrappedTx is a struct that is an implementation of Transaction interface. 153 | type WrappedTx struct { 154 | Tx SqlTx 155 | ctrl *Controller 156 | } 157 | 158 | // NewWrappedTx returns the WrappedTx object. 159 | func NewWrappedTx(tx SqlTx, ctrl *Controller) *WrappedTx { 160 | if ctrl == nil { 161 | ctrl = NewController() 162 | } 163 | return &WrappedTx{Tx: tx, ctrl: ctrl} 164 | } 165 | 166 | // QueryContext executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query. 167 | func (wtx *WrappedTx) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { 168 | ctx = context.WithValue(ctx, ContextKeyTxOpened, true) 169 | ctx = context.WithValue(ctx, ContextKeyOperationType, OperationTypeQuery.String()) 170 | var ( 171 | resp *sql.Rows 172 | err error 173 | ) 174 | for _, fn := range wtx.ctrl.BeforeQuery { 175 | var fnz FinalizerFunc 176 | ctx, fnz = fn(ctx, query, args) 177 | if fnz != nil { 178 | defer func() { fnz(ctx, err) }() 179 | } 180 | } 181 | 182 | resp, err = wtx.Tx.QueryContext(ctx, query, args...) 183 | 184 | return resp, err 185 | } 186 | 187 | // Exec executes a query without returning any rows. The args are for any placeholder parameters in the query. 188 | func (wtx *WrappedTx) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { 189 | ctx = context.WithValue(ctx, ContextKeyTxOpened, true) 190 | ctx = context.WithValue(ctx, ContextKeyOperationType, OperationTypeExec.String()) 191 | var ( 192 | resp sql.Result 193 | err error 194 | ) 195 | for _, fn := range wtx.ctrl.BeforeQuery { 196 | var fnz FinalizerFunc 197 | ctx, fnz = fn(ctx, query, args) 198 | if fnz != nil { 199 | defer func() { fnz(ctx, err) }() 200 | } 201 | } 202 | 203 | resp, err = wtx.Tx.ExecContext(ctx, query, args...) 204 | 205 | return resp, err 206 | } 207 | 208 | // PrepareContext creates a prepared statement for later queries or executions. 209 | // Multiple queries or executions may be run concurrently from the returned statement. 210 | // The caller must call the statement's Close method when the statement is no longer needed. 211 | // 212 | //The provided context is used for the preparation of the statement, not for the execution of the statement. 213 | func (wtx *WrappedTx) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { 214 | ctx = context.WithValue(ctx, ContextKeyTxOpened, true) 215 | ctx = context.WithValue(ctx, ContextKeyOperationType, OperationTypePrepare.String()) 216 | var ( 217 | resp *sql.Stmt 218 | err error 219 | ) 220 | for _, fn := range wtx.ctrl.BeforeQuery { 221 | var fnz FinalizerFunc 222 | ctx, fnz = fn(ctx, query, nil) 223 | if fnz != nil { 224 | defer func() { fnz(ctx, err) }() 225 | } 226 | } 227 | 228 | resp, err = wtx.Tx.PrepareContext(ctx, query) 229 | 230 | return resp, err 231 | } 232 | 233 | // Stmt returns a transaction-specific prepared statement from an existing statement. 234 | func (wtx *WrappedTx) StmtContext(ctx context.Context, stmt *sql.Stmt) *sql.Stmt { 235 | ctx = context.WithValue(ctx, ContextKeyTxOpened, true) 236 | ctx = context.WithValue(ctx, ContextKeyOperationType, OperationTypeStmt.String()) 237 | for _, fn := range wtx.ctrl.BeforeQuery { 238 | var fnz FinalizerFunc 239 | ctx, fnz = fn(ctx, "", nil) 240 | if fnz != nil { 241 | defer func() { fnz(ctx, nil) }() 242 | } 243 | } 244 | 245 | return wtx.Tx.StmtContext(ctx, stmt) 246 | } 247 | 248 | // Commit commits the transaction. 249 | func (wtx *WrappedTx) Commit(ctx context.Context) error { 250 | ctx = context.WithValue(ctx, ContextKeyTxOpened, true) 251 | ctx = context.WithValue(ctx, ContextKeyOperationType, OperationTypeCommit.String()) 252 | ctx = context.WithValue(ctx, ContextKeyMethodName, "Commit") 253 | var err error 254 | for _, fn := range wtx.ctrl.BeforeQuery { 255 | var fnz FinalizerFunc 256 | ctx, fnz = fn(ctx, "COMMIT", nil) 257 | if fnz != nil { 258 | defer func() { fnz(ctx, err) }() 259 | } 260 | } 261 | 262 | err = wtx.Tx.Commit() 263 | 264 | return err 265 | } 266 | 267 | // Rollback aborts the transaction. 268 | func (wtx *WrappedTx) Rollback(ctx context.Context) error { 269 | ctx = context.WithValue(ctx, ContextKeyTxOpened, true) 270 | ctx = context.WithValue(ctx, ContextKeyOperationType, OperationTypeRollback.String()) 271 | ctx = context.WithValue(ctx, ContextKeyMethodName, "Rollback") 272 | var err error 273 | for _, fn := range wtx.ctrl.BeforeQuery { 274 | var fnz FinalizerFunc 275 | ctx, fnz = fn(ctx, "ROLLBACK", nil) 276 | if fnz != nil { 277 | defer func() { fnz(ctx, err) }() 278 | } 279 | } 280 | 281 | err = wtx.Tx.Rollback() 282 | 283 | return err 284 | } 285 | 286 | // Controller is a manager of query processing. Contains the stack of middlewares 287 | // and cache of prepared statements. 288 | type Controller struct { 289 | BeforeQuery []BeforeQueryFunc 290 | sync.RWMutex 291 | CacheStmts map[string]*sql.Stmt 292 | } 293 | 294 | // NewController retunes a new object of Controller. 295 | func NewController(options ...ClientOption) *Controller { 296 | ctrl := &Controller{ 297 | BeforeQuery: []BeforeQueryFunc{}, 298 | CacheStmts: make(map[string]*sql.Stmt), 299 | } 300 | for _, option := range options { 301 | option(ctrl) 302 | } 303 | return ctrl 304 | } 305 | 306 | func (ctrl *Controller) findStmt(query string) *sql.Stmt { 307 | ctrl.RLock() 308 | stmt, ok := ctrl.CacheStmts[query] 309 | ctrl.RUnlock() 310 | if ok { 311 | return stmt 312 | } 313 | 314 | return nil 315 | } 316 | 317 | func (ctrl *Controller) putStmt(query string, stmt *sql.Stmt) { 318 | ctrl.Lock() 319 | ctrl.CacheStmts[query] = stmt 320 | ctrl.Unlock() 321 | } 322 | 323 | func (ctrl *Controller) prepareStmt(ctx context.Context, qh QueryHandler, query string) (*sql.Stmt, error) { 324 | var err error 325 | ctx = context.WithValue(ctx, ContextKeyOperationType, OperationTypePrepare.String()) 326 | for _, fn := range ctrl.BeforeQuery { 327 | var fnz FinalizerFunc 328 | ctx, fnz = fn(ctx, query, nil) 329 | if fnz != nil { 330 | defer func() { fnz(ctx, err) }() 331 | } 332 | } 333 | 334 | stmt, err := qh.PrepareContext(ctx, query) 335 | if err != nil { 336 | return nil, err 337 | } 338 | 339 | return stmt, nil 340 | } 341 | 342 | // PrepareStmt returns the prepared statements. If stmt is presented in cache then it will be returned. 343 | // if not, stmt will be prepared and put to cache. 344 | func (ctrl *Controller) PrepareStmt(ctx context.Context, parent QueryHandler, qh QueryHandler, query string) (*sql.Stmt, error) { 345 | var ( 346 | err error 347 | stmt *sql.Stmt 348 | ) 349 | 350 | txOpened, _ := ctx.Value(ContextKeyTxOpened).(bool) 351 | stmt = ctrl.findStmt(query) 352 | if stmt == nil && !txOpened { 353 | stmt, err = ctrl.prepareStmt(ctx, qh, query) 354 | if err != nil { 355 | return nil, errors.Wrapf(err, "failed to prepare stmt on query %q", query) 356 | } 357 | ctrl.putStmt(query, stmt) 358 | } 359 | 360 | if txOpened { 361 | txh, ok := qh.(*sql.Tx) 362 | if !ok { 363 | return nil, errors.New("failed to get transaction handler") 364 | } 365 | if stmt == nil { 366 | if parent != nil { 367 | stmt, err = ctrl.prepareStmt(ctx, parent, query) 368 | if err != nil { 369 | return nil, errors.Wrapf(err, "failed to prepare stmt with conn on query %q", query) 370 | } 371 | ctrl.putStmt(query, stmt) 372 | stmt = txh.StmtContext(ctx, stmt) 373 | } else { 374 | stmt, err = ctrl.prepareStmt(ctx, txh, query) 375 | if err != nil { 376 | return nil, errors.Wrapf(err, "failed to prepare stmt with tx on query %q", query) 377 | } 378 | } 379 | } else { 380 | stmt = txh.StmtContext(ctx, stmt) 381 | } 382 | } 383 | 384 | return stmt, nil 385 | } 386 | 387 | type contextKey int 388 | 389 | const ( 390 | // ContextKeyTxOpened is a key of bool value in context. If true it means that transaction is opened. 391 | ContextKeyTxOpened contextKey = iota 392 | // ContextKeyOperationType is a key of value that describes the operation type. See consts OperationType*. 393 | ContextKeyOperationType 394 | // ContextKeyMethodName contains the method name from user interface. 395 | ContextKeyMethodName 396 | ) 397 | 398 | // ClientOption sets to controller the optional parameters for clients. 399 | type ClientOption func(ctrl *Controller) 400 | 401 | // BeforeQuery sets the BeforeQueryFunc that is executed before the query. 402 | func BeforeQuery(before ...BeforeQueryFunc) ClientOption { 403 | return func(ctrl *Controller) { ctrl.BeforeQuery = append(ctrl.BeforeQuery, before...) } 404 | } 405 | 406 | // BeforeQueryFunc is called before the query execution but after the preparing stmts. 407 | // Returns the FinalizerFunc. 408 | type BeforeQueryFunc func(ctx context.Context, query string, req interface{}) (context.Context, FinalizerFunc) 409 | 410 | // FinalizerFunc is executed after the query execution. 411 | type FinalizerFunc func(ctx context.Context, err error) 412 | 413 | // OperationType is a datatype for operation types. 414 | type OperationType int 415 | 416 | const ( 417 | // OperationTypeQueryRow is a handler.Query operation and single row in response (like db.QueryRow). 418 | OperationTypeQueryRow OperationType = iota 419 | // OperationTypeQuery is a handler.Query operation. 420 | OperationTypeQuery 421 | // OperationTypeExec is a handler.Exec operation. 422 | OperationTypeExec 423 | // OperationTypeBegin is a start transaction operation, db.Begin(). 424 | OperationTypeBegin 425 | // OperationTypeCommit is a commits the transaction operation, tx.Commit(). 426 | OperationTypeCommit 427 | // OperationTypeRollback is a aborting the transaction operation, tx.Rollback(). 428 | OperationTypeRollback 429 | // OperationTypePrepare is a prepare statements operation. 430 | OperationTypePrepare 431 | // OperationTypeStmt is a operation of prepare statements on transaction. 432 | OperationTypeStmt 433 | ) 434 | 435 | var operationTypeNames = []string{ 436 | "QueryRow", 437 | "Query", 438 | "Exec", 439 | "Begin", 440 | "Commit", 441 | "Rollback", 442 | "Prepare", 443 | "Stmt", 444 | } 445 | 446 | // String returns the string name of operation. 447 | func (op OperationType) String() string { 448 | return operationTypeNames[op] 449 | } 450 | -------------------------------------------------------------------------------- /sal_test.go: -------------------------------------------------------------------------------- 1 | package sal 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "gopkg.in/DATA-DOG/go-sqlmock.v1" 8 | 9 | "github.com/pkg/errors" 10 | "github.com/stretchr/testify/assert" 11 | ) 12 | 13 | func TestQueryArgs(t *testing.T) { 14 | //t.Skip("todo") 15 | var tt = []struct { 16 | QueryNamed string 17 | QueryPg string 18 | NamedArgs []string 19 | }{ 20 | { 21 | QueryNamed: `UPDATE authors SET name=@name, desc=@desc WHERE id=@id`, 22 | QueryPg: `UPDATE authors SET name=$1, desc=$2 WHERE id=$3`, 23 | NamedArgs: []string{"name", "desc", "id"}, 24 | }, { 25 | QueryNamed: `SELECT id, created_at, name, desc FROM authors WHERE id>@id`, 26 | QueryPg: `SELECT id, created_at, name, desc FROM authors WHERE id>$1`, 27 | NamedArgs: []string{"id"}, 28 | }, 29 | } 30 | for _, tc := range tt { 31 | query, args := QueryArgs(tc.QueryNamed) 32 | assert.Equal(t, tc.QueryPg, query) 33 | assert.Equal(t, tc.NamedArgs, args) 34 | } 35 | } 36 | 37 | func TestMapIndex_NextVal(t *testing.T) { 38 | ind := make(mapIndex) 39 | assert.Equal(t, 0, ind.NextVal("foo")) 40 | assert.Equal(t, 1, ind.NextVal("foo")) 41 | assert.Equal(t, 2, ind.NextVal("foo")) 42 | assert.Equal(t, 0, ind.NextVal("bar")) 43 | assert.Equal(t, 3, ind.NextVal("foo")) 44 | assert.Equal(t, 1, ind.NextVal("bar")) 45 | } 46 | 47 | func TestRowMap(t *testing.T) { 48 | assert := assert.New(t) 49 | rm := make(RowMap) 50 | assert.Nil(rm.Get("foo")) 51 | assert.Nil(rm.GetByIndex("foo", 0)) 52 | rm.AppendTo("foo", 777) 53 | assert.Equal(777, rm.Get("foo")) 54 | assert.Equal(777, rm.GetByIndex("foo", 0)) 55 | assert.Nil(rm.GetByIndex("foo", 1)) 56 | } 57 | 58 | func TestGetDests(t *testing.T) { 59 | assert := assert.New(t) 60 | rm := make(RowMap) 61 | rm.AppendTo("id", 111) 62 | rm.AppendTo("title", "foobar") 63 | cols := []string{"id", "created_at", "title", "desc"} 64 | dest := GetDests(cols, rm) 65 | var n skippedField 66 | expt := []interface{}{111, &n, "foobar", &n} 67 | assert.Equal(expt, dest) 68 | } 69 | 70 | func TestController_PrepareStmt(t *testing.T) { 71 | assert := assert.New(t) 72 | db, mock, err := sqlmock.New() 73 | if err != nil { 74 | t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) 75 | } 76 | defer db.Close() 77 | ctrl := NewController() 78 | ctx := context.Background() 79 | 80 | // PrepareStmt on dbConn 81 | query := "SELECT 1" 82 | mock.ExpectPrepare(query) // on connection 83 | _, err = ctrl.PrepareStmt(ctx, nil, db, query) 84 | assert.NoError(err) 85 | 86 | // Checking prepared stmt in cache 87 | stmt := ctrl.findStmt(query) 88 | assert.NotNil(stmt) 89 | 90 | // Second try with same query on dbConn returns cached stmt 91 | stmt2, err := ctrl.PrepareStmt(ctx, nil, db, query) 92 | assert.NoError(err) 93 | assert.Equal(stmt, stmt2) 94 | 95 | // If something wrong then returns error 96 | mock.ExpectPrepare(`SELECT 2`).WillReturnError(errors.New("bye")) 97 | _, err = ctrl.PrepareStmt(ctx, nil, db, "SELECT 2") 98 | assert.Error(err) 99 | 100 | // open tx connection 101 | mock.ExpectBegin() 102 | tx, err := db.Begin() 103 | assert.NoError(err) 104 | ctx = context.WithValue(ctx, ContextKeyTxOpened, true) 105 | 106 | // try to prepare stmt with dbconn in tx context init an error 107 | _, err = ctrl.PrepareStmt(ctx, nil, db, "SELECT 3") 108 | assert.Error(err) 109 | //t.Logf("error %+v", err) 110 | 111 | // non-cached stmt for query, prepare query on tx 112 | query = "SELECT 4" 113 | mock.ExpectPrepare(query) // on transaction tx.Stmt 114 | _, err = ctrl.PrepareStmt(ctx, nil, tx, query) 115 | assert.NoError(err) 116 | 117 | // something wrong and error 118 | query = "SELECT 41" 119 | mock.ExpectPrepare(query).WillReturnError(errors.New("ops")) // on transaction tx.Stmt 120 | _, err = ctrl.PrepareStmt(ctx, nil, tx, query) 121 | assert.Error(err) 122 | 123 | // if we call BeginTx and after try to perform prepare query 124 | // and cache doesn't contain value 125 | // then stmt is prepared on dbConn and applied to tx 126 | query = "SELECT 5" 127 | mock.ExpectPrepare(query) // on connection 128 | mock.ExpectPrepare(query) // on transaction tx.Stmt 129 | _, err = ctrl.PrepareStmt(ctx, db, tx, query) 130 | assert.NoError(err) 131 | 132 | // error case 133 | query = "SELECT 51" 134 | mock.ExpectPrepare(query).WillReturnError(errors.New("ops")) // on connection 135 | //mock.ExpectPrepare(query) // on transaction tx.Stmt 136 | _, err = ctrl.PrepareStmt(ctx, db, tx, query) 137 | assert.Error(err) 138 | 139 | // second try with first stmt 140 | query = "SELECT 1" 141 | //mock.ExpectPrepare(query) // on transaction tx.Stmt 142 | _, err = ctrl.PrepareStmt(ctx, db, tx, query) 143 | assert.NoError(err) 144 | 145 | assert.Nil(mock.ExpectationsWereMet()) 146 | } 147 | -------------------------------------------------------------------------------- /salgen/generator.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "go/format" 7 | "log" 8 | "strings" 9 | 10 | "reflect" 11 | 12 | "github.com/go-gad/sal" 13 | "github.com/go-gad/sal/looker" 14 | "github.com/pkg/errors" 15 | ) 16 | 17 | const ( 18 | Prefix = "Sal" 19 | ) 20 | 21 | const ( 22 | MethodNameTx string = "Tx" 23 | MethodNameBeginTx string = "BeginTx" 24 | ) 25 | 26 | type generator struct { 27 | buf bytes.Buffer 28 | indent string 29 | } 30 | 31 | func (g *generator) Generate(pkg *looker.Package, dstPkg looker.ImportElement) error { 32 | g.p("// Code generated by SalGen. DO NOT EDIT.") 33 | //g.p("// Generated at %s", time.Now()) 34 | g.p("package %v", dstPkg.Name()) 35 | 36 | paths := ImportPaths(pkg.ImportPaths(), dstPkg.Path) 37 | g.GenerateImportPaths(paths) 38 | 39 | for _, intf := range pkg.Interfaces { 40 | if err := g.GenerateInterface(dstPkg, intf); err != nil { 41 | return err 42 | } 43 | g.p("// compile time checks") 44 | g.p("var _ %s = &%s{}", intf.Name(dstPkg.Path), intf.ImplementationName(Prefix)) 45 | } 46 | 47 | return nil 48 | } 49 | 50 | func (g *generator) GenerateImportPaths(paths []string) { 51 | g.p("import (") 52 | g.p("%q", "database/sql") 53 | for _, p := range paths { 54 | g.p("%q", p) 55 | } 56 | g.p("%q", "github.com/pkg/errors") 57 | g.p("%q", "github.com/go-gad/sal") 58 | g.p(")") 59 | } 60 | 61 | func (g *generator) GenerateInterface(dstPkg looker.ImportElement, intf *looker.Interface) error { 62 | implName := intf.ImplementationName(Prefix) 63 | g.p("type %v struct {", implName) 64 | g.p("%s", intf.Name(dstPkg.Path)) 65 | g.p("handler sal.QueryHandler") 66 | g.p("parent sal.QueryHandler") 67 | g.p("ctrl *sal.Controller") 68 | g.p("txOpened bool") 69 | g.p("}") 70 | 71 | g.p("func New%v(h sal.QueryHandler, options ...sal.ClientOption) *%v {", intf.UserType, implName) 72 | g.p("s := &%s{", implName) 73 | g.p("handler: h,") 74 | g.p("ctrl: sal.NewController(options...),") 75 | g.p("txOpened: false,") 76 | g.p("}") 77 | g.br() 78 | g.p("return s") 79 | g.p("}") 80 | g.br() 81 | 82 | g.GenerateBeginTx(dstPkg, intf) 83 | g.br() 84 | g.GenerateTx(dstPkg, intf) 85 | 86 | for _, mtd := range intf.Methods { 87 | if err := g.GenerateMethod(dstPkg, implName, mtd); err != nil { 88 | return err 89 | } 90 | g.br() 91 | } 92 | 93 | return nil 94 | } 95 | 96 | type prmArgs []string 97 | 98 | func (pa prmArgs) String() string { 99 | return strings.Join(pa, ",") 100 | } 101 | 102 | func (g *generator) GenerateMethod(dstPkg looker.ImportElement, implName string, mtd *looker.Method) error { 103 | switch mtd.Name { 104 | case MethodNameBeginTx, MethodNameTx: 105 | return nil 106 | } 107 | 108 | inArgs := make(prmArgs, 0, 2) 109 | inArgs = append(inArgs, "ctx "+mtd.In[0].Name(dstPkg.Path)) 110 | req := mtd.In[1] 111 | inArgs = append(inArgs, "req "+elementType(req.Pointer(), req.Name(dstPkg.Path))) 112 | 113 | operation := calcOperationType(mtd.Out) 114 | 115 | outArgs := make(prmArgs, 0, 2) 116 | 117 | resp := mtd.Out[0] 118 | if operation == sal.OperationTypeExec { 119 | if isSqlResult(resp) { 120 | outArgs = append(outArgs, elementType(resp.Pointer(), resp.Name(dstPkg.Path))) 121 | } 122 | } else { 123 | outArgs = append(outArgs, elementType(resp.Pointer(), resp.Name(dstPkg.Path))) 124 | } 125 | outArgs = append(outArgs, mtd.Out[len(mtd.Out)-1].Name(dstPkg.Path)) 126 | 127 | g.p("func (s *%v) %v(%v) (%v) {", implName, mtd.Name, inArgs.String(), outArgs.String()) 128 | g.p("var (") 129 | g.p("err error") 130 | g.p("rawQuery = req.Query()") 131 | g.p("reqMap = make(sal.RowMap)") 132 | g.p(")") 133 | g.GenerateRowMap(req, "reqMap", "req") 134 | 135 | g.p("ctx = context.WithValue(ctx, sal.ContextKeyTxOpened, s.txOpened)") 136 | g.p("ctx = context.WithValue(ctx, sal.ContextKeyOperationType, %q)", operation.String()) 137 | g.p("ctx = context.WithValue(ctx, sal.ContextKeyMethodName, %q)", mtd.Name) 138 | g.br() 139 | 140 | g.p("pgQuery, args := sal.ProcessQueryAndArgs(rawQuery, reqMap)") 141 | g.br() 142 | 143 | var errRespStr = responseErrStr(operation, resp, dstPkg.Path) 144 | 145 | g.p("stmt, err := s.ctrl.PrepareStmt(ctx, s.parent, s.handler, pgQuery)") 146 | g.p("if err != nil {") 147 | switch operation { 148 | case sal.OperationTypeQuery, sal.OperationTypeQueryRow: 149 | g.p("return %s, errors.WithStack(err)", errRespStr) 150 | case sal.OperationTypeExec: 151 | if isSqlResult(mtd.Out[0]) { 152 | g.p("return nil, errors.WithStack(err)") 153 | } else { 154 | g.p("return errors.WithStack(err)") 155 | } 156 | } 157 | g.p("}") 158 | g.br() 159 | 160 | g.beforeQueryHook("rawQuery", "req") 161 | g.br() 162 | 163 | switch operation { 164 | case sal.OperationTypeQuery, sal.OperationTypeQueryRow: 165 | g.p("rows, err := stmt.QueryContext(ctx, args...)") 166 | g.ifErr(errRespStr, "failed to execute Query") 167 | g.p("defer rows.Close()") 168 | g.br() 169 | 170 | g.p("cols, err := rows.Columns()") 171 | g.ifErr(errRespStr, "failed to fetch columns") 172 | g.br() 173 | case sal.OperationTypeExec: 174 | if isSqlResult(mtd.Out[0]) { 175 | g.p("res, err := stmt.ExecContext(ctx, args...)") 176 | g.ifErr("nil", "failed to execute Exec") 177 | } else { 178 | g.p("_, err = stmt.ExecContext(ctx, args...)") 179 | g.ifErr("", "failed to execute Exec") 180 | } 181 | 182 | g.br() 183 | } 184 | 185 | if operation == sal.OperationTypeExec { 186 | if isSqlResult(mtd.Out[0]) { 187 | g.p("return res, nil") 188 | } else { 189 | g.p("return nil") 190 | } 191 | g.p("}") 192 | return nil 193 | } 194 | 195 | if operation == sal.OperationTypeQueryRow { 196 | g.p("if !rows.Next() {") 197 | g.p("if err = rows.Err(); err != nil {") 198 | g.p("return %s, errors.Wrap(err, %q)", errRespStr, "rows error") 199 | g.p("}") 200 | g.p("return %s, sql.ErrNoRows", errRespStr) 201 | g.p("}") 202 | g.br() 203 | } 204 | 205 | var respRow looker.Parameter 206 | if operation == sal.OperationTypeQuery { 207 | g.p("var list = make(%s, 0)", resp.Name(dstPkg.Path)) 208 | g.br() 209 | g.p("for rows.Next() {") 210 | respSlice := resp.(*looker.SliceElement) 211 | 212 | respRow = respSlice.Item 213 | } else { 214 | respRow = resp 215 | } 216 | var respRowStr = "resp" 217 | g.p("var %s %s", respRowStr, respRow.Name(dstPkg.Path)) 218 | g.p("var respMap = make(sal.RowMap)") 219 | g.GenerateRowMap(respRow, "respMap", "resp") 220 | 221 | g.p("dest := sal.GetDests(cols, respMap)") 222 | g.br() 223 | 224 | g.p("if err = rows.Scan(dest...); err != nil {") 225 | g.p("return %s, errors.Wrap(err, %q)", errRespStr, "failed to scan row") 226 | g.p("}") 227 | if operation == sal.OperationTypeQuery { 228 | if respRow.Pointer() { 229 | respRowStr = "&resp" 230 | } 231 | g.br() 232 | g.p("list = append(list, %s)", respRowStr) 233 | g.p("}") 234 | } 235 | g.br() 236 | 237 | g.p("if err = rows.Err(); err != nil {") 238 | g.p("return %s, errors.Wrap(err, %q)", errRespStr, "something failed during iteration") 239 | g.p("}") 240 | g.br() 241 | 242 | respStr := "resp" 243 | if operation == sal.OperationTypeQuery { 244 | respStr = "list" 245 | } 246 | 247 | if resp.Pointer() { 248 | respStr = "&" + respStr 249 | } 250 | 251 | g.p("return %s, nil", respStr) 252 | g.p("}") 253 | 254 | return nil 255 | } 256 | 257 | func (g *generator) GenerateRowMap(prm looker.Parameter, mapName string, prmName string) error { 258 | if prm.Kind() == reflect.Struct.String() { 259 | st := prm.(*looker.StructElement) 260 | for _, field := range st.Fields { 261 | g.p("%s.AppendTo(%q, &%s.%s)", mapName, field.ColumnName(), prmName, field.Path()) 262 | } 263 | g.br() 264 | if st.ProcessRower { 265 | g.p("%s.ProcessRow(%s)", prmName, mapName) 266 | g.br() 267 | } 268 | } else { 269 | return errors.New("unsupported type of request variable") 270 | } 271 | 272 | return nil 273 | } 274 | 275 | func (g *generator) GenerateBeginTx(dstPkg looker.ImportElement, intf *looker.Interface) { 276 | g.p("func (s *%s) BeginTx(ctx context.Context, opts *sql.TxOptions) (%s, error) {", intf.ImplementationName(Prefix), intf.Name(dstPkg.Path)) 277 | g.p("dbConn, ok := s.handler.(sal.TransactionBegin)") 278 | g.p("if !ok {") 279 | g.p("return nil, errors.New(%q)", "handler doesn't satisfy the interface TransactionBegin") 280 | g.p("}") 281 | g.p("var (") 282 | g.p("err error") 283 | g.p("tx *sql.Tx") 284 | g.p(")") 285 | g.br() 286 | 287 | g.p("ctx = context.WithValue(ctx, sal.ContextKeyTxOpened, s.txOpened)") 288 | g.p("ctx = context.WithValue(ctx, sal.ContextKeyOperationType, %q)", sal.OperationTypeBegin.String()) 289 | g.p("ctx = context.WithValue(ctx, sal.ContextKeyMethodName, %q)", "BeginTx") 290 | g.br() 291 | 292 | g.beforeQueryHook(`"BEGIN"`, "nil") 293 | g.br() 294 | 295 | g.p("tx, err = dbConn.BeginTx(ctx, opts)") 296 | g.p("if err != nil {") 297 | g.p("err = errors.Wrap(err, %q)", "failed to start tx") 298 | g.p("return nil, err") 299 | g.p("}") 300 | g.br() 301 | g.p("newClient := &%s{", intf.ImplementationName(Prefix)) 302 | g.p("handler: tx,") 303 | g.p("parent: s.handler,") 304 | g.p("ctrl: s.ctrl,") 305 | g.p("txOpened: true,") 306 | g.p("}") 307 | g.br() 308 | g.p("return newClient, nil") 309 | g.p("}") 310 | } 311 | 312 | func (g *generator) GenerateTx(dstPkg looker.ImportElement, intf *looker.Interface) { 313 | g.p("func (s *%s) Tx() sal.Transaction {", intf.ImplementationName(Prefix)) 314 | g.p("if tx, ok := s.handler.(sal.SqlTx); ok {") 315 | g.p("return sal.NewWrappedTx(tx, s.ctrl)") 316 | g.p("}") 317 | g.p("return nil") 318 | g.p("}") 319 | } 320 | 321 | func (g *generator) ifErr(resp, msg string) { 322 | g.p("if err != nil {") 323 | if resp == "" { 324 | g.p("return errors.Wrap(err, %q)", msg) 325 | } else { 326 | g.p("return %s, errors.Wrap(err, %q)", resp, msg) 327 | } 328 | g.p("}") 329 | } 330 | 331 | func (g *generator) beforeQueryHook(q, r string) { 332 | g.p("for _, fn := range s.ctrl.BeforeQuery {") 333 | g.p("var fnz sal.FinalizerFunc") 334 | g.p("ctx, fnz = fn(ctx, %s, %s)", q, r) 335 | g.p("if fnz != nil {") 336 | g.p("defer func() { fnz(ctx, err) }()") 337 | g.p("}") 338 | g.p("}") 339 | } 340 | 341 | func elementType(ptr bool, name string) string { 342 | var prefix string 343 | if ptr { 344 | prefix = "*" 345 | } 346 | return prefix + name 347 | } 348 | 349 | // Output returns the generator's output, formatted in the standard Go style. 350 | func (g *generator) Output() []byte { 351 | src, err := format.Source(g.buf.Bytes()) 352 | if err != nil { 353 | log.Fatalf("Failed to format generated source code: %s\n%s", err, g.buf.String()) 354 | } 355 | return src 356 | } 357 | 358 | func (g *generator) p(format string, args ...interface{}) { 359 | fmt.Fprintf(&g.buf, g.indent+format+"\n", args...) 360 | } 361 | 362 | func (g *generator) br() { 363 | g.p("") 364 | } 365 | 366 | func calcOperationType(prms looker.Parameters) sal.OperationType { 367 | if len(prms) == 1 { 368 | return sal.OperationTypeExec 369 | } 370 | if isSqlResult(prms[0]) { 371 | return sal.OperationTypeExec 372 | } 373 | if prms[0].Kind() == reflect.Slice.String() { 374 | return sal.OperationTypeQuery 375 | } 376 | return sal.OperationTypeQueryRow 377 | } 378 | 379 | func ImportPaths(dirtyList []string, dstPath string) []string { 380 | list := make([]string, 0) 381 | for _, p := range dirtyList { 382 | // todo: find mistake when import contains something from vendor 383 | if strings.Contains(p, "/vendor/") { 384 | continue 385 | } 386 | if p != "" && p != dstPath { 387 | list = append(list, p) 388 | } 389 | } 390 | 391 | return list 392 | } 393 | 394 | func responseErrStr(operation sal.OperationType, resp looker.Parameter, dstPath string) string { 395 | var errRespStr string 396 | if operation != sal.OperationTypeExec { 397 | if resp.Pointer() { 398 | errRespStr = "nil" 399 | } else { 400 | if resp.Kind() == reflect.Struct.String() { 401 | errRespStr = resp.Name(dstPath) + "{}" 402 | } else { 403 | errRespStr = "nil" 404 | } 405 | } 406 | } 407 | 408 | return errRespStr 409 | } 410 | 411 | func isSqlResult(prm looker.Parameter) bool { 412 | if prm.Name("path/to/pkg") == "sql.Result" { 413 | return true 414 | } 415 | return false 416 | } 417 | -------------------------------------------------------------------------------- /salgen/generator_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io/ioutil" 5 | "testing" 6 | 7 | "github.com/go-gad/sal/looker" 8 | "github.com/sergi/go-diff/diffmatchpatch" 9 | ) 10 | 11 | var update bool = false 12 | 13 | func TestGenerateCode(t *testing.T) { 14 | dstPkg := looker.ImportElement{Path: "github.com/go-gad/sal/examples/bookstore"} 15 | code, err := GenerateCode(dstPkg, "github.com/go-gad/sal/examples/bookstore", []string{"Store"}) 16 | if err != nil { 17 | t.Fatalf("Failed to generate a code: %+v", err) 18 | } 19 | 20 | //t.Logf("\n%s", string(code)) 21 | if update { 22 | if err = ioutil.WriteFile("../examples/bookstore/sal_client.go", code, 0666); err != nil { 23 | t.Fatalf("failed to write file: %+v", err) 24 | } 25 | } 26 | expCode, err := ioutil.ReadFile("../examples/bookstore/sal_client.go") 27 | if string(expCode) != string(code) { 28 | t.Error("generated code is not equal to expected") 29 | dmp := diffmatchpatch.New() 30 | diffs := dmp.DiffMain(string(expCode), string(code), true) 31 | t.Log(dmp.DiffPrettyText(diffs)) 32 | } 33 | } 34 | 35 | func TestGenerateCode2(t *testing.T) { 36 | dstPkg := looker.ImportElement{Path: "github.com/go-gad/sal/looker/testdata"} 37 | code, err := GenerateCode(dstPkg, "github.com/go-gad/sal/looker/testdata", []string{"Store"}) 38 | if err != nil { 39 | t.Fatalf("Failed to generate a code: %+v", err) 40 | } 41 | 42 | t.Logf("\n%s", string(code)) 43 | 44 | if update { 45 | if err = ioutil.WriteFile("../looker/testdata/store_client.go", code, 0666); err != nil { 46 | t.Fatalf("failed to write file: %+v", err) 47 | } 48 | } 49 | } 50 | 51 | func TestGenerator_GenerateRowMap(t *testing.T) { 52 | prm := &looker.UnsupportedElement{ 53 | ImportPath: looker.ImportElement{}, 54 | UserType: "int64", 55 | BaseType: "int64", 56 | IsPointer: true, 57 | } 58 | g := new(generator) 59 | if err := g.GenerateRowMap(prm, "rowMap", "resp"); err == nil { 60 | t.Error("should be error") 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /salgen/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "io" 6 | "log" 7 | "os" 8 | "strings" 9 | 10 | "github.com/go-gad/sal/looker" 11 | "github.com/pkg/errors" 12 | ) 13 | 14 | var ( 15 | destination = flag.String("destination", "", "Output file; defaults to stdout.") 16 | packageName = flag.String("package", "", "The full import path of the library for the generated implementation") 17 | ) 18 | 19 | func main() { 20 | flag.Usage = usage 21 | flag.Parse() 22 | 23 | if flag.NArg() != 2 { 24 | log.Fatal("Expected exactly two arguments") 25 | } 26 | var ( 27 | srcpkg = flag.Arg(0) 28 | symbols = strings.Split(flag.Arg(1), ",") 29 | ) 30 | 31 | if len(*destination) > 0 { 32 | err := os.Remove(*destination) 33 | if err != nil && !os.IsNotExist(err) { 34 | log.Fatalf("Failed to remove destination file: %+v", err) 35 | } 36 | } 37 | 38 | dstPkg := looker.ImportElement{Path: *packageName} 39 | code, err := GenerateCode(dstPkg, srcpkg, symbols) 40 | if err != nil { 41 | log.Fatalf("Failed to generate a code: %+v", err) 42 | } 43 | 44 | dst := os.Stdout 45 | if len(*destination) > 0 { 46 | f, err := os.Create(*destination) 47 | if err != nil { 48 | log.Fatalf("Failed opening destination file: %v", err) 49 | } 50 | defer f.Close() 51 | dst = f 52 | } 53 | 54 | if _, err := dst.Write(code); err != nil { 55 | log.Fatalf("Failed writing to destination: %v", err) 56 | } 57 | 58 | } 59 | 60 | func GenerateCode(dstPkg looker.ImportElement, srcpkg string, symbols []string) ([]byte, error) { 61 | pkg, err := looker.Reflect(srcpkg, symbols) 62 | if err != nil { 63 | return nil, errors.Wrap(err, "failed to reflect package") 64 | } 65 | 66 | g := new(generator) 67 | 68 | if err := g.Generate(pkg, dstPkg); err != nil { 69 | return nil, errors.Wrap(err, "failed generating mock") 70 | } 71 | 72 | return g.Output(), nil 73 | } 74 | 75 | func usage() { 76 | io.WriteString(os.Stderr, usageText) 77 | flag.PrintDefaults() 78 | } 79 | 80 | const usageText = `Usage: 81 | salgen [options...] 82 | 83 | Example: 84 | salgen -destination=./client.go -package=github.com/go-gad/sal/examples/profile/storage github.com/go-gad/sal/examples/profile/storage Store 85 | 86 | 87 | describes the complete package path where the interface is located. 88 | 89 | indicates the interface name itself. 90 | 91 | Options: 92 | ` 93 | --------------------------------------------------------------------------------