├── .github
└── workflows
│ └── codeql.yml
├── .gitignore
├── LICENSE
├── README.md
├── coll_stack.go
├── config.go
├── config_builder.go
├── config_db.go
├── config_db_test.go
├── config_mapper.go
├── config_mapper_test.go
├── db.yml
├── examples
├── examples.go
├── mapper
│ └── userMapper.xml
└── sql
│ └── user.sql
├── executor.go
├── expr.go
├── expr_test.go
├── go.mod
├── go.sum
├── gobatis.dtd
├── gobatis.go
├── gobatis_db.go
├── gobatis_test.go
├── logger.go
├── mapper.go
├── nilable_structs.go
├── option.go
├── option_db.go
├── option_ds.go
├── option_file.go
├── params_test.go
├── parser_xml.go
├── parser_xml_test.go
├── proc_params.go
├── proc_params_test.go
├── proc_res.go
├── sql_source.go
├── sql_source_test.go
├── util.go
├── util_builder.go
├── val.go
├── xmltag.go
└── xmltag_test.go
/.github/workflows/codeql.yml:
--------------------------------------------------------------------------------
1 | # For most projects, this workflow file will not need changing; you simply need
2 | # to commit it to your repository.
3 | #
4 | # You may wish to alter this file to override the set of languages analyzed,
5 | # or to provide custom queries or build logic.
6 | #
7 | # ******** NOTE ********
8 | # We have attempted to detect the languages in your repository. Please check
9 | # the `language` matrix defined below to confirm you have the correct set of
10 | # supported CodeQL languages.
11 | #
12 | name: "CodeQL"
13 |
14 | on:
15 | push:
16 | branches: [ "master" ]
17 | pull_request:
18 | # The branches below must be a subset of the branches above
19 | branches: [ "master" ]
20 | schedule:
21 | - cron: '45 6 * * 3'
22 |
23 | jobs:
24 | analyze:
25 | name: Analyze
26 | runs-on: ubuntu-latest
27 | permissions:
28 | actions: read
29 | contents: read
30 | security-events: write
31 |
32 | strategy:
33 | fail-fast: false
34 | matrix:
35 | language: [ 'go' ]
36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
37 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
38 |
39 | steps:
40 | - name: Checkout repository
41 | uses: actions/checkout@v3
42 |
43 | # Initializes the CodeQL tools for scanning.
44 | - name: Initialize CodeQL
45 | uses: github/codeql-action/init@v2
46 | with:
47 | languages: ${{ matrix.language }}
48 | # If you wish to specify custom queries, you can do so here or in a config file.
49 | # By default, queries listed here will override any specified in a config file.
50 | # Prefix the list here with "+" to use these queries and those in the config file.
51 |
52 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
53 | # queries: security-extended,security-and-quality
54 |
55 |
56 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
57 | # If this step fails, then you should remove it and run the build manually (see below)
58 | - name: Autobuild
59 | uses: github/codeql-action/autobuild@v2
60 |
61 | # ℹ️ Command-line programs to run using the OS shell.
62 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
63 |
64 | # If the Autobuild fails above, remove it and uncomment the following three lines.
65 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
66 |
67 | # - run: |
68 | # echo "Run, Build Application using script"
69 | # ./location_of_script_within_repo/buildscript.sh
70 |
71 | - name: Perform CodeQL Analysis
72 | uses: github/codeql-action/analyze@v2
73 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### Go template
3 | # Binaries for programs and plugins
4 | *.exe
5 | *.exe~
6 | *.dll
7 | *.so
8 | *.dylib
9 |
10 | # Test binary, build with `go test -c`
11 | *.test
12 |
13 | # Output of the go coverage tool, specifically when used with LiteIDE
14 | *.out
15 |
16 | .DS_Store
17 | .idea/
18 | pkg/
19 | /src/
20 | /.vscode
21 | /*.code-workspace
22 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # gobatis
2 |
3 | [](https://github.com/wenj91/gobatis/actions/workflows/codeql.yml)
4 |
5 | 目前代码都是基于类mysql数据库编写测试的,其他数据库暂时还未做兼容处理
6 |
7 | - [x] 支持数据库
8 | - [x] mysql
9 | - [x] tidb
10 | - [x] mariadb
11 | - [ ] postgres
12 | - [ ] sqlite
13 | - [x] 基础操作
14 | - [x] query
15 | - [x] insert
16 | - [x] update
17 | - [x] delete
18 |
19 | ## ToDo
20 |
21 | - 增加更多易用表达式指令,目前已有`$blank`指令用于判别字符串是否为空的指令,比如判断name为空串: test="$blank(name)"
22 |
23 | ## 模板代码生成
24 |
25 | 提供了简单的增删改查代码自动生成
26 |
27 | 具体操作看仓库: [https://github.com/wenj91/mctl.git](https://github.com/wenj91/mctl.git)
28 |
29 | ## gobatis接口
30 |
31 | ```go
32 | type GoBatis interface {
33 | // Select 查询数据
34 | Select(stmt string, param interface{}, rowBound ...*rowBounds) func(res interface{}) (int64, error)
35 | // SelectContext 查询数据with context
36 | SelectContext(ctx context.Context, stmt string, param interface{}, rowBound ...*rowBounds) func(res interface{}) (int64, error)
37 | // Insert 插入数据
38 | Insert(stmt string, param interface{}) (lastInsertId int64, affected int64, err error)
39 | // InsertContext 插入数据with context
40 | InsertContext(ctx context.Context, stmt string, param interface{}) (lastInsertId int64, affected int64, err error)
41 | // Update 更新数据
42 | Update(stmt string, param interface{}) (affected int64, err error)
43 | // UpdateContext 更新数据with context
44 | UpdateContext(ctx context.Context, stmt string, param interface{}) (affected int64, err error)
45 | // Delete 刪除数据
46 | Delete(stmt string, param interface{}) (affected int64, err error)
47 | // DeleteContext 刪除数据with context
48 | DeleteContext(ctx context.Context, stmt string, param interface{}) (affected int64, err error)
49 | }
50 | ```
51 |
52 | ## db数据源配置
53 | - 支持多数据源配置
54 | - db子级配置为一个map,map的key即为数据源名称标识
55 | - map的value为数据源具体配置,具体配置项如下表
56 |
57 | | 配置 | 是否必填配置 | 默认值 | 说明 |
58 | |:---|:----:|:----:|----|
59 | | driverName | 是 | | 数据源驱动名,必填配置项
60 | | dataSourceName | 是 | | 数据源名称,必填配置项,例如: root:123456@tcp(127.0.0.1:3306)/test?charset=utf8
61 | | maxLifeTime | 否 | 120(单位: s)| 连接最大存活时间,默认值为: 120 单位为: s
62 | | maxOpenConns | 否 | 10 | 最大打开连接数,默认值为: 10
63 | | maxIdleConns | 否 | 5 | 最大挂起连接数,默认值为: 5
64 |
65 | ### 示例
66 | * db配置示例(配置较之前的有所调整)
67 | 以下为多数据源配置示例: db.yml
68 | ```yaml
69 | # 数据库配置
70 | db:
71 | # 数据源名称1
72 | - datasource: ds1
73 | # 驱动名
74 | driverName: mysql
75 | # 数据源
76 | dataSourceName: root:123456@tcp(127.0.0.1:3306)/test?charset=utf8
77 | # 连接最大存活时间(单位: s)
78 | maxLifeTime: 120
79 | # 最大open连接数
80 | maxOpenConns: 10
81 | # 最大挂起连接数
82 | maxIdleConns: 5
83 | # 数据源名称2
84 | - datasource: ds2
85 | # 驱动名
86 | driverName: mysql
87 | # 数据源
88 | dataSourceName: root:123456@tcp(127.0.0.1:3306)/test?charset=utf8
89 | # 连接最大存活时间(单位: s)
90 | maxLifeTime: 120
91 | # 最大open连接数
92 | maxOpenConns: 10
93 | # 最大挂起连接数
94 | maxIdleConns: 5
95 | # 是否显示SQL语句
96 | showSql: true
97 | # 数据表映射文件路径配置
98 | mappers:
99 | # 映射文件路径, 可以为绝对路径,如: /usr/local/mapper/userMapper.xml
100 | - mapper/userMapper.xml
101 | ```
102 |
103 | * mapper配置
104 | 1. mapper可以配置namespace属性
105 | 1. mapper可以包含: select, insert, update, delete标签
106 | 1. mapper子标签id属性则为标签唯一标识, 必须配置属性
107 | 1. 其中select标签必须包含resultType属性,resultType可以是: map, maps, array, arrays, struct, structs, value
108 |
109 | * 标签说明
110 | select: 用于查询操作
111 | insert: 用于插入sql操作
112 | update: 用于更新sql操作
113 | delete: 用于删除sql操作
114 |
115 | * resultType说明
116 | map: 则数据库查询结果为map
117 | maps: 则数据库查询结果为map数组
118 | array: 则数据库查询结果为值数组
119 | arrays: 则数据库查询结果为多个值数组
120 | struct: 则数据库查询结果为单个结构体
121 | structs: 则数据库查询结果为结构体数组
122 | value: 则数据库查询结果为单个数值
123 |
124 | 以下是mapper配置示例: mapper/userMapper.xml
125 | ```xml
126 |
127 |
129 |
130 |
131 | id, name, crtTm, pwd, email
132 |
133 |
139 |
142 |
145 |
148 |
151 |
154 |
155 | insert into user (name, email, crtTm)
156 | values (#{Name}, #{Email}, #{CrtTm})
157 |
158 |
159 | delete from user where id=#{id}
160 |
161 |
168 |
175 |
176 | update user
177 |
178 | name = #{Name},
179 |
180 | where id = #{Id}
181 |
182 |
183 | ```
184 |
185 | ## 使用方法
186 |
187 | ### 使用配置文件配置
188 | example1.go
189 | ```go
190 | package main
191 |
192 | import (
193 | "fmt"
194 | _ "github.com/go-sql-driver/mysql" // 引入驱动
195 | "github.com/wenj91/gobatis" // 引入gobatis
196 | )
197 |
198 | // 实体结构示例, tag:field为数据库对应字段名称
199 | type User struct {
200 | Id gobatis.NullInt64 `field:"id"`
201 | Name gobatis.NullString `field:"name"`
202 | Email gobatis.NullString `field:"email"`
203 | CrtTm gobatis.NullTime `field:"crtTm"`
204 | }
205 |
206 |
207 | // User to string
208 | func (u *User) String() string {
209 | bs, _ := json.Marshal(u)
210 | return string(bs)
211 | }
212 |
213 | func main() {
214 | // 初始化db,参数为db.yml路径,如:db.yml
215 | gobatis.Init(gobatis.NewFileOption("db.yml"))
216 |
217 | // 获取数据源,参数为数据源名称,如:datasource1
218 | gb := gobatis.Get("ds1")
219 |
220 | //传入id查询Map
221 | mapRes := make(map[string]interface{})
222 | // stmt标识为:namespace + '.' + id, 如:userMapper.findMapById
223 | // 查询参数可以是map,也可以是数组,也可以是实体结构
224 | _, err := gb.Select("userMapper.findMapById", map[string]interface{}{"id": 1})(mapRes)
225 | fmt.Println("userMapper.findMapById-->", mapRes, err)
226 |
227 | // 根据传入实体查询对象
228 | param := User{Id: gobatis.NullInt64{Int64: 1, Valid: true}}
229 | var structRes *User
230 | _, err = gb.Select("userMapper.findStructByStruct", param)(&structRes)
231 | fmt.Println("userMapper.findStructByStruct-->", structRes, err)
232 |
233 | // 查询实体列表
234 | structsRes := make([]*User, 0)
235 | _, err = gb.Select("userMapper.queryStructs", map[string]interface{}{})(&structsRes)
236 | fmt.Println("userMapper.queryStructs-->", structsRes, err)
237 |
238 | param = User{
239 | Id: gobatis.NullInt64{Int64: 1, Valid: true},
240 | Name: gobatis.NullString{String: "wenj1993", Valid: true},
241 | }
242 |
243 | // set tag
244 | affected, err := gb.Update("userMapper.updateByCond", param)
245 | fmt.Println("updateByCond:", affected, err)
246 |
247 | param = User{Name: gobatis.NullString{String: "wenj1993", Valid: true}}
248 | // where tag
249 | res := make([]*User, 0)
250 | _, err = gb.Select("userMapper.queryStructsByCond", param)(&res)
251 | fmt.Println("queryStructsByCond", res, err)
252 |
253 | // trim tag
254 | res = make([]*User, 0)
255 | _, err = gb.Select("userMapper.queryStructsByCond2", param)(&res)
256 | fmt.Println("queryStructsByCond2", res, err)
257 |
258 | // include tag
259 | ms := make([]map[string]interface{}, 0)
260 | _, err = gb.Select("userMapper.findIncludeMaps", nil)(&ms)
261 | fmt.Println("userMapper.findIncludeMaps-->", ms, err)
262 |
263 | // ${id}
264 | res = make([]*User, 0)
265 | _, err = gb.Select("userMapper.queryStructsByOrder", map[string]interface{}{
266 | "id":"id",
267 | })(&res)
268 | fmt.Println("queryStructsByCond", res, err)
269 |
270 | // ${id} with count, 传入RowBounds(0, 100)即可返回count总数
271 | res = make([]*User, 0)
272 | cnt, err = gb.Select("userMapper.queryStructsByOrder", map[string]interface{}{
273 | "id":"id",
274 | }, RowBounds(0, 100))(&res)
275 | fmt.Println("queryStructsByCond", cnt, res, err)
276 |
277 |
278 | // 开启事务示例
279 | tx, _ := gb.Begin()
280 | defer tx.Rollback()
281 | _, tx.Select("userMapper.findMapById", map[string]interface{}{"id": 1,})(mapRes)
282 | fmt.Println("tx userMapper.findMapById-->", mapRes, err)
283 | tx.Commit()
284 | }
285 | ```
286 |
287 | ### 代码配置方式
288 |
289 | example2.go
290 |
291 | ```go
292 | package main
293 |
294 | import (
295 | "fmt"
296 | _ "github.com/go-sql-driver/mysql" // 引入驱动
297 | "github.com/wenj91/gobatis" // 引入gobatis
298 | )
299 |
300 | // 实体结构示例, tag:field为数据库对应字段名称
301 | type User struct {
302 | Id gobatis.NullInt64 `field:"id"`
303 | Name gobatis.NullString `field:"name"`
304 | Email gobatis.NullString `field:"email"`
305 | CrtTm gobatis.NullTime `field:"crtTm"`
306 | }
307 |
308 | func main() {
309 | // 初始化db
310 | ds1 := gobatis.NewDataSourceBuilder().
311 | DataSource("ds1").
312 | DriverName("mysql").
313 | DataSourceName("root:123456@tcp(127.0.0.1:3306)/test?charset=utf8").
314 | MaxLifeTime(120).
315 | MaxOpenConns(10).
316 | MaxIdleConns(5).
317 | Build()
318 |
319 | option := gobatis.NewDSOption().
320 | DS([]*gobatis.DataSource{ds1}).
321 | Mappers([]string{"examples/mapper/userMapper.xml"}).
322 | ShowSQL(true)
323 |
324 | gobatis.Init(option)
325 |
326 | // 获取数据源,参数为数据源名称,如:ds1
327 | gb := gobatis.Get("ds1")
328 |
329 | //传入id查询Map
330 | mapRes := make(map[string]interface{})
331 | // stmt标识为:namespace + '.' + id, 如:userMapper.findMapById
332 | // 查询参数可以是map,也可以是数组,也可以是实体结构
333 | _, err := gb.Select("userMapper.findMapById", map[string]interface{}{"id": 1})(mapRes)
334 | fmt.Println("userMapper.findMapById-->", mapRes, err)
335 | }
336 | ```
337 |
338 | example3.go
339 |
340 | ```go
341 | package main
342 |
343 | import (
344 | "database/sql"
345 | "fmt"
346 | _ "github.com/go-sql-driver/mysql" // 引入驱动
347 | "github.com/wenj91/gobatis" // 引入gobatis
348 | )
349 |
350 | // 实体结构示例, tag:field为数据库对应字段名称
351 | type User struct {
352 | Id gobatis.NullInt64 `field:"id"`
353 | Name gobatis.NullString `field:"name"`
354 | Email gobatis.NullString `field:"email"`
355 | CrtTm gobatis.NullTime `field:"crtTm"`
356 | }
357 |
358 | func main() {
359 | // 初始化db
360 | db, _ := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8")
361 | dbs := make(map[string]*gobatis.GoBatisDB)
362 | dbs["ds1"] = gobatis.NewGoBatisDB(gobatis.DBTypeMySQL, db)
363 |
364 | option := gobatis.NewDBOption().
365 | DB(dbs).
366 | ShowSQL(true).
367 | Mappers([]string{"examples/mapper/userMapper.xml"})
368 |
369 | gobatis.Init(option)
370 |
371 | // 获取数据源,参数为数据源名称,如:ds1
372 | gb := gobatis.Get("ds1")
373 |
374 | //传入id查询Map
375 | mapRes := make(map[string]interface{})
376 | // stmt标识为:namespace + '.' + id, 如:userMapper.findMapById
377 | // 查询参数可以是map,也可以是数组,也可以是实体结构
378 | _, err := gb.Select("userMapper.findMapById", map[string]interface{}{"id": 1})(mapRes)
379 | fmt.Println("userMapper.findMapById-->", mapRes, err)
380 | }
381 | ```
382 |
383 | ## 致谢
384 |
385 | 感谢jetbrains提供的goland!
386 |
--------------------------------------------------------------------------------
/coll_stack.go:
--------------------------------------------------------------------------------
1 | package gobatis
2 |
3 | import (
4 | l "container/list"
5 | "sync"
6 | )
7 |
8 | type stack struct {
9 | list *l.List
10 | mu sync.Mutex
11 | }
12 |
13 | func NewStack() *stack {
14 | list := l.New()
15 | return &stack{list: list,}
16 | }
17 |
18 | func (s *stack) Push(t interface{}){
19 | s.mu.Lock()
20 | defer s.mu.Unlock()
21 | s.list.PushFront(t)
22 | }
23 |
24 | func (s *stack) Pop() interface{} {
25 | s.mu.Lock()
26 | defer s.mu.Unlock()
27 | ele := s.list.Front()
28 | if nil != ele {
29 | s.list.Remove(ele)
30 | return ele.Value
31 | }
32 |
33 | return nil
34 | }
35 |
36 | func (s *stack) Peak() interface{} {
37 | s.mu.Lock()
38 | defer s.mu.Unlock()
39 | ele := s.list.Front()
40 | return ele.Value
41 | }
42 |
43 | func (s *stack) Len() int {
44 | return s.list.Len()
45 | }
46 |
47 | func (s *stack) IsEmpty() bool {
48 | return s.list.Len() == 0
49 | }
50 |
--------------------------------------------------------------------------------
/config.go:
--------------------------------------------------------------------------------
1 | package gobatis
2 |
3 | import (
4 | "database/sql"
5 | "os"
6 | "strings"
7 | "time"
8 | )
9 |
10 | type config struct {
11 | dbConf *DBConfig
12 | mapperConf *mapperConfig
13 | }
14 |
15 | var conf *config
16 | var db map[string]*GoBatisDB
17 |
18 | func Init(option IOption) {
19 | configInit(option.ToDBConf())
20 | }
21 |
22 | func configInit(dbConf *DBConfig) {
23 | if nil == dbConf {
24 | panic("Build db config err: dbConf == nil")
25 | }
26 |
27 | if len(dbConf.DB) <= 0 && dbConf.db == nil {
28 | panic("No datasource config")
29 | }
30 |
31 | mapperConf := &mapperConfig{
32 | mappedStmts: make(map[string]*node),
33 | mappedSql: make(map[string]*node),
34 | }
35 |
36 | for _, item := range dbConf.Mappers {
37 | f, err := os.Open(item)
38 | if nil != err {
39 | panic("Open mapper config: " + item + " err:" + err.Error())
40 | }
41 |
42 | LOG.Info("mapper config:%s %s", item, "init...")
43 | mc := buildMapperConfig(f)
44 | for k, ms := range mc.mappedStmts {
45 | mapperConf.put(k, ms)
46 | }
47 |
48 | // sql tag cache
49 | for k, ms := range mc.mappedSql {
50 | mapperConf.putSql(k, ms)
51 | }
52 | }
53 |
54 | conf = &config{
55 | dbConf: dbConf,
56 | mapperConf: mapperConf,
57 | }
58 |
59 | // init db
60 | dbInit(dbConf)
61 | }
62 |
63 | func dbInit(dbConf *DBConfig) {
64 | db = make(map[string]*GoBatisDB)
65 | if len(dbConf.DB) <= 0 && dbConf.db == nil {
66 | panic("No config for datasource")
67 | }
68 |
69 | for _, item := range dbConf.DB {
70 | if item.DataSource == "" {
71 | panic("DB config err: datasource must not be nil")
72 | }
73 |
74 | item.DataSource = strings.TrimSpace(item.DataSource)
75 |
76 | _, ok := db[item.DataSource]
77 | if ok {
78 | panic("DB config datasource name repeat:" + item.DataSource)
79 | }
80 |
81 | if item.DriverName == "" {
82 | panic("DB config err: driverName must not be nil")
83 | }
84 |
85 | if item.DataSourceName == "" {
86 | panic("DB config err: dataSourceName must not be nil")
87 | }
88 |
89 | dbConn, err := sql.Open(item.DriverName, item.DataSourceName)
90 | if nil != err {
91 | panic(err)
92 | }
93 |
94 | if err := dbConn.Ping(); err != nil {
95 | panic(err)
96 | }
97 |
98 | if item.MaxLifeTime == 0 {
99 | dbConn.SetConnMaxLifetime(120 * time.Second)
100 | } else {
101 | dbConn.SetConnMaxLifetime(time.Duration(item.MaxLifeTime) * time.Second)
102 | }
103 |
104 | if item.MaxOpenConns == 0 {
105 | dbConn.SetMaxOpenConns(10)
106 | } else {
107 | dbConn.SetMaxOpenConns(item.MaxOpenConns)
108 | }
109 |
110 | if item.MaxOpenConns == 0 {
111 | dbConn.SetMaxIdleConns(5)
112 | } else {
113 | dbConn.SetMaxIdleConns(item.MaxIdleConns)
114 | }
115 |
116 | d := NewGoBatisDB(DBType(item.DriverName), dbConn)
117 | db[item.DataSource] = d
118 | }
119 |
120 | if dbConf.db != nil {
121 | for k, v := range dbConf.db {
122 | _, ok := db[k]
123 | if ok {
124 | panic("DB config datasource name repeat:" + k)
125 | }
126 | db[k] = v
127 | }
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/config_builder.go:
--------------------------------------------------------------------------------
1 | package gobatis
2 |
3 | type DataSourceBuilder struct {
4 | ds *DataSource
5 | }
6 |
7 | func NewDataSourceBuilder() *DataSourceBuilder {
8 | return &DataSourceBuilder{
9 | ds: &DataSource{},
10 | }
11 | }
12 |
13 | // DataSource
14 | func (d *DataSourceBuilder) DataSource(ds string) *DataSourceBuilder {
15 | d.ds.DataSource = ds
16 | return d
17 | }
18 |
19 | // DriverName
20 | func (d *DataSourceBuilder) DriverName(dn string) *DataSourceBuilder {
21 | d.ds.DriverName = dn
22 | return d
23 | }
24 |
25 | // DataSourceName
26 | func (d *DataSourceBuilder) DataSourceName(dsn string) *DataSourceBuilder {
27 | d.ds.DataSourceName = dsn
28 | return d
29 | }
30 |
31 | // MaxLifeTime
32 | func (d *DataSourceBuilder) MaxLifeTime(mlt int) *DataSourceBuilder {
33 | d.ds.MaxLifeTime = mlt
34 | return d
35 | }
36 |
37 | // MaxOpenConns
38 | func (d *DataSourceBuilder) MaxOpenConns(moc int) *DataSourceBuilder {
39 | d.ds.MaxOpenConns = moc
40 | return d
41 | }
42 |
43 | // MaxIdleConns
44 | func (d *DataSourceBuilder) MaxIdleConns(mic int) *DataSourceBuilder {
45 | d.ds.MaxIdleConns = mic
46 | return d
47 | }
48 |
49 | func (d *DataSourceBuilder) Build() *DataSource {
50 | if d.ds.DataSource == "" {
51 | panic("DataSource is nil")
52 | }
53 |
54 | if d.ds.DataSourceName == "" {
55 | panic("DataSourceName is nil")
56 | }
57 |
58 | if d.ds.DriverName == "" {
59 | panic("DriverName is nil")
60 | }
61 |
62 | return d.ds
63 | }
64 |
65 | type DBConfigBuilder struct {
66 | d *DBConfig
67 | }
68 |
69 | func NewDBConfigBuilder() *DBConfigBuilder {
70 | return &DBConfigBuilder{
71 | d: &DBConfig{
72 | DB: make([]*DataSource, 0),
73 | },
74 | }
75 | }
76 |
77 | func (d *DBConfigBuilder) Mappers(mappers []string) *DBConfigBuilder {
78 | d.d.Mappers = mappers
79 | return d
80 | }
81 |
82 | func (d *DBConfigBuilder) DS(dss []*DataSource) *DBConfigBuilder {
83 | d.d.DB = dss
84 | return d
85 | }
86 |
87 | func (d *DBConfigBuilder) DB(db map[string]*GoBatisDB) *DBConfigBuilder {
88 | d.d.db = db
89 | return d
90 | }
91 |
92 | func (d *DBConfigBuilder) ShowSQL(showSQL bool) *DBConfigBuilder {
93 | d.d.ShowSQL = showSQL
94 | return d
95 | }
96 |
97 | func (d *DBConfigBuilder) Build() *DBConfig {
98 | if len(d.d.DB) <= 0 && d.d.db == nil {
99 | panic("No config for datasource")
100 | }
101 |
102 | return d.d
103 | }
104 |
--------------------------------------------------------------------------------
/config_db.go:
--------------------------------------------------------------------------------
1 | package gobatis
2 |
3 | type DataSource struct {
4 | DataSource string `yaml:"datasource"`
5 | DriverName string `yaml:"driverName"`
6 | DataSourceName string `yaml:"dataSourceName"`
7 | MaxLifeTime int `yaml:"maxLifeTime"`
8 | MaxOpenConns int `yaml:"maxOpenConns"`
9 | MaxIdleConns int `yaml:"maxIdleConns"`
10 | }
11 |
12 | // NewDataSource new data source
13 | func NewDataSource(dataSource string, driverName string, dataSourceName string) *DataSource {
14 | return &DataSource{
15 | DataSource: dataSource,
16 | DriverName: driverName,
17 | DataSourceName: dataSourceName,
18 | }
19 | }
20 |
21 | // NewDataSource_ new data source
22 | func NewDataSource_(dataSource string, driverName string, dataSourceName string,
23 | maxLifeTime int, maxOpenConns int, maxIdleConns int) *DataSource {
24 | return &DataSource{
25 | DataSource: dataSource,
26 | DriverName: driverName,
27 | DataSourceName: dataSourceName,
28 | MaxLifeTime: maxLifeTime,
29 | MaxOpenConns: maxOpenConns,
30 | MaxIdleConns: maxIdleConns,
31 | }
32 | }
33 |
34 | type DBConfig struct {
35 | DB []*DataSource `yaml:"db"`
36 | ShowSQL bool `yaml:"showSQL"`
37 | Mappers []string `yaml:"mappers"`
38 | db map[string]*GoBatisDB
39 | dbMap map[string]*DataSource
40 | }
41 |
42 | func (this *DBConfig) getDataSourceByName(datasource string) *DataSource {
43 | if this.dbMap == nil {
44 | this.dbMap = make(map[string]*DataSource)
45 | }
46 |
47 | if v, ok := this.dbMap[datasource]; ok {
48 | return v
49 | }
50 |
51 | for _, v := range this.DB {
52 | if v.DataSource == datasource {
53 | this.dbMap[datasource] = v
54 | return v
55 | }
56 | }
57 |
58 | return nil
59 | }
60 |
--------------------------------------------------------------------------------
/config_db_test.go:
--------------------------------------------------------------------------------
1 | package gobatis
2 |
3 | import (
4 | "fmt"
5 | "github.com/stretchr/testify/assert"
6 | "testing"
7 | )
8 |
9 | func TestDbConfig(t *testing.T) {
10 | ymlStr := `
11 | db:
12 | - datasource: ds1
13 | driverName: mysql
14 | dataSourceName: root:123456@tcp(127.0.0.1:3306)/test?charset=utf8
15 | maxLifeTime: 120
16 | maxOpenConns: 10
17 | maxIdleConns: 5
18 | - datasource: ds2
19 | driverName: mysql
20 | dataSourceName: root:123456@tcp(127.0.0.1:3306)/test?charset=utf8
21 | maxLifeTime: 120
22 | maxOpenConns: 10
23 | maxIdleConns: 5
24 | showSQL: true
25 | mappers:
26 | - userMapper.xml
27 | - orderMapper.xml
28 | `
29 | dbconf := buildDbConfig(ymlStr)
30 |
31 | dbc := dbconf.getDataSourceByName("ds1")
32 | assert.True(t, dbc != nil, "test fail: No datasource1")
33 | assert.True(t, dbconf.ShowSQL, "test fail: showSql == false")
34 | assert.Equal(t, dbc.DriverName, "mysql", "test fail, actual:"+dbc.DriverName)
35 | assert.Equal(t, dbc.DataSourceName, "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8", "test fail, actual:"+dbc.DataSourceName)
36 | assert.Equal(t, dbc.MaxLifeTime, 120, "test fail, actual:"+fmt.Sprintf("%d", dbc.MaxLifeTime))
37 | assert.Equal(t, dbc.MaxOpenConns, 10, "test fail, actual:"+fmt.Sprintf("%d", dbc.MaxOpenConns))
38 | assert.Equal(t, dbc.MaxIdleConns, 5, "test fail, actual:"+fmt.Sprintf("%d", dbc.MaxIdleConns))
39 | assert.True(t, len(dbconf.Mappers) == 2, "len(dbconf.Mappers) != 2")
40 | assert.Equal(t, dbconf.Mappers[0], "userMapper.xml", "test fail, actual:"+dbconf.Mappers[0])
41 | assert.Equal(t, dbconf.Mappers[1], "orderMapper.xml", "test fail, actual:"+dbconf.Mappers[1])
42 | }
43 |
44 | func TestDbConfigCodeInit(t *testing.T) {
45 | ds1 := NewDataSourceBuilder().
46 | DataSource("ds1").
47 | DriverName("mysql").
48 | DataSourceName("root:123456@tcp(127.0.0.1:3306)/test?charset=utf8").
49 | MaxLifeTime(120).
50 | MaxOpenConns(10).
51 | MaxIdleConns(5).
52 | Build()
53 |
54 | dbconf := NewDBConfigBuilder().
55 | DS([]*DataSource{ds1}).
56 | ShowSQL(true).
57 | Mappers([]string{"userMapper.xml", "orderMapper.xml"}).
58 | Build()
59 |
60 | dbc := dbconf.getDataSourceByName("ds1")
61 | assert.True(t, dbc != nil, "test fail: No datasource1")
62 | assert.True(t, dbconf.ShowSQL, "test fail: showSql == false")
63 | assert.Equal(t, dbc.DriverName, "mysql", "test fail, actual:"+dbc.DriverName)
64 | assert.Equal(t, dbc.DataSourceName, "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8", "test fail, actual:"+dbc.DataSourceName)
65 | assert.Equal(t, dbc.MaxLifeTime, 120, "test fail, actual:"+fmt.Sprintf("%d", dbc.MaxLifeTime))
66 | assert.Equal(t, dbc.MaxOpenConns, 10, "test fail, actual:"+fmt.Sprintf("%d", dbc.MaxOpenConns))
67 | assert.Equal(t, dbc.MaxIdleConns, 5, "test fail, actual:"+fmt.Sprintf("%d", dbc.MaxIdleConns))
68 | assert.True(t, len(dbconf.Mappers) == 2, "len(dbconf.Mappers) != 2")
69 | assert.Equal(t, dbconf.Mappers[0], "userMapper.xml", "test fail, actual:"+dbconf.Mappers[0])
70 | assert.Equal(t, dbconf.Mappers[1], "orderMapper.xml", "test fail, actual:"+dbconf.Mappers[1])
71 | }
72 |
--------------------------------------------------------------------------------
/config_mapper.go:
--------------------------------------------------------------------------------
1 | package gobatis
2 |
3 | import (
4 | "sync"
5 | )
6 |
7 | type mapperConfig struct {
8 | mappedStmts map[string]*node
9 | mappedSql map[string]*node
10 | cache map[string]*mappedStmt
11 | mu sync.Mutex
12 | }
13 |
14 | func (this *mapperConfig) put(id string, n *node) bool {
15 | this.mu.Lock()
16 | defer this.mu.Unlock()
17 |
18 | if _, ok := this.mappedStmts[id]; ok {
19 | return false
20 | }
21 |
22 | this.mappedStmts[id] = n
23 | return true
24 | }
25 |
26 | func (this *mapperConfig) putSql(id string, n *node) bool {
27 | this.mu.Lock()
28 | defer this.mu.Unlock()
29 |
30 | if _, ok := this.mappedSql[id]; ok {
31 | return false
32 | }
33 |
34 | this.mappedSql[id] = n
35 | return true
36 | }
37 |
38 | func (this *mapperConfig) getXmlNode(id string) (rootNode *node, resultType string) {
39 | rootNode, ok := this.mappedStmts[id]
40 | if !ok {
41 | panic("Can not find id:" + id + "mapped stmt")
42 | }
43 |
44 | resultType = ""
45 | if rootNode.Name == "select" {
46 | resultTypeAttr, ok := rootNode.Attrs["resultType"]
47 | if !ok {
48 | panic("Tag `