go-on-rails 0.1.0 → 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 98efb6c9f89545a36de83af4b3a972af42dcdab3
4
- data.tar.gz: 15f4301f4f7030325d8e9e29140b31308118e75d
3
+ metadata.gz: 116d71d0238292ffc07cf20ac48510629db81d0a
4
+ data.tar.gz: 2cc31cd05ad5b3683b1f3f8fbe5c8545c9ebbe25
5
5
  SHA512:
6
- metadata.gz: f3827a7e075ce518bfc57a595174d8b2d6a68372c5f8b093d45b67fae06ad7ab46b20a8e6aa2f10a2a4879da1d62b2fe4312d20dc507060c2bef5c28807770a7
7
- data.tar.gz: 65b16cacd2909f45a721903be8e51676043c365840db2c82c6a1e44dd18ed85a991827c8fcb1fdf9a31810ca99746ff0068c5037e7f8df9e535b15fa0cbef3b4
6
+ metadata.gz: 831ea5814ff101e6f6db2aad38accb6c63c9cc9177390a77edbc1fb396b8ff6696f975387a8f722d29f4452091dff4de019b3f768e69ee7561bb1556f81135f8
7
+ data.tar.gz: 11ab127f3ff002f793dd8cb3bc11a96926a36c96bc95c1413ac1e83efafdb561df9f0401236e312774e0b5b19639dd51e7d1181564b0e4bb7b49b50957c1fb68
data/README.md CHANGED
@@ -21,7 +21,7 @@ Here's a simple [example(tutorial)](https://github.com/goonr/example_simple) sho
21
21
  Add this line to your application's Gemfile:
22
22
 
23
23
  ```ruby
24
- gem 'go-on-rails', '~> 0.1.0'
24
+ gem 'go-on-rails', '~> 0.1.1'
25
25
  ```
26
26
 
27
27
  And then execute:
@@ -76,15 +76,22 @@ And the gem is still under development, so there're a lot of known issues.
76
76
 
77
77
  ## Known issues and TODOs
78
78
 
79
- * the generated Golang codes includes the association between models, basic relations like has_many, has_one, belongs_to have been supported
80
- * so some association functions is available
81
- * and the :dependent action is triggered when destroying some related model
82
- * some validation like presense, length restriction and format are supported
83
- * databases specific functions between mysql, postgres are not covered yet
84
- * model callbacks are not available
79
+ * databases specific functions between MySQL, Postgres are not covered yet
85
80
  * sql.NullType not supported yet, so you'd better in the migrations set those columns "not null" with a default value that's consistent with Golang's zero value specification, such as "" default for string and text typed column, and 0 default for int, etc.
86
81
 
87
- Really a lot...
82
+ - [x] Associations
83
+ - [x] has_many
84
+ - [x] has_one
85
+ - [x] belongs_to
86
+ - [x] dependent
87
+ - [x] Validations
88
+ - [x] length
89
+ - [x] presence
90
+ - [x] format(string only)
91
+ - [x] numericality(partially)
92
+ - [ ] other validations
93
+ - [ ] Callbacks
94
+ - [ ] Transactions
88
95
 
89
96
  ## Golang dependencies by default
90
97
 
@@ -1,12 +1,10 @@
1
1
  module GoOnRails
2
2
  class Association
3
- def initialize(klass, models, max_col_size, max_type_size)
3
+ def initialize(klass, models)
4
4
  @klass = klass
5
5
  @models = models
6
- @max_col_size = max_col_size
7
- @max_type_size = max_type_size
8
6
  end
9
- attr_reader :klass, :models, :max_col_size, :max_type_size
7
+ attr_reader :klass, :models
10
8
 
11
9
  def get_schema_info
12
10
  info = {struct_body: "", has_assoc_dependent: false, assoc_info: {has_many: {}, has_one: {}, belongs_to: {}}}
@@ -32,8 +30,7 @@ module GoOnRails
32
30
  end
33
31
  info[:has_assoc_dependent] = true if assoc.options.key? :dependent
34
32
  if col_name && type_name && (self.models.include? class_name)
35
- format = "\t%-#{max_col_size}.#{max_col_size+2}s%-#{max_type_size}.#{max_type_size}s`%s`\n"
36
- info[:struct_body] << sprintf(format, col_name, type_name, tags.join(" "))
33
+ info[:struct_body] << sprintf("%s %s `%s`\n", col_name, type_name, tags.join(" "))
37
34
  end
38
35
  end
39
36
  info
@@ -14,13 +14,11 @@ module GoOnRails
14
14
  "date" => "time.Time"
15
15
  }
16
16
 
17
- def initialize(klass, models, option = {})
17
+ def initialize(klass, models)
18
18
  @klass = klass
19
19
  @models = models
20
- @max_col_size = 0
21
- @max_type_size = 0
22
20
  end
23
- attr_accessor :klass, :models, :max_col_size, :max_type_size
21
+ attr_accessor :klass, :models
24
22
 
25
23
  def convert
26
24
  get_schema_info
@@ -31,8 +29,6 @@ module GoOnRails
31
29
  def get_schema_info
32
30
  struct_info = {col_names: [], timestamp_cols: [], has_datetime_type: false, struct_body: ""}
33
31
 
34
- self.max_col_size = get_max_col_size
35
- self.max_type_size = get_max_type_size
36
32
  validation = GoOnRails::Validator.new(self.klass)
37
33
 
38
34
  self.klass.columns.each_with_index do |col, index|
@@ -55,9 +51,8 @@ module GoOnRails
55
51
  type = TYPE_MAP[col_type] || "string"
56
52
  end
57
53
 
58
- format = (index == 0 ? "" : "\t") + "%-#{self.max_col_size}.#{self.max_col_size}s%-#{self.max_type_size}.#{self.max_type_size}s`%s`\n"
59
54
  struct_info[:col_names] << col.name unless col.name == "id"
60
- struct_info[:struct_body] << sprintf(format, col.name.camelize, type, tags.join(" "))
55
+ struct_info[:struct_body] << sprintf("%s %s `%s`\n", col.name.camelize, type, tags.join(" "))
61
56
  end
62
57
 
63
58
  assoc = get_associations
@@ -67,25 +62,12 @@ module GoOnRails
67
62
  return struct_info
68
63
  end
69
64
 
70
- def get_max_col_size
71
- col_name_max_size = self.klass.column_names.collect{|name| name.size}.max || 0
72
- assoc_max_size = self.klass.reflect_on_all_associations.collect{|assoc| assoc.name.to_s.size}.max || 0
73
- type_max_size = TYPE_MAP.collect{|key, value| key.size}.max || 0
74
- [col_name_max_size + 1, assoc_max_size, type_max_size].max
75
- end
76
-
77
- def get_max_type_size
78
- assoc_max_size = self.klass.reflect_on_all_associations.collect{|assoc| assoc.name.to_s.size + 2}.max || 0
79
- type_max_size = TYPE_MAP.collect{|key, value| key.size}.max || 0
80
- [assoc_max_size, type_max_size].max
81
- end
82
-
83
65
  def get_struct_name
84
66
  self.klass.table_name.camelize
85
67
  end
86
68
 
87
69
  def get_associations
88
- builder = GoOnRails::Association.new(self.klass, self.models, self.max_col_size, self.max_type_size)
70
+ builder = GoOnRails::Association.new(self.klass, self.models)
89
71
  builder.get_schema_info
90
72
  end
91
73
 
@@ -1,4 +1,4 @@
1
- package model
1
+ package models
2
2
 
3
3
  import (
4
4
  "log"
@@ -2,11 +2,11 @@
2
2
  <%- model_name_underscore = @model_name.underscore -%>
3
3
  <%- col_names = @struct_info[:col_names] -%>
4
4
  <%- has_assoc = !@struct_info[:assoc_info][:has_many].empty? || !@struct_info[:assoc_info][:has_one].empty? -%>
5
- // The file is generated by go-on-rails, a Rails generator gem:
5
+ // Package models is generated by go-on-rails, a Rails generator gem:
6
6
  // https://rubygems.org/gems/go-on-rails
7
7
  // Or on Github: https://github.com/goonr/go-on-rails
8
8
  // By B1nj0y <idegorepl@gmail.com>
9
- package model
9
+ package models
10
10
 
11
11
  import (
12
12
  "errors"
@@ -29,59 +29,59 @@ func Find<%= @model_name %>(id int64) (*<%= @model_name %>, error) {
29
29
  if id == 0 {
30
30
  return nil, errors.New("Invalid id: it can't be zero")
31
31
  }
32
- var_<%= model_name_underscore %> := <%= @model_name %>{}
33
- err := db.Get(&var_<%= model_name_underscore %>, db.Rebind(`SELECT * FROM <%= table_name %> WHERE id = ? LIMIT 1`), id)
32
+ _<%= model_name_underscore %> := <%= @model_name %>{}
33
+ err := db.Get(&_<%= model_name_underscore %>, db.Rebind(`SELECT * FROM <%= table_name %> WHERE id = ? LIMIT 1`), id)
34
34
  if err != nil {
35
35
  log.Printf("Error: %v\n", err)
36
36
  return nil, err
37
37
  }
38
- return &var_<%= model_name_underscore %>, nil
38
+ return &_<%= model_name_underscore %>, nil
39
39
  }
40
40
 
41
41
  // First<%= @model_name %> find the first one <%= model_name_underscore %> by id ASC order
42
42
  func First<%= @model_name %>() (*<%= @model_name %>, error) {
43
- var_<%= model_name_underscore %> := <%= @model_name %>{}
44
- err := db.Get(&var_<%= model_name_underscore %>, db.Rebind(`SELECT * FROM <%= table_name %> ORDER BY id ASC LIMIT 1`))
43
+ _<%= model_name_underscore %> := <%= @model_name %>{}
44
+ err := db.Get(&_<%= model_name_underscore %>, db.Rebind(`SELECT * FROM <%= table_name %> ORDER BY id ASC LIMIT 1`))
45
45
  if err != nil {
46
46
  log.Printf("Error: %v\n", err)
47
47
  return nil, err
48
48
  }
49
- return &var_<%= model_name_underscore %>, nil
49
+ return &_<%= model_name_underscore %>, nil
50
50
  }
51
51
 
52
52
  // First<%= @model_name.pluralize %> find the first N <%= model_name_underscore.pluralize %> by id ASC order
53
53
  func First<%= @model_name.pluralize %>(n uint32) ([]<%= @model_name %>, error) {
54
- var_<%= param_name_plural %> := []<%= @model_name %>{}
54
+ _<%= param_name_plural %> := []<%= @model_name %>{}
55
55
  sql := fmt.Sprintf("SELECT * FROM <%= table_name %> ORDER BY id ASC LIMIT %v", n)
56
- err := db.Select(&var_<%= param_name_plural %>, db.Rebind(sql))
56
+ err := db.Select(&_<%= param_name_plural %>, db.Rebind(sql))
57
57
  if err != nil {
58
58
  log.Printf("Error: %v\n", err)
59
59
  return nil, err
60
60
  }
61
- return var_<%= param_name_plural %>, nil
61
+ return _<%= param_name_plural %>, nil
62
62
  }
63
63
 
64
64
  // Last<%= @model_name %> find the last one <%= model_name_underscore %> by id DESC order
65
65
  func Last<%= @model_name %>() (*<%= @model_name %>, error) {
66
- var_<%= model_name_underscore %> := <%= @model_name %>{}
67
- err := db.Get(&var_<%= model_name_underscore %>, db.Rebind(`SELECT * FROM <%= table_name %> ORDER BY id DESC LIMIT 1`))
66
+ _<%= model_name_underscore %> := <%= @model_name %>{}
67
+ err := db.Get(&_<%= model_name_underscore %>, db.Rebind(`SELECT * FROM <%= table_name %> ORDER BY id DESC LIMIT 1`))
68
68
  if err != nil {
69
69
  log.Printf("Error: %v\n", err)
70
70
  return nil, err
71
71
  }
72
- return &var_<%= model_name_underscore %>, nil
72
+ return &_<%= model_name_underscore %>, nil
73
73
  }
74
74
 
75
75
  // Last<%= @model_name.pluralize %> find the last N <%= model_name_underscore.pluralize %> by id DESC order
76
76
  func Last<%= @model_name.pluralize %>(n uint32) ([]<%= @model_name %>, error) {
77
- var_<%= param_name_plural %> := []<%= @model_name %>{}
77
+ _<%= param_name_plural %> := []<%= @model_name %>{}
78
78
  sql := fmt.Sprintf("SELECT * FROM <%= table_name %> ORDER BY id DESC LIMIT %v", n)
79
- err := db.Select(&var_<%= param_name_plural %>, db.Rebind(sql))
79
+ err := db.Select(&_<%= param_name_plural %>, db.Rebind(sql))
80
80
  if err != nil {
81
81
  log.Printf("Error: %v\n", err)
82
82
  return nil, err
83
83
  }
84
- return var_<%= param_name_plural %>, nil
84
+ return _<%= param_name_plural %>, nil
85
85
  }
86
86
 
87
87
  // Find<%= @model_name.pluralize %> find one or more <%= model_name_underscore.pluralize %> by one or more ids
@@ -91,44 +91,44 @@ func Find<%= @model_name.pluralize %>(ids ...int64) ([]<%= @model_name %>, error
91
91
  log.Println(msg)
92
92
  return nil, errors.New(msg)
93
93
  }
94
- var_<%= param_name_plural %> := []<%= @model_name %>{}
94
+ _<%= param_name_plural %> := []<%= @model_name %>{}
95
95
  idsHolder := strings.Repeat(",?", len(ids)-1)
96
96
  sql := db.Rebind(fmt.Sprintf(`SELECT * FROM <%= table_name %> WHERE id IN (?%s)`, idsHolder))
97
97
  idsT := []interface{}{}
98
98
  for _,id := range ids {
99
99
  idsT = append(idsT, interface{}(id))
100
100
  }
101
- err := db.Select(&var_<%= param_name_plural %>, sql, idsT...)
101
+ err := db.Select(&_<%= param_name_plural %>, sql, idsT...)
102
102
  if err != nil {
103
103
  log.Printf("Error: %v\n", err)
104
104
  return nil, err
105
105
  }
106
- return var_<%= param_name_plural %>, nil
106
+ return _<%= param_name_plural %>, nil
107
107
  }
108
108
 
109
109
  // Find<%= @model_name %>By find a single <%= model_name_underscore %> by a field name and a value
110
110
  func Find<%= @model_name %>By(field string, val interface{}) (*<%= @model_name %>, error) {
111
- var_<%= model_name_underscore %> := <%= @model_name %>{}
111
+ _<%= model_name_underscore %> := <%= @model_name %>{}
112
112
  sqlFmt := `SELECT * FROM <%= table_name %> WHERE %s = ? LIMIT 1`
113
113
  sqlStr := fmt.Sprintf(sqlFmt, field)
114
- err := db.Get(&var_<%= model_name_underscore %>, db.Rebind(sqlStr), val)
114
+ err := db.Get(&_<%= model_name_underscore %>, db.Rebind(sqlStr), val)
115
115
  if err != nil {
116
116
  log.Printf("Error: %v\n", err)
117
117
  return nil, err
118
118
  }
119
- return &var_<%= model_name_underscore %>, nil
119
+ return &_<%= model_name_underscore %>, nil
120
120
  }
121
121
 
122
122
  // Find<%= @model_name.pluralize %>By find all <%= param_name_plural %> by a field name and a value
123
- func Find<%= @model_name.pluralize %>By(field string, val interface{}) (var_<%= param_name_plural %> []<%= @model_name %>, err error) {
123
+ func Find<%= @model_name.pluralize %>By(field string, val interface{}) (_<%= param_name_plural %> []<%= @model_name %>, err error) {
124
124
  sqlFmt := `SELECT * FROM <%= table_name %> WHERE %s = ?`
125
125
  sqlStr := fmt.Sprintf(sqlFmt, field)
126
- err = db.Select(&var_<%= param_name_plural %>, db.Rebind(sqlStr), val)
126
+ err = db.Select(&_<%= param_name_plural %>, db.Rebind(sqlStr), val)
127
127
  if err != nil {
128
128
  log.Printf("Error: %v\n", err)
129
129
  return nil, err
130
130
  }
131
- return var_<%= param_name_plural %>, nil
131
+ return _<%= param_name_plural %>, nil
132
132
  }
133
133
 
134
134
  // All<%= @model_name.pluralize %> get all the <%= @model_name %> records
@@ -171,21 +171,21 @@ func <%= @model_name %>CountWhere(where string, args ...interface{}) (c int64, e
171
171
  }
172
172
 
173
173
  // <%= @model_name %>IncludesWhere get the <%= @model_name %> associated models records, it's just the eager_load function
174
- func <%= @model_name %>IncludesWhere(assocs []string, sql string, args ...interface{}) (var_<%= param_name_plural %> []<%= @model_name %>, err error) {
175
- var_<%= param_name_plural %>, err = Find<%= @model_name.pluralize %>Where(sql, args...)
174
+ func <%= @model_name %>IncludesWhere(assocs []string, sql string, args ...interface{}) (_<%= param_name_plural %> []<%= @model_name %>, err error) {
175
+ _<%= param_name_plural %>, err = Find<%= @model_name.pluralize %>Where(sql, args...)
176
176
  if err != nil {
177
177
  log.Println(err)
178
178
  return nil, err
179
179
  }
180
180
  if len(assocs) == 0 {
181
181
  log.Println("No associated fields ard specified")
182
- return var_<%= param_name_plural %>, err
182
+ return _<%= param_name_plural %>, err
183
183
  }
184
- if len(var_<%= param_name_plural %>) <= 0 {
184
+ if len(_<%= param_name_plural %>) <= 0 {
185
185
  return nil, errors.New("No results available")
186
186
  }
187
- ids := make([]interface{}, len(var_<%= param_name_plural %>))
188
- for _, v := range var_<%= param_name_plural %> {
187
+ ids := make([]interface{}, len(_<%= param_name_plural %>))
188
+ for _, v := range _<%= param_name_plural %> {
189
189
  ids = append(ids, interface{}(v.Id))
190
190
  }
191
191
  <%- if has_assoc -%>
@@ -196,15 +196,15 @@ func <%= @model_name %>IncludesWhere(assocs []string, sql string, args ...interf
196
196
  <%- has_many = @struct_info[:assoc_info][:has_many] -%>
197
197
  <%- has_many.each do |k, v| -%>
198
198
  case "<%= k.underscore.pluralize %>":
199
- <%- if v[:through] -%>
199
+ <%- if v[:through] || v[:as] -%>
200
200
  // FIXME: optimize the query
201
- for i, vvv := range var_<%= param_name_plural %> {
202
- var_<%= v[:class_name].underscore.pluralize %>, err := <%= @model_name %>Get<%= v[:class_name].pluralize %>(vvv.Id)
201
+ for i, vvv := range _<%= param_name_plural %> {
202
+ _<%= v[:class_name].underscore.pluralize %>, err := <%= @model_name %>Get<%= v[:class_name].pluralize %>(vvv.Id)
203
203
  if err != nil {
204
204
  continue
205
205
  }
206
- vvv.<%= k %> = var_<%= v[:class_name].underscore.pluralize %>
207
- var_<%= param_name_plural %>[i] = vvv
206
+ vvv.<%= k %> = _<%= v[:class_name].underscore.pluralize %>
207
+ _<%= param_name_plural %>[i] = vvv
208
208
  }
209
209
  <%- else -%>
210
210
  <%- if v[:foreign_key] -%>
@@ -212,13 +212,13 @@ func <%= @model_name %>IncludesWhere(assocs []string, sql string, args ...interf
212
212
  <%- else -%>
213
213
  where := fmt.Sprintf("<%= model_name_underscore %>_id IN (?%s)", idsHolder)
214
214
  <%- end -%>
215
- var_<%= v[:class_name].underscore.pluralize %>, err := Find<%= v[:class_name].pluralize %>Where(where, ids...)
215
+ _<%= v[:class_name].underscore.pluralize %>, err := Find<%= v[:class_name].pluralize %>Where(where, ids...)
216
216
  if err != nil {
217
217
  log.Printf("Error when query associated objects: %v\n", assoc)
218
218
  continue
219
219
  }
220
- for _, vv := range var_<%= v[:class_name].underscore.pluralize %> {
221
- for i, vvv := range var_<%= param_name_plural %> {
220
+ for _, vv := range _<%= v[:class_name].underscore.pluralize %> {
221
+ for i, vvv := range _<%= param_name_plural %> {
222
222
  <%- if v[:foreign_key] -%>
223
223
  if vv.<%= v[:foreign_key].camelize %> == vvv.Id {
224
224
  vvv.<%= k %> = append(vvv.<%= k %>, vv)
@@ -228,7 +228,7 @@ func <%= @model_name %>IncludesWhere(assocs []string, sql string, args ...interf
228
228
  vvv.<%= k %> = append(vvv.<%= k %>, vv)
229
229
  }
230
230
  <%- end -%>
231
- var_<%= param_name_plural %>[i].<%= k %> = vvv.<%= k %>
231
+ _<%= param_name_plural %>[i].<%= k %> = vvv.<%= k %>
232
232
  }
233
233
  }
234
234
  <%- end -%>
@@ -243,13 +243,13 @@ func <%= @model_name %>IncludesWhere(assocs []string, sql string, args ...interf
243
243
  <%- else -%>
244
244
  where := fmt.Sprintf("<%= model_name_underscore %>_id IN (?%s)", idsHolder)
245
245
  <%- end -%>
246
- var_<%= v[:class_name].underscore.pluralize %>, err := Find<%= v[:class_name].pluralize %>Where(where, ids...)
246
+ _<%= v[:class_name].underscore.pluralize %>, err := Find<%= v[:class_name].pluralize %>Where(where, ids...)
247
247
  if err != nil {
248
248
  log.Printf("Error when query associated objects: %v\n", assoc)
249
249
  continue
250
250
  }
251
- for _, vv := range var_<%= v[:class_name].underscore.pluralize %> {
252
- for i, vvv := range var_<%= param_name_plural %> {
251
+ for _, vv := range _<%= v[:class_name].underscore.pluralize %> {
252
+ for i, vvv := range _<%= param_name_plural %> {
253
253
  <%- if v[:foreign_key] -%>
254
254
  if vv.<%= v[:foreign_key].camelize %> == vvv.Id {
255
255
  vvv.<%= k %> = vv
@@ -259,7 +259,7 @@ func <%= @model_name %>IncludesWhere(assocs []string, sql string, args ...interf
259
259
  vvv.<%= k %> = vv
260
260
  }
261
261
  <%- end -%>
262
- var_<%= param_name_plural %>[i].<%= k %> = vvv.<%= k %>
262
+ _<%= param_name_plural %>[i].<%= k %> = vvv.<%= k %>
263
263
  }
264
264
  }
265
265
  <%- end -%>
@@ -267,7 +267,7 @@ func <%= @model_name %>IncludesWhere(assocs []string, sql string, args ...interf
267
267
  }
268
268
  }
269
269
  <%- end -%>
270
- return var_<%= param_name_plural %>, nil
270
+ return _<%= param_name_plural %>, nil
271
271
  }
272
272
 
273
273
  // <%= @model_name %>Ids get all the Ids of <%= @model_name %> records
@@ -280,7 +280,7 @@ func <%= @model_name %>Ids() (ids []int64, err error) {
280
280
  return ids, nil
281
281
  }
282
282
 
283
- // <%= @model_name %>Ids get all the Ids of <%= @model_name %> records by where restriction
283
+ // <%= @model_name %>IdsWhere get all the Ids of <%= @model_name %> records by where restriction
284
284
  func <%= @model_name %>IdsWhere(where string, args ...interface{}) ([]int64, error) {
285
285
  ids, err := <%= @model_name %>IntCol("id", where, args...)
286
286
  return ids, err
@@ -345,10 +345,10 @@ func Find<%= @model_name.pluralize %>Where(where string, args ...interface{}) (<
345
345
  return <%= param_name_plural %>, nil
346
346
  }
347
347
 
348
- // Find<%= @model_name.pluralize %>BySql query use a complete SQL clause
349
- // with placeholders, eg: FindUsersBySql("SELECT * FROM users WHERE first_name = ? AND age > ?", "John", 18)
348
+ // Find<%= @model_name.pluralize %>BySQL query use a complete SQL clause
349
+ // with placeholders, eg: FindUsersBySQL("SELECT * FROM users WHERE first_name = ? AND age > ?", "John", 18)
350
350
  // will return those records in the table "users" whose first_name is "John" and age elder than 18
351
- func Find<%= @model_name.pluralize %>BySql(sql string, args ...interface{}) (<%= param_name_plural %> []<%= @model_name %>, err error) {
351
+ func Find<%= @model_name.pluralize %>BySQL(sql string, args ...interface{}) (<%= param_name_plural %> []<%= @model_name %>, err error) {
352
352
  stmt, err := db.Preparex(db.Rebind(sql))
353
353
  if err != nil {
354
354
  log.Println(err)
@@ -395,8 +395,8 @@ func Create<%= @model_name %>(am map[string]interface{}) (int64, error) {
395
395
  return lastId, nil
396
396
  }
397
397
 
398
- func (var_<%= model_name_underscore %> *<%= @model_name %>) Create() (int64, error) {
399
- ok, err := govalidator.ValidateStruct(var_<%= model_name_underscore %>)
398
+ func (_<%= model_name_underscore %> *<%= @model_name %>) Create() (int64, error) {
399
+ ok, err := govalidator.ValidateStruct(_<%= model_name_underscore %>)
400
400
  if !ok {
401
401
  errMsg := "Validate <%= @model_name %> struct error: Unknown error"
402
402
  if err != nil {
@@ -408,11 +408,11 @@ func (var_<%= model_name_underscore %> *<%= @model_name %>) Create() (int64, err
408
408
  <%- unless @struct_info[:timestamp_cols].empty? -%>
409
409
  t := time.Now()
410
410
  <%- @struct_info[:timestamp_cols].each do |c| -%>
411
- var_<%= model_name_underscore %>.<%= c.camelize %> = t
411
+ _<%= model_name_underscore %>.<%= c.camelize %> = t
412
412
  <%- end -%>
413
413
  <%- end -%>
414
414
  sql := `INSERT INTO <%= table_name %> (<%= col_names.join(",") %>) VALUES (:<%= col_names.join(",:") %>)`
415
- result, err := db.NamedExec(sql, var_<%= model_name_underscore %>)
415
+ result, err := db.NamedExec(sql, _<%= model_name_underscore %>)
416
416
  if err != nil {
417
417
  log.Println(err)
418
418
  return 0, err
@@ -428,48 +428,62 @@ func (var_<%= model_name_underscore %> *<%= @model_name %>) Create() (int64, err
428
428
  <%- unless @struct_info[:assoc_info][:has_many].empty? -%>
429
429
  <%- has_many = @struct_info[:assoc_info][:has_many] -%>
430
430
  <%- has_many.each do |k, v| -%>
431
- func (var_<%= model_name_underscore %> *<%= @model_name %>) <%= v[:class_name].pluralize %>Create(am map[string]interface{}) error {
431
+ // <%= v[:class_name].pluralize %>Create used to create the associated objects
432
+ func (_<%= model_name_underscore %> *<%= @model_name %>) <%= v[:class_name].pluralize %>Create(am map[string]interface{}) error {
432
433
  <%- if v[:through] -%>
433
434
  // FIXME: use transaction to create these associated objects
434
- <%= v[:class_name].underscore %>_id, err := Create<%= v[:class_name] %>(am)
435
+ <%= v[:class_name].underscore %>Id, err := Create<%= v[:class_name] %>(am)
435
436
  if err != nil {
436
437
  return err
437
438
  }
438
- _, err = Create<%= v[:through].to_s.singularize.camelize %>(map[string]interface{}{"<%= model_name_underscore %>_id": var_<%= model_name_underscore %>.Id, "<%= v[:class_name].underscore %>_id": <%= v[:class_name].underscore %>_id})
439
+ _, err = Create<%= v[:through].to_s.singularize.camelize %>(map[string]interface{}{"<%= model_name_underscore %>_id": _<%= model_name_underscore %>.Id, "<%= v[:class_name].underscore %>_id": <%= v[:class_name].underscore %>Id})
440
+ <%- elsif v[:as] -%>
441
+ am["<%= v[:as] %>_id"] = _<%= model_name_underscore %>.Id
442
+ am["<%= v[:as] %>_type"] = "<%= @model_name %>"
443
+ _, err := Create<%= v[:class_name] %>(am)
439
444
  <%- else -%>
440
445
  <%- if v[:foreign_key] -%>
441
- am["<%= v[:foreign_key] %>"] = var_<%= model_name_underscore %>.Id
446
+ am["<%= v[:foreign_key] %>"] = _<%= model_name_underscore %>.Id
442
447
  <%- else -%>
443
- am["<%= model_name_underscore %>_id"] = var_<%= model_name_underscore %>.Id
448
+ am["<%= model_name_underscore %>_id"] = _<%= model_name_underscore %>.Id
444
449
  <%- end -%>
445
450
  _, err := Create<%= v[:class_name] %>(am)
446
451
  <%- end -%>
447
452
  return err
448
453
  }
449
454
 
450
- func (var_<%= model_name_underscore %> *<%= @model_name %>) Get<%= v[:class_name].pluralize %>() error {
451
- var_<%= v[:class_name].underscore.pluralize %>, err := <%= @model_name %>Get<%= v[:class_name].pluralize %>(var_<%= model_name_underscore %>.Id)
455
+ // Get<%= v[:class_name].pluralize %> used to get associated objects
456
+ func (_<%= model_name_underscore %> *<%= @model_name %>) Get<%= v[:class_name].pluralize %>() error {
457
+ _<%= v[:class_name].underscore.pluralize %>, err := <%= @model_name %>Get<%= v[:class_name].pluralize %>(_<%= model_name_underscore %>.Id)
452
458
  if err == nil {
453
- var_<%= model_name_underscore %>.<%= k %> = var_<%= v[:class_name].underscore.pluralize %>
459
+ _<%= model_name_underscore %>.<%= k %> = _<%= v[:class_name].underscore.pluralize %>
454
460
  }
455
461
  return err
456
462
  }
457
463
 
464
+ // <%= @model_name %>Get<%= v[:class_name].pluralize %> a helper fuction used to get associated objects for <%= @model_name %>IncludesWhere()
458
465
  func <%= @model_name %>Get<%= v[:class_name].pluralize %>(id int64) ([]<%= v[:class_name] %>, error) {
459
466
  <%- if v[:through] -%>
460
467
  // FIXME: use transaction to create these associated objects
461
468
  <%- target_table = v[:class_name].underscore.pluralize -%>
462
469
  <%- through_table = v[:through].to_s.pluralize -%>
463
- sql := "SELECT `<%= target_table %>`.* FROM `<%= target_table %>` INNER JOIN `<%= through_table %>` ON `<%= target_table %>`.`id` = `<%= through_table %>`.`<%= v[:class_name].underscore %>_id` WHERE `<%= through_table %>`.`<%= model_name_underscore %>_id` = ?"
464
- var_<%= v[:class_name].underscore.pluralize %>, err := Find<%= v[:class_name].pluralize %>BySql(sql, id)
470
+ sql := `SELECT <%= target_table %>.*
471
+ FROM <%= target_table %>
472
+ INNER JOIN <%= through_table %>
473
+ ON <%= target_table %>.id = <%= through_table %>.<%= v[:class_name].underscore %>_id
474
+ WHERE <%= through_table %>.<%= model_name_underscore %>_id = ?`
475
+ _<%= v[:class_name].underscore.pluralize %>, err := Find<%= v[:class_name].pluralize %>BySQL(sql, id)
476
+ <%- elsif v[:as] -%>
477
+ where := `<%= v[:as] %>_type = "<%= @model_name %>" AND <%= v[:as] %>_id = ?`
478
+ _<%= v[:class_name].underscore.pluralize %>, err := Find<%= v[:class_name].pluralize %>Where(where, id)
465
479
  <%- else -%>
466
480
  <%- if v[:foreign_key] -%>
467
- var_<%= v[:class_name].underscore.pluralize %>, err := Find<%= v[:class_name].pluralize %>By("<%= v[:foreign_key] %>", id)
481
+ _<%= v[:class_name].underscore.pluralize %>, err := Find<%= v[:class_name].pluralize %>By("<%= v[:foreign_key] %>", id)
468
482
  <%- else -%>
469
- var_<%= v[:class_name].underscore.pluralize %>, err := Find<%= v[:class_name].pluralize %>By("<%= model_name_underscore %>_id", id)
483
+ _<%= v[:class_name].underscore.pluralize %>, err := Find<%= v[:class_name].pluralize %>By("<%= model_name_underscore %>_id", id)
470
484
  <%- end -%>
471
485
  <%- end -%>
472
- return var_<%= v[:class_name].underscore.pluralize %>, err
486
+ return _<%= v[:class_name].underscore.pluralize %>, err
473
487
  }
474
488
 
475
489
  <%- end -%>
@@ -478,11 +492,11 @@ func <%= @model_name %>Get<%= v[:class_name].pluralize %>(id int64) ([]<%= v[:cl
478
492
  <%- unless @struct_info[:assoc_info][:has_one].empty? -%>
479
493
  <%- has_one = @struct_info[:assoc_info][:has_one] -%>
480
494
  <%- has_one.each do |k, v| -%>
481
- func (var_<%= model_name_underscore %> *<%= @model_name %>) Create<%= v[:class_name] %>(am map[string]interface{}) error {
495
+ func (_<%= model_name_underscore %> *<%= @model_name %>) Create<%= v[:class_name] %>(am map[string]interface{}) error {
482
496
  <%- if v[:foreign_key] -%>
483
- am["<%= v[:foreign_key] %>"] = var_<%= model_name_underscore %>.Id
497
+ am["<%= v[:foreign_key] %>"] = _<%= model_name_underscore %>.Id
484
498
  <%- else -%>
485
- am["<%= model_name_underscore %>_id"] = var_<%= model_name_underscore %>.Id
499
+ am["<%= model_name_underscore %>_id"] = _<%= model_name_underscore %>.Id
486
500
  <%- end -%>
487
501
  _, err := Create<%= v[:class_name] %>(am)
488
502
  return err
@@ -493,11 +507,13 @@ func (var_<%= model_name_underscore %> *<%= @model_name %>) Create<%= v[:class_n
493
507
  <%- unless @struct_info[:assoc_info][:belongs_to].empty? -%>
494
508
  <%- belongs_to = @struct_info[:assoc_info][:belongs_to] -%>
495
509
  <%- belongs_to.each do |k, v| -%>
496
- func (var_<%= model_name_underscore %> *<%= @model_name %>) Create<%= v[:class_name] %>(am map[string]interface{}) error {
510
+ <%-# don't create virtual table for polymorphic model -%>
511
+ <%- next if v[:polymorphic] -%>
512
+ func (_<%= model_name_underscore %> *<%= @model_name %>) Create<%= v[:class_name] %>(am map[string]interface{}) error {
497
513
  <%- if v[:foreign_key] -%>
498
- am["<%= v[:foreign_key] %>"] = var_<%= model_name_underscore %>.Id
514
+ am["<%= v[:foreign_key] %>"] = _<%= model_name_underscore %>.Id
499
515
  <%- else -%>
500
- am["<%= model_name_underscore %>_id"] = var_<%= model_name_underscore %>.Id
516
+ am["<%= model_name_underscore %>_id"] = _<%= model_name_underscore %>.Id
501
517
  <%- end -%>
502
518
  _, err := Create<%= v[:class_name] %>(am)
503
519
  return err
@@ -505,11 +521,11 @@ func (var_<%= model_name_underscore %> *<%= @model_name %>) Create<%= v[:class_n
505
521
  <%- end -%>
506
522
  <%- end -%>
507
523
 
508
- func (var_<%= model_name_underscore %> *<%= @model_name %>) Destroy() error {
509
- if var_<%= model_name_underscore %>.Id == 0 {
524
+ func (_<%= model_name_underscore %> *<%= @model_name %>) Destroy() error {
525
+ if _<%= model_name_underscore %>.Id == 0 {
510
526
  return errors.New("Invalid Id field: it can't be a zero value")
511
527
  }
512
- err := Destroy<%= @model_name %>(var_<%= model_name_underscore %>.Id)
528
+ err := Destroy<%= @model_name %>(_<%= model_name_underscore %>.Id)
513
529
  return err
514
530
  }
515
531
 
@@ -608,23 +624,29 @@ func destroy<%= @model_name %>Associations(ids ...int64) {
608
624
  <%- case opts[:dependent] -%>
609
625
  <%- when :destroy, :delete_all -%>
610
626
  <%- if opts[:through] -%>
611
- sql := fmt.Sprintf("id IN (SELECT id FROM <%= opts[:through].to_s %> WHERE <%= model_name_underscore %>_id IN (?%s))", idsHolder)
612
- _, err = Destroy<%= opts[:class_name].pluralize %>Where(sql, idsT...)
627
+ where := fmt.Sprintf("id IN (SELECT id FROM <%= opts[:through].to_s %> WHERE <%= model_name_underscore %>_id IN (?%s))", idsHolder)
628
+ _, err = Destroy<%= opts[:class_name].pluralize %>Where(where, idsT...)
613
629
  if err != nil {
614
630
  log.Printf("Destroy associated object %s error: %v\n", "<%= opts[:class_name].pluralize %>", err)
615
631
  }
616
- sql = fmt.Sprintf("<%= model_name_underscore %>_id IN (?%s)", idsHolder)
617
- _, err = Destroy<%= opts[:through].to_s.pluralize.camelize %>Where(sql, idsT...)
632
+ where = fmt.Sprintf("<%= model_name_underscore %>_id IN (?%s)", idsHolder)
633
+ _, err = Destroy<%= opts[:through].to_s.pluralize.camelize %>Where(where, idsT...)
618
634
  if err != nil {
619
635
  log.Printf("Destroy associated object %s error: %v\n", "<%= opts[:through].to_s.singularize.camelize %>", err)
620
636
  }
637
+ <%- elsif opts[:as] -%>
638
+ where := fmt.Sprintf(`<%= opts[:as] %>_type = "<%= @model_name %>" AND <%= opts[:as] %>_id IN (?%s)`, idsHolder)
639
+ _, err = Destroy<%= opts[:class_name].pluralize %>Where(where, idsT...)
640
+ if err != nil {
641
+ log.Printf("Destroy associated object %s error: %v\n", "<%= opts[:class_name].pluralize %>", err)
642
+ }
621
643
  <%- else -%>
622
644
  <%- if opts.key? :foreign_key -%>
623
- sql := fmt.Sprintf("<%= opts[:foreign_key] %> IN (?%s)", idsHolder)
645
+ where := fmt.Sprintf("<%= opts[:foreign_key] %> IN (?%s)", idsHolder)
624
646
  <%- else -%>
625
- sql := fmt.Sprintf("<%= model_name_underscore %>_id IN (?%s)", idsHolder)
647
+ where := fmt.Sprintf("<%= model_name_underscore %>_id IN (?%s)", idsHolder)
626
648
  <%- end -%>
627
- _, err = Destroy<%= opts[:class_name].pluralize %>Where(sql, idsT...)
649
+ _, err = Destroy<%= opts[:class_name].pluralize %>Where(where, idsT...)
628
650
  if err != nil {
629
651
  log.Printf("Destroy associated object %s error: %v\n", "<%= opts[:class_name].pluralize %>", err)
630
652
  }
@@ -633,7 +655,7 @@ func destroy<%= @model_name %>Associations(ids ...int64) {
633
655
  // no sql.NULLType supported, just set the associated field to zero value of int64
634
656
  <%- if opts[:through] -%>
635
657
  sql := fmt.Sprintf("UPDATE <%= opts[:through].to_s %> SET <%= opts[:class_name].underscore %>_id = 0 WHERE <%= opts[:class_name].underscore %>_id IN (?%s)", idsHolder)
636
- _, err = Update<%= opts[:through].to_s.camelize %>BySql(sql, idsT...)
658
+ _, err = Update<%= opts[:through].to_s.camelize %>BySQL(sql, idsT...)
637
659
  if err != nil {
638
660
  log.Printf("Delete associated object %s error: %v\n", "<%= opts[:class_name].pluralize %>", err)
639
661
  }
@@ -643,7 +665,7 @@ func destroy<%= @model_name %>Associations(ids ...int64) {
643
665
  <%- else -%>
644
666
  sql := fmt.Sprintf("UPDATE <%= opts[:class_name].underscore.pluralize %> SET <%= model_name_underscore %>_id = 0 WHERE <%= model_name_underscore %>_id IN (?%s)", idsHolder)
645
667
  <%- end -%>
646
- _, err = Update<%= opts[:class_name].pluralize %>BySql(sql, idsT...)
668
+ _, err = Update<%= opts[:class_name].pluralize %>BySQL(sql, idsT...)
647
669
  if err != nil {
648
670
  log.Printf("Delete associated object %s error: %v\n", "<%= opts[:class_name].pluralize %>", err)
649
671
  }
@@ -656,8 +678,8 @@ func destroy<%= @model_name %>Associations(ids ...int64) {
656
678
  }
657
679
  <%- end -%>
658
680
 
659
- func (var_<%= model_name_underscore %> *<%= @model_name %>) Save() error {
660
- ok, err := govalidator.ValidateStruct(var_<%= model_name_underscore %>)
681
+ func (_<%= model_name_underscore %> *<%= @model_name %>) Save() error {
682
+ ok, err := govalidator.ValidateStruct(_<%= model_name_underscore %>)
661
683
  if !ok {
662
684
  errMsg := "Validate <%= @model_name %> struct error: Unknown error"
663
685
  if err != nil {
@@ -666,16 +688,16 @@ func (var_<%= model_name_underscore %> *<%= @model_name %>) Save() error {
666
688
  log.Println(errMsg)
667
689
  return errors.New(errMsg)
668
690
  }
669
- if var_<%= model_name_underscore %>.Id == 0 {
691
+ if _<%= model_name_underscore %>.Id == 0 {
670
692
  return errors.New("Invalid Id field: it can't be a zero value")
671
693
  }
672
694
  <%- if @struct_info[:timestamp_cols].include? "updated_at" -%>
673
- var_<%= model_name_underscore %>.UpdatedAt = time.Now()
695
+ _<%= model_name_underscore %>.UpdatedAt = time.Now()
674
696
  <%- end -%>
675
697
  sqlFmt := `UPDATE <%= table_name %> SET %s WHERE id = %v`
676
698
  <%- save_col_names = col_names - ["created_at"] -%>
677
- sqlStr := fmt.Sprintf(sqlFmt, "<%= save_col_names.zip(save_col_names).map{|c| c.join(" = :")}.join(", ") %>", var_<%= model_name_underscore %>.Id)
678
- _, err = db.NamedExec(sqlStr, var_<%= model_name_underscore %>)
699
+ sqlStr := fmt.Sprintf(sqlFmt, "<%= save_col_names.zip(save_col_names).map{|c| c.join(" = :")}.join(", ") %>", _<%= model_name_underscore %>.Id)
700
+ _, err = db.NamedExec(sqlStr, _<%= model_name_underscore %>)
679
701
  return err
680
702
  }
681
703
 
@@ -707,31 +729,31 @@ func Update<%= @model_name %>(id int64, am map[string]interface{}) error {
707
729
  return nil
708
730
  }
709
731
 
710
- func (var_<%= model_name_underscore %> *<%= @model_name %>) Update(am map[string]interface{}) error {
711
- if var_<%= model_name_underscore %>.Id == 0 {
732
+ func (_<%= model_name_underscore %> *<%= @model_name %>) Update(am map[string]interface{}) error {
733
+ if _<%= model_name_underscore %>.Id == 0 {
712
734
  return errors.New("Invalid Id field: it can't be a zero value")
713
735
  }
714
- err := Update<%= @model_name %>(var_<%= model_name_underscore %>.Id, am)
736
+ err := Update<%= @model_name %>(_<%= model_name_underscore %>.Id, am)
715
737
  return err
716
738
  }
717
739
 
718
- func (var_<%= model_name_underscore %> *<%= @model_name %>) UpdateAttributes(am map[string]interface{}) error {
719
- if var_<%= model_name_underscore %>.Id == 0 {
740
+ func (_<%= model_name_underscore %> *<%= @model_name %>) UpdateAttributes(am map[string]interface{}) error {
741
+ if _<%= model_name_underscore %>.Id == 0 {
720
742
  return errors.New("Invalid Id field: it can't be a zero value")
721
743
  }
722
- err := Update<%= @model_name %>(var_<%= model_name_underscore %>.Id, am)
744
+ err := Update<%= @model_name %>(_<%= model_name_underscore %>.Id, am)
723
745
  return err
724
746
  }
725
747
 
726
- func (var_<%= model_name_underscore %> *<%= @model_name %>) UpdateColumns(am map[string]interface{}) error {
727
- if var_<%= model_name_underscore %>.Id == 0 {
748
+ func (_<%= model_name_underscore %> *<%= @model_name %>) UpdateColumns(am map[string]interface{}) error {
749
+ if _<%= model_name_underscore %>.Id == 0 {
728
750
  return errors.New("Invalid Id field: it can't be a zero value")
729
751
  }
730
- err := Update<%= @model_name %>(var_<%= model_name_underscore %>.Id, am)
752
+ err := Update<%= @model_name %>(_<%= model_name_underscore %>.Id, am)
731
753
  return err
732
754
  }
733
755
 
734
- func Update<%= @model_name.pluralize %>BySql(sql string, args ...interface{}) (int64, error) {
756
+ func Update<%= @model_name.pluralize %>BySQL(sql string, args ...interface{}) (int64, error) {
735
757
  if sql == "" {
736
758
  return 0, errors.New("A blank SQL clause")
737
759
  }
data/lib/tasks/gor.rake CHANGED
@@ -11,4 +11,9 @@ namespace :gor do
11
11
  github.com/asaskevich/govalidator"
12
12
  puts 'Installation completed!'
13
13
  end
14
+
15
+ task :fmt do
16
+ go_files = Rails.root.join('go_app', 'models/*.go').to_s
17
+ system "gofmt -w #{go_files} > /dev/null 2>&1"
18
+ end
14
19
  end
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.0
4
+ version: 0.1.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - B1nj0y
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2017-05-21 00:00:00.000000000 Z
11
+ date: 2017-06-02 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