go-on-rails 0.1.4 → 0.1.5
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/README.md +4 -2
- data/lib/generators/gor/gor_generator.rb +8 -4
- data/lib/generators/gor/templates/db.go.erb +2 -2
- data/lib/generators/gor/templates/gor_model.go.erb +217 -41
- metadata +2 -2
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA1:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: 4885ebf7ebb9df3a3c2941dd88966f28384975a1
|
4
|
+
data.tar.gz: 71d6fca3d339378f36105063de928ed2f3620d0a
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: 86055cbc92c586e8c1764f392f2bc1ca895faee9b3b0933a3c88c87ea58199bdabfd2b24853a55a9b6b46b51f7bb316e470c9d3004cac3d29b344b4f46390154
|
7
|
+
data.tar.gz: a835298ceea075195217320032977be3530b1dad25aa1233f72ba34d33553e64ed581bdaa248f4c692b3d69b2c325730bd6edd81af92339d9afe930f79b8ae27
|
data/README.md
CHANGED
@@ -1,3 +1,5 @@
|
|
1
|
+
[![Gem Version](https://badge.fury.io/rb/go-on-rails.svg)](https://badge.fury.io/rb/go-on-rails)
|
2
|
+
|
1
3
|
<img align="right" width="260" height="260" src="./go-on-rails.png">
|
2
4
|
|
3
5
|
go-on-rails
|
@@ -9,7 +11,7 @@ go-on-rails is a Rails generator created for three scenarios:
|
|
9
11
|
2. Use your farmiliar Rails tools to develope and manage a Golang app project
|
10
12
|
3. Convert a *not very complicated* Rails app to Golang equivalent
|
11
13
|
|
12
|
-
Here's a simple [example(tutorial)](https://github.com/goonr/example_simple) shows the basic usage of go-on-rails generator, and
|
14
|
+
Here's a simple [example(tutorial)](https://github.com/goonr/example_simple) shows the basic usage of go-on-rails generator, and [another example](https://github.com/goonr/example_with_admin) shows how to integrate Go APIs in a Rails project. Some real-world examples are coming soon.
|
13
15
|
|
14
16
|
## Prerequisites
|
15
17
|
|
@@ -21,7 +23,7 @@ Here's a simple [example(tutorial)](https://github.com/goonr/example_simple) sho
|
|
21
23
|
Add this line to your application's Gemfile:
|
22
24
|
|
23
25
|
```ruby
|
24
|
-
gem 'go-on-rails', '~> 0.1.
|
26
|
+
gem 'go-on-rails', '~> 0.1.4'
|
25
27
|
```
|
26
28
|
|
27
29
|
And then execute:
|
@@ -29,6 +29,10 @@ class GorGenerator < Rails::Generators::Base
|
|
29
29
|
puts "Rails env: [#{rails_env}]"
|
30
30
|
puts "The models: #{@models} will be converted to a Golang App!"
|
31
31
|
|
32
|
+
# read the database configuration
|
33
|
+
@db_config = {}
|
34
|
+
create_database_config(rails_env)
|
35
|
+
|
32
36
|
@models.each do |m|
|
33
37
|
begin
|
34
38
|
klass = m.split('::').inject(Object) { |kls, part| kls.const_get(part) }
|
@@ -48,8 +52,6 @@ class GorGenerator < Rails::Generators::Base
|
|
48
52
|
copy_file "main.go", "go_app/main.go"
|
49
53
|
|
50
54
|
# generate program for database connection
|
51
|
-
@db_config = {}
|
52
|
-
create_database_config(rails_env)
|
53
55
|
template "db.go.erb", "go_app/models/db.go"
|
54
56
|
|
55
57
|
# generate the controllers and views dir
|
@@ -75,6 +77,7 @@ class GorGenerator < Rails::Generators::Base
|
|
75
77
|
|
76
78
|
def create_database_config rails_env
|
77
79
|
db_conf = Rails.configuration.database_configuration[rails_env]
|
80
|
+
db_conf["host"] = "localhost" unless db_conf["host"]
|
78
81
|
case db_conf["adapter"]
|
79
82
|
when "sqlite3"
|
80
83
|
@db_config[:driver_name] = "sqlite3"
|
@@ -82,10 +85,11 @@ class GorGenerator < Rails::Generators::Base
|
|
82
85
|
@db_config[:driver_package] = "_ \"github.com/mattn/go-sqlite3\""
|
83
86
|
when "mysql2"
|
84
87
|
@db_config[:driver_name] = "mysql"
|
88
|
+
db_conf["port"] = 3306 unless db_conf["port"]
|
85
89
|
# MySQL DSN format: username:password@protocol(address)/dbname?param=value
|
86
90
|
# See more: https://github.com/go-sql-driver/mysql
|
87
|
-
format = "%s:%s
|
88
|
-
@db_config[:dsn] = sprintf(format, *db_conf.values_at("username", "password", "host", "database", "encoding"))
|
91
|
+
format = "%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local"
|
92
|
+
@db_config[:dsn] = sprintf(format, *db_conf.values_at("username", "password", "host", "port", "database", "encoding"))
|
89
93
|
@db_config[:driver_package] = "_ \"github.com/go-sql-driver/mysql\""
|
90
94
|
when "postgresql"
|
91
95
|
@db_config[:driver_name] = "postgres"
|
@@ -7,7 +7,7 @@ import (
|
|
7
7
|
"github.com/jmoiron/sqlx"
|
8
8
|
)
|
9
9
|
|
10
|
-
var
|
10
|
+
var DB *sqlx.DB
|
11
11
|
|
12
12
|
func init() {
|
13
13
|
var err error
|
@@ -19,7 +19,7 @@ func init() {
|
|
19
19
|
if dsn == "" {
|
20
20
|
log.Fatal("Invalid DSN")
|
21
21
|
}
|
22
|
-
|
22
|
+
DB, err = sqlx.Connect(driver_name, dsn)
|
23
23
|
if err != nil {
|
24
24
|
log.Fatal(err)
|
25
25
|
}
|
@@ -9,6 +9,7 @@ import (
|
|
9
9
|
"errors"
|
10
10
|
"fmt"
|
11
11
|
"log"
|
12
|
+
"math"
|
12
13
|
"strings"
|
13
14
|
<%- if @struct_info[:has_datetime_type] -%>
|
14
15
|
"time"
|
@@ -26,13 +27,187 @@ type <%= @model_name %> struct {
|
|
26
27
|
<%= @struct_info[:struct_body] -%>
|
27
28
|
}
|
28
29
|
|
29
|
-
//
|
30
|
+
// DataStruct for the pagination
|
31
|
+
type <%= @model_name %>Page struct {
|
32
|
+
WhereString string
|
33
|
+
WhereParams []interface{}
|
34
|
+
Order map[string]string
|
35
|
+
FirstId int64
|
36
|
+
LastId int64
|
37
|
+
PageNum int
|
38
|
+
PerPage int
|
39
|
+
TotalPages int
|
40
|
+
TotalItems int64
|
41
|
+
orderStr string
|
42
|
+
}
|
43
|
+
|
44
|
+
// Current get the current page of <%= @model_name %>Page object for pagination
|
45
|
+
func (_p *<%= @model_name %>Page) Current() ([]<%= @model_name %>, error) {
|
46
|
+
if _, exist := _p.Order["id"]; !exist {
|
47
|
+
return nil, errors.New("No id order specified in Order map")
|
48
|
+
}
|
49
|
+
err := _p.buildPageCount()
|
50
|
+
if err != nil {
|
51
|
+
return nil, fmt.Errorf("Calculate page count error: %v", err)
|
52
|
+
}
|
53
|
+
if _p.orderStr == "" {
|
54
|
+
_p.buildOrder()
|
55
|
+
}
|
56
|
+
idStr, idParams := _p.buildIdRestrict("current")
|
57
|
+
<% if @db_config[:driver_name] == "postgres" %>
|
58
|
+
whereStr := fmt.Sprintf("%s %s %s FETCH NEXT %v ROWS ONLY", _p.WhereString, idStr, _p.orderStr, _p.PerPage)
|
59
|
+
<% else %>
|
60
|
+
whereStr := fmt.Sprintf("%s %s %s LIMIT %v", _p.WhereString, idStr, _p.orderStr, _p.PerPage)
|
61
|
+
<% end %>
|
62
|
+
whereParams := []interface{}{}
|
63
|
+
whereParams = append(append(whereParams, _p.WhereParams...), idParams...)
|
64
|
+
<%= param_name_plural %>, err := Find<%= @model_name.pluralize %>Where(whereStr, whereParams...)
|
65
|
+
if err != nil {
|
66
|
+
return nil, err
|
67
|
+
}
|
68
|
+
if len(<%= param_name_plural %>) != 0 {
|
69
|
+
_p.FirstId, _p.LastId = <%= param_name_plural %>[0].Id, <%= param_name_plural %>[len(<%= param_name_plural %>)-1].Id
|
70
|
+
}
|
71
|
+
return <%= param_name_plural %>, nil
|
72
|
+
}
|
73
|
+
|
74
|
+
// Current get the previous page of <%= @model_name %>Page object for pagination
|
75
|
+
func (_p *<%= @model_name %>Page) Previous() ([]<%= @model_name %>, error) {
|
76
|
+
if _p.PageNum == 0 {
|
77
|
+
return nil, errors.New("This's the first page, no previous page yet")
|
78
|
+
}
|
79
|
+
if _, exist := _p.Order["id"]; !exist {
|
80
|
+
return nil, errors.New("No id order specified in Order map")
|
81
|
+
}
|
82
|
+
err := _p.buildPageCount()
|
83
|
+
if err != nil {
|
84
|
+
return nil, fmt.Errorf("Calculate page count error: %v", err)
|
85
|
+
}
|
86
|
+
if _p.orderStr == "" {
|
87
|
+
_p.buildOrder()
|
88
|
+
}
|
89
|
+
idStr, idParams := _p.buildIdRestrict("previous")
|
90
|
+
<% if @db_config[:driver_name] == "postgres" %>
|
91
|
+
whereStr := fmt.Sprintf("%s %s %s FETCH NEXT %v ROWS ONLY", _p.WhereString, idStr, _p.orderStr, _p.PerPage)
|
92
|
+
<% else %>
|
93
|
+
whereStr := fmt.Sprintf("%s %s %s LIMIT %v", _p.WhereString, idStr, _p.orderStr, _p.PerPage)
|
94
|
+
<% end %>
|
95
|
+
whereParams := []interface{}{}
|
96
|
+
whereParams = append(append(whereParams, _p.WhereParams...), idParams...)
|
97
|
+
<%= param_name_plural %>, err := Find<%= @model_name.pluralize %>Where(whereStr, whereParams...)
|
98
|
+
if err != nil {
|
99
|
+
return nil, err
|
100
|
+
}
|
101
|
+
if len(<%= param_name_plural %>) != 0 {
|
102
|
+
_p.FirstId, _p.LastId = <%= param_name_plural %>[0].Id, <%= param_name_plural %>[len(<%= param_name_plural %>)-1].Id
|
103
|
+
}
|
104
|
+
_p.PageNum -= 1
|
105
|
+
return <%= param_name_plural %>, nil
|
106
|
+
}
|
107
|
+
|
108
|
+
// Current get the next page of <%= @model_name %>Page object for pagination
|
109
|
+
func (_p *<%= @model_name %>Page) Next() ([]<%= @model_name %>, error) {
|
110
|
+
if _p.PageNum == _p.TotalPages-1 {
|
111
|
+
return nil, errors.New("This's the last page, no next page yet")
|
112
|
+
}
|
113
|
+
if _, exist := _p.Order["id"]; !exist {
|
114
|
+
return nil, errors.New("No id order specified in Order map")
|
115
|
+
}
|
116
|
+
err := _p.buildPageCount()
|
117
|
+
if err != nil {
|
118
|
+
return nil, fmt.Errorf("Calculate page count error: %v", err)
|
119
|
+
}
|
120
|
+
if _p.orderStr == "" {
|
121
|
+
_p.buildOrder()
|
122
|
+
}
|
123
|
+
idStr, idParams := _p.buildIdRestrict("next")
|
124
|
+
<% if @db_config[:driver_name] == "postgres" %>
|
125
|
+
whereStr := fmt.Sprintf("%s %s %s FETCH NEXT %v ROWS ONLY", _p.WhereString, idStr, _p.orderStr, _p.PerPage)
|
126
|
+
<% else %>
|
127
|
+
whereStr := fmt.Sprintf("%s %s %s LIMIT %v", _p.WhereString, idStr, _p.orderStr, _p.PerPage)
|
128
|
+
<% end %>
|
129
|
+
whereParams := []interface{}{}
|
130
|
+
whereParams = append(append(whereParams, _p.WhereParams...), idParams...)
|
131
|
+
<%= param_name_plural %>, err := Find<%= @model_name.pluralize %>Where(whereStr, whereParams...)
|
132
|
+
if err != nil {
|
133
|
+
return nil, err
|
134
|
+
}
|
135
|
+
if len(<%= param_name_plural %>) != 0 {
|
136
|
+
_p.FirstId, _p.LastId = <%= param_name_plural %>[0].Id, <%= param_name_plural %>[len(<%= param_name_plural %>)-1].Id
|
137
|
+
}
|
138
|
+
_p.PageNum += 1
|
139
|
+
return <%= param_name_plural %>, nil
|
140
|
+
}
|
141
|
+
|
142
|
+
// buildOrder is for <%= @model_name %>Page object to build SQL ORDER clause
|
143
|
+
func (_p *<%= @model_name %>Page) buildOrder() {
|
144
|
+
tempList := []string{}
|
145
|
+
for k, v := range _p.Order {
|
146
|
+
tempList = append(tempList, fmt.Sprintf("%v %v", k, v))
|
147
|
+
}
|
148
|
+
_p.orderStr = " ORDER BY " + strings.Join(tempList, ", ")
|
149
|
+
}
|
150
|
+
|
151
|
+
// buildIdRestrict is for <%= @model_name %>Page object to build a SQL clause for ID restriction,
|
152
|
+
// implementing a simple keyset style pagination
|
153
|
+
func (_p *<%= @model_name %>Page) buildIdRestrict(direction string) (idStr string, idParams []interface{}) {
|
154
|
+
switch direction {
|
155
|
+
case "previous":
|
156
|
+
if strings.ToLower(_p.Order["id"]) == "desc" {
|
157
|
+
idStr += "id > ? "
|
158
|
+
idParams = append(_p.WhereParams, _p.FirstId)
|
159
|
+
} else {
|
160
|
+
idStr += "id < ? "
|
161
|
+
idParams = append(_p.WhereParams, _p.FirstId)
|
162
|
+
}
|
163
|
+
case "current":
|
164
|
+
// trick to make Where function work
|
165
|
+
if _p.PageNum == 0 && _p.FirstId == 0 && _p.LastId == 0 {
|
166
|
+
idStr += "id > ? "
|
167
|
+
idParams = append(_p.WhereParams, 0)
|
168
|
+
} else {
|
169
|
+
if strings.ToLower(_p.Order["id"]) == "desc" {
|
170
|
+
idStr += "id <= ? AND id >= ? "
|
171
|
+
idParams = append(_p.WhereParams, _p.FirstId, _p.LastId)
|
172
|
+
} else {
|
173
|
+
idStr += "id >= ? AND id <= ? "
|
174
|
+
idParams = append(_p.WhereParams, _p.FirstId, _p.LastId)
|
175
|
+
}
|
176
|
+
}
|
177
|
+
case "next":
|
178
|
+
if strings.ToLower(_p.Order["id"]) == "desc" {
|
179
|
+
idStr += "id < ? "
|
180
|
+
idParams = append(_p.WhereParams, _p.LastId)
|
181
|
+
} else {
|
182
|
+
idStr += "id > ? "
|
183
|
+
idParams = append(_p.WhereParams, _p.LastId)
|
184
|
+
}
|
185
|
+
}
|
186
|
+
return
|
187
|
+
}
|
188
|
+
|
189
|
+
// buildPageCount calculate the TotalItems/TotalPages for the <%= @model_name %>Page object
|
190
|
+
func (_p *<%= @model_name %>Page) buildPageCount() error {
|
191
|
+
count, err := <%= @model_name %>CountWhere(_p.WhereString, _p.WhereParams...)
|
192
|
+
if err != nil {
|
193
|
+
return err
|
194
|
+
}
|
195
|
+
_p.TotalItems = count
|
196
|
+
if _p.PerPage == 0 {
|
197
|
+
_p.PerPage = 10
|
198
|
+
}
|
199
|
+
_p.TotalPages = int(math.Ceil(float64(_p.TotalItems) / float64(_p.PerPage)))
|
200
|
+
return nil
|
201
|
+
}
|
202
|
+
|
203
|
+
|
204
|
+
// Find<%= @model_name %> find a single <%= model_name_underscore %> by an ID
|
30
205
|
func Find<%= @model_name %>(id int64) (*<%= @model_name %>, error) {
|
31
206
|
if id == 0 {
|
32
|
-
return nil, errors.New("Invalid
|
207
|
+
return nil, errors.New("Invalid ID: it can't be zero")
|
33
208
|
}
|
34
209
|
_<%= model_name_underscore %> := <%= @model_name %>{}
|
35
|
-
err :=
|
210
|
+
err := DB.Get(&_<%= model_name_underscore %>, DB.Rebind(`SELECT * FROM <%= table_name %> WHERE id = ? LIMIT 1`), id)
|
36
211
|
if err != nil {
|
37
212
|
log.Printf("Error: %v\n", err)
|
38
213
|
return nil, err
|
@@ -40,10 +215,10 @@ func Find<%= @model_name %>(id int64) (*<%= @model_name %>, error) {
|
|
40
215
|
return &_<%= model_name_underscore %>, nil
|
41
216
|
}
|
42
217
|
|
43
|
-
// First<%= @model_name %> find the first one <%= model_name_underscore %> by
|
218
|
+
// First<%= @model_name %> find the first one <%= model_name_underscore %> by ID ASC order
|
44
219
|
func First<%= @model_name %>() (*<%= @model_name %>, error) {
|
45
220
|
_<%= model_name_underscore %> := <%= @model_name %>{}
|
46
|
-
err :=
|
221
|
+
err := DB.Get(&_<%= model_name_underscore %>, DB.Rebind(`SELECT * FROM <%= table_name %> ORDER BY id ASC LIMIT 1`))
|
47
222
|
if err != nil {
|
48
223
|
log.Printf("Error: %v\n", err)
|
49
224
|
return nil, err
|
@@ -51,11 +226,11 @@ func First<%= @model_name %>() (*<%= @model_name %>, error) {
|
|
51
226
|
return &_<%= model_name_underscore %>, nil
|
52
227
|
}
|
53
228
|
|
54
|
-
// First<%= @model_name.pluralize %> find the first N <%= model_name_underscore.pluralize %> by
|
229
|
+
// First<%= @model_name.pluralize %> find the first N <%= model_name_underscore.pluralize %> by ID ASC order
|
55
230
|
func First<%= @model_name.pluralize %>(n uint32) ([]<%= @model_name %>, error) {
|
56
231
|
_<%= param_name_plural %> := []<%= @model_name %>{}
|
57
232
|
sql := fmt.Sprintf("SELECT * FROM <%= table_name %> ORDER BY id ASC LIMIT %v", n)
|
58
|
-
err :=
|
233
|
+
err := DB.Select(&_<%= param_name_plural %>, DB.Rebind(sql))
|
59
234
|
if err != nil {
|
60
235
|
log.Printf("Error: %v\n", err)
|
61
236
|
return nil, err
|
@@ -63,10 +238,10 @@ func First<%= @model_name.pluralize %>(n uint32) ([]<%= @model_name %>, error) {
|
|
63
238
|
return _<%= param_name_plural %>, nil
|
64
239
|
}
|
65
240
|
|
66
|
-
// Last<%= @model_name %> find the last one <%= model_name_underscore %> by
|
241
|
+
// Last<%= @model_name %> find the last one <%= model_name_underscore %> by ID DESC order
|
67
242
|
func Last<%= @model_name %>() (*<%= @model_name %>, error) {
|
68
243
|
_<%= model_name_underscore %> := <%= @model_name %>{}
|
69
|
-
err :=
|
244
|
+
err := DB.Get(&_<%= model_name_underscore %>, DB.Rebind(`SELECT * FROM <%= table_name %> ORDER BY id DESC LIMIT 1`))
|
70
245
|
if err != nil {
|
71
246
|
log.Printf("Error: %v\n", err)
|
72
247
|
return nil, err
|
@@ -74,11 +249,11 @@ func Last<%= @model_name %>() (*<%= @model_name %>, error) {
|
|
74
249
|
return &_<%= model_name_underscore %>, nil
|
75
250
|
}
|
76
251
|
|
77
|
-
// Last<%= @model_name.pluralize %> find the last N <%= model_name_underscore.pluralize %> by
|
252
|
+
// Last<%= @model_name.pluralize %> find the last N <%= model_name_underscore.pluralize %> by ID DESC order
|
78
253
|
func Last<%= @model_name.pluralize %>(n uint32) ([]<%= @model_name %>, error) {
|
79
254
|
_<%= param_name_plural %> := []<%= @model_name %>{}
|
80
255
|
sql := fmt.Sprintf("SELECT * FROM <%= table_name %> ORDER BY id DESC LIMIT %v", n)
|
81
|
-
err :=
|
256
|
+
err := DB.Select(&_<%= param_name_plural %>, DB.Rebind(sql))
|
82
257
|
if err != nil {
|
83
258
|
log.Printf("Error: %v\n", err)
|
84
259
|
return nil, err
|
@@ -86,7 +261,7 @@ func Last<%= @model_name.pluralize %>(n uint32) ([]<%= @model_name %>, error) {
|
|
86
261
|
return _<%= param_name_plural %>, nil
|
87
262
|
}
|
88
263
|
|
89
|
-
// Find<%= @model_name.pluralize %> find one or more <%= model_name_underscore.pluralize %> by
|
264
|
+
// Find<%= @model_name.pluralize %> find one or more <%= model_name_underscore.pluralize %> by the given ID(s)
|
90
265
|
func Find<%= @model_name.pluralize %>(ids ...int64) ([]<%= @model_name %>, error) {
|
91
266
|
if len(ids) == 0 {
|
92
267
|
msg := "At least one or more ids needed"
|
@@ -95,12 +270,12 @@ func Find<%= @model_name.pluralize %>(ids ...int64) ([]<%= @model_name %>, error
|
|
95
270
|
}
|
96
271
|
_<%= param_name_plural %> := []<%= @model_name %>{}
|
97
272
|
idsHolder := strings.Repeat(",?", len(ids)-1)
|
98
|
-
sql :=
|
273
|
+
sql := DB.Rebind(fmt.Sprintf(`SELECT * FROM <%= table_name %> WHERE id IN (?%s)`, idsHolder))
|
99
274
|
idsT := []interface{}{}
|
100
275
|
for _,id := range ids {
|
101
276
|
idsT = append(idsT, interface{}(id))
|
102
277
|
}
|
103
|
-
err :=
|
278
|
+
err := DB.Select(&_<%= param_name_plural %>, sql, idsT...)
|
104
279
|
if err != nil {
|
105
280
|
log.Printf("Error: %v\n", err)
|
106
281
|
return nil, err
|
@@ -113,7 +288,7 @@ func Find<%= @model_name %>By(field string, val interface{}) (*<%= @model_name %
|
|
113
288
|
_<%= model_name_underscore %> := <%= @model_name %>{}
|
114
289
|
sqlFmt := `SELECT * FROM <%= table_name %> WHERE %s = ? LIMIT 1`
|
115
290
|
sqlStr := fmt.Sprintf(sqlFmt, field)
|
116
|
-
err :=
|
291
|
+
err := DB.Get(&_<%= model_name_underscore %>, DB.Rebind(sqlStr), val)
|
117
292
|
if err != nil {
|
118
293
|
log.Printf("Error: %v\n", err)
|
119
294
|
return nil, err
|
@@ -125,7 +300,7 @@ func Find<%= @model_name %>By(field string, val interface{}) (*<%= @model_name %
|
|
125
300
|
func Find<%= @model_name.pluralize %>By(field string, val interface{}) (_<%= param_name_plural %> []<%= @model_name %>, err error) {
|
126
301
|
sqlFmt := `SELECT * FROM <%= table_name %> WHERE %s = ?`
|
127
302
|
sqlStr := fmt.Sprintf(sqlFmt, field)
|
128
|
-
err =
|
303
|
+
err = DB.Select(&_<%= param_name_plural %>, DB.Rebind(sqlStr), val)
|
129
304
|
if err != nil {
|
130
305
|
log.Printf("Error: %v\n", err)
|
131
306
|
return nil, err
|
@@ -135,7 +310,7 @@ func Find<%= @model_name.pluralize %>By(field string, val interface{}) (_<%= par
|
|
135
310
|
|
136
311
|
// All<%= @model_name.pluralize %> get all the <%= @model_name %> records
|
137
312
|
func All<%= @model_name.pluralize %>() (<%= param_name_plural %> []<%= @model_name %>, err error) {
|
138
|
-
err =
|
313
|
+
err = DB.Select(&<%= param_name_plural %>, "SELECT * FROM <%= table_name %>")
|
139
314
|
if err != nil {
|
140
315
|
log.Println(err)
|
141
316
|
return nil, err
|
@@ -145,7 +320,7 @@ func All<%= @model_name.pluralize %>() (<%= param_name_plural %> []<%= @model_na
|
|
145
320
|
|
146
321
|
// <%= @model_name %>Count get the count of all the <%= @model_name %> records
|
147
322
|
func <%= @model_name %>Count() (c int64, err error) {
|
148
|
-
err =
|
323
|
+
err = DB.Get(&c, "SELECT count(*) FROM <%= table_name %>")
|
149
324
|
if err != nil {
|
150
325
|
log.Println(err)
|
151
326
|
return 0, err
|
@@ -159,7 +334,7 @@ func <%= @model_name %>CountWhere(where string, args ...interface{}) (c int64, e
|
|
159
334
|
if len(where) > 0 {
|
160
335
|
sql = sql + " WHERE " + where
|
161
336
|
}
|
162
|
-
stmt, err :=
|
337
|
+
stmt, err := DB.Preparex(DB.Rebind(sql))
|
163
338
|
if err != nil {
|
164
339
|
log.Println(err)
|
165
340
|
return 0, err
|
@@ -272,9 +447,9 @@ func <%= @model_name %>IncludesWhere(assocs []string, sql string, args ...interf
|
|
272
447
|
return _<%= param_name_plural %>, nil
|
273
448
|
}
|
274
449
|
|
275
|
-
// <%= @model_name %>Ids get all the
|
450
|
+
// <%= @model_name %>Ids get all the IDs of <%= @model_name %> records
|
276
451
|
func <%= @model_name %>Ids() (ids []int64, err error) {
|
277
|
-
err =
|
452
|
+
err = DB.Select(&ids, "SELECT id FROM <%= table_name %>")
|
278
453
|
if err != nil {
|
279
454
|
log.Println(err)
|
280
455
|
return nil, err
|
@@ -282,7 +457,7 @@ func <%= @model_name %>Ids() (ids []int64, err error) {
|
|
282
457
|
return ids, nil
|
283
458
|
}
|
284
459
|
|
285
|
-
// <%= @model_name %>IdsWhere get all the
|
460
|
+
// <%= @model_name %>IdsWhere get all the IDs of <%= @model_name %> records by where restriction
|
286
461
|
func <%= @model_name %>IdsWhere(where string, args ...interface{}) ([]int64, error) {
|
287
462
|
ids, err := <%= @model_name %>IntCol("id", where, args...)
|
288
463
|
return ids, err
|
@@ -294,7 +469,7 @@ func <%= @model_name %>IntCol(col, where string, args ...interface{}) (intColRec
|
|
294
469
|
if len(where) > 0 {
|
295
470
|
sql = sql + " WHERE " + where
|
296
471
|
}
|
297
|
-
stmt, err :=
|
472
|
+
stmt, err := DB.Preparex(DB.Rebind(sql))
|
298
473
|
if err != nil {
|
299
474
|
log.Println(err)
|
300
475
|
return nil, err
|
@@ -313,7 +488,7 @@ func <%= @model_name %>StrCol(col, where string, args ...interface{}) (strColRec
|
|
313
488
|
if len(where) > 0 {
|
314
489
|
sql = sql + " WHERE " + where
|
315
490
|
}
|
316
|
-
stmt, err :=
|
491
|
+
stmt, err := DB.Preparex(DB.Rebind(sql))
|
317
492
|
if err != nil {
|
318
493
|
log.Println(err)
|
319
494
|
return nil, err
|
@@ -334,7 +509,7 @@ func Find<%= @model_name.pluralize %>Where(where string, args ...interface{}) (<
|
|
334
509
|
if len(where) > 0 {
|
335
510
|
sql = sql + " WHERE " + where
|
336
511
|
}
|
337
|
-
stmt, err :=
|
512
|
+
stmt, err := DB.Preparex(DB.Rebind(sql))
|
338
513
|
if err != nil {
|
339
514
|
log.Println(err)
|
340
515
|
return nil, err
|
@@ -351,7 +526,7 @@ func Find<%= @model_name.pluralize %>Where(where string, args ...interface{}) (<
|
|
351
526
|
// with placeholders, eg: FindUserBySql("SELECT * FROM users WHERE first_name = ? AND age > ? ORDER BY DESC LIMIT 1", "John", 18)
|
352
527
|
// will return only One record in the table "users" whose first_name is "John" and age elder than 18
|
353
528
|
func Find<%= @model_name %>BySql(sql string, args ...interface{}) (*<%= @model_name %>, error) {
|
354
|
-
stmt, err :=
|
529
|
+
stmt, err := DB.Preparex(DB.Rebind(sql))
|
355
530
|
if err != nil {
|
356
531
|
log.Println(err)
|
357
532
|
return nil, err
|
@@ -369,7 +544,7 @@ func Find<%= @model_name %>BySql(sql string, args ...interface{}) (*<%= @model_n
|
|
369
544
|
// with placeholders, eg: FindUsersBySql("SELECT * FROM users WHERE first_name = ? AND age > ?", "John", 18)
|
370
545
|
// will return those records in the table "users" whose first_name is "John" and age elder than 18
|
371
546
|
func Find<%= @model_name.pluralize %>BySql(sql string, args ...interface{}) (<%= param_name_plural %> []<%= @model_name %>, err error) {
|
372
|
-
stmt, err :=
|
547
|
+
stmt, err := DB.Preparex(DB.Rebind(sql))
|
373
548
|
if err != nil {
|
374
549
|
log.Println(err)
|
375
550
|
return nil, err
|
@@ -404,7 +579,7 @@ func Create<%= @model_name %>(am map[string]interface{}) (int64, error) {
|
|
404
579
|
}
|
405
580
|
sqlFmt := `INSERT INTO <%= table_name %> (%s) VALUES (%s)`
|
406
581
|
sqlStr := fmt.Sprintf(sqlFmt, strings.Join(keys, ","), ":"+strings.Join(keys, ",:"))
|
407
|
-
result, err :=
|
582
|
+
result, err := DB.NamedExec(sqlStr, am)
|
408
583
|
if err != nil {
|
409
584
|
log.Println(err)
|
410
585
|
return 0, err
|
@@ -435,7 +610,7 @@ func (_<%= model_name_underscore %> *<%= @model_name %>) Create() (int64, error)
|
|
435
610
|
<%- end -%>
|
436
611
|
<%- end -%>
|
437
612
|
sql := `INSERT INTO <%= table_name %> (<%= col_names.join(",") %>) VALUES (:<%= col_names.join(",:") %>)`
|
438
|
-
result, err :=
|
613
|
+
result, err := DB.NamedExec(sql, _<%= model_name_underscore %>)
|
439
614
|
if err != nil {
|
440
615
|
log.Println(err)
|
441
616
|
return 0, err
|
@@ -517,7 +692,7 @@ func <%= @model_name %>Get<%= k.pluralize %>(id int64) ([]<%= v[:class_name] %>,
|
|
517
692
|
<%- unless @struct_info[:assoc_info][:has_one].empty? -%>
|
518
693
|
<%- has_one = @struct_info[:assoc_info][:has_one] -%>
|
519
694
|
<%- has_one.each do |k, v| -%>
|
520
|
-
// Create<%= k %> is a method
|
695
|
+
// Create<%= k %> is a method for the <%= @model_name %> model object to create an associated <%= k %> record
|
521
696
|
func (_<%= model_name_underscore %> *<%= @model_name %>) Create<%= k %>(am map[string]interface{}) error {
|
522
697
|
<%- if v[:foreign_key] -%>
|
523
698
|
am["<%= v[:foreign_key] %>"] = _<%= model_name_underscore %>.Id
|
@@ -557,14 +732,14 @@ func (_<%= model_name_underscore %> *<%= @model_name %>) Destroy() error {
|
|
557
732
|
return err
|
558
733
|
}
|
559
734
|
|
560
|
-
// Destroy<%= @model_name %> will destroy a <%= @model_name %> record specified by id parameter.
|
735
|
+
// Destroy<%= @model_name %> will destroy a <%= @model_name %> record specified by the id parameter.
|
561
736
|
func Destroy<%= @model_name %>(id int64) error {
|
562
737
|
<%- if @struct_info[:has_assoc_dependent] -%>
|
563
738
|
// Destroy association objects at first
|
564
739
|
// Not care if exec properly temporarily
|
565
740
|
destroy<%= @model_name %>Associations(id)
|
566
741
|
<%- end -%>
|
567
|
-
stmt, err :=
|
742
|
+
stmt, err := DB.Preparex(DB.Rebind(`DELETE FROM <%= table_name %> WHERE id = ?`))
|
568
743
|
_, err = stmt.Exec(id)
|
569
744
|
if err != nil {
|
570
745
|
return err
|
@@ -590,7 +765,7 @@ func Destroy<%= @model_name.pluralize %>(ids ...int64) (int64, error) {
|
|
590
765
|
for _,id := range ids {
|
591
766
|
idsT = append(idsT, interface{}(id))
|
592
767
|
}
|
593
|
-
stmt, err :=
|
768
|
+
stmt, err := DB.Preparex(DB.Rebind(sql))
|
594
769
|
result, err := stmt.Exec(idsT...)
|
595
770
|
if err != nil {
|
596
771
|
return 0, err
|
@@ -602,8 +777,8 @@ func Destroy<%= @model_name.pluralize %>(ids ...int64) (int64, error) {
|
|
602
777
|
return cnt, nil
|
603
778
|
}
|
604
779
|
|
605
|
-
// Destroy<%= @model_name.pluralize %>Where delete records by a where clause
|
606
|
-
//
|
780
|
+
// Destroy<%= @model_name.pluralize %>Where delete records by a where clause restriction.
|
781
|
+
// e.g. Destroy<%= @model_name.pluralize %>Where("name = ?", "John")
|
607
782
|
// And this func will not call the association dependent action
|
608
783
|
func Destroy<%= @model_name.pluralize %>Where(where string, args ...interface{}) (int64, error) {
|
609
784
|
sql := `DELETE FROM <%= table_name %> WHERE `
|
@@ -620,7 +795,7 @@ func Destroy<%= @model_name.pluralize %>Where(where string, args ...interface{})
|
|
620
795
|
destroy<%= @model_name %>Associations(ids...)
|
621
796
|
}
|
622
797
|
<%- end -%>
|
623
|
-
stmt, err :=
|
798
|
+
stmt, err := DB.Preparex(DB.Rebind(sql))
|
624
799
|
result, err := stmt.Exec(args...)
|
625
800
|
if err != nil {
|
626
801
|
return 0, err
|
@@ -731,7 +906,7 @@ func (_<%= model_name_underscore %> *<%= @model_name %>) Save() error {
|
|
731
906
|
sqlFmt := `UPDATE <%= table_name %> SET %s WHERE id = %v`
|
732
907
|
<%- save_col_names = col_names - ["created_at"] -%>
|
733
908
|
sqlStr := fmt.Sprintf(sqlFmt, "<%= save_col_names.zip(save_col_names).map{|c| c.join(" = :")}.join(", ") %>", _<%= model_name_underscore %>.Id)
|
734
|
-
_, err =
|
909
|
+
_, err = DB.NamedExec(sqlStr, _<%= model_name_underscore %>)
|
735
910
|
return err
|
736
911
|
}
|
737
912
|
|
@@ -756,7 +931,7 @@ func Update<%= @model_name %>(id int64, am map[string]interface{}) error {
|
|
756
931
|
setKeysArr = append(setKeysArr, s)
|
757
932
|
}
|
758
933
|
sqlStr := fmt.Sprintf(sqlFmt, strings.Join(setKeysArr, ", "), id)
|
759
|
-
_, err :=
|
934
|
+
_, err := DB.NamedExec(sqlStr, am)
|
760
935
|
if err != nil {
|
761
936
|
log.Println(err)
|
762
937
|
return err
|
@@ -773,6 +948,7 @@ func (_<%= model_name_underscore %> *<%= @model_name %>) Update(am map[string]in
|
|
773
948
|
return err
|
774
949
|
}
|
775
950
|
|
951
|
+
// UpdateAttributes method is supposed to be used to update <%= @model_name %> records as corresponding update_attributes in Ruby on Rails.
|
776
952
|
func (_<%= model_name_underscore %> *<%= @model_name %>) UpdateAttributes(am map[string]interface{}) error {
|
777
953
|
if _<%= model_name_underscore %>.Id == 0 {
|
778
954
|
return errors.New("Invalid Id field: it can't be a zero value")
|
@@ -781,7 +957,7 @@ func (_<%= model_name_underscore %> *<%= @model_name %>) UpdateAttributes(am map
|
|
781
957
|
return err
|
782
958
|
}
|
783
959
|
|
784
|
-
// UpdateColumns method is supposed to be used to update <%= @model_name %> records as corresponding update_columns in Rails
|
960
|
+
// UpdateColumns method is supposed to be used to update <%= @model_name %> records as corresponding update_columns in Ruby on Rails.
|
785
961
|
func (_<%= model_name_underscore %> *<%= @model_name %>) UpdateColumns(am map[string]interface{}) error {
|
786
962
|
if _<%= model_name_underscore %>.Id == 0 {
|
787
963
|
return errors.New("Invalid Id field: it can't be a zero value")
|
@@ -791,7 +967,7 @@ func (_<%= model_name_underscore %> *<%= @model_name %>) UpdateColumns(am map[st
|
|
791
967
|
}
|
792
968
|
|
793
969
|
// Update<%= @model_name.pluralize %>BySql is used to update <%= @model_name %> records by a SQL clause
|
794
|
-
//
|
970
|
+
// using the '?' binding syntax.
|
795
971
|
func Update<%= @model_name.pluralize %>BySql(sql string, args ...interface{}) (int64, error) {
|
796
972
|
if sql == "" {
|
797
973
|
return 0, errors.New("A blank SQL clause")
|
@@ -800,7 +976,7 @@ func Update<%= @model_name.pluralize %>BySql(sql string, args ...interface{}) (i
|
|
800
976
|
sql = strings.Replace(strings.ToLower(sql), "set", "set updated_at = ?, ", 1)
|
801
977
|
args = append([]interface{}{time.Now()}, args...)
|
802
978
|
<%- end -%>
|
803
|
-
stmt, err :=
|
979
|
+
stmt, err := DB.Preparex(DB.Rebind(sql))
|
804
980
|
result, err := stmt.Exec(args...)
|
805
981
|
if err != nil {
|
806
982
|
return 0, err
|
metadata
CHANGED
@@ -1,14 +1,14 @@
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
2
2
|
name: go-on-rails
|
3
3
|
version: !ruby/object:Gem::Version
|
4
|
-
version: 0.1.
|
4
|
+
version: 0.1.5
|
5
5
|
platform: ruby
|
6
6
|
authors:
|
7
7
|
- B1nj0y
|
8
8
|
autorequire:
|
9
9
|
bindir: bin
|
10
10
|
cert_chain: []
|
11
|
-
date: 2017-
|
11
|
+
date: 2017-09-05 00:00:00.000000000 Z
|
12
12
|
dependencies: []
|
13
13
|
description: Modeling, developing and testing your Golang app with your familiar Rails
|
14
14
|
tools like rails generate, db migration, console etc. It is more meant to help integrating
|