Skip to content

Commit

Permalink
SQLX changed MustExec to Exec and checking/returning error
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex Jeannopoulos committed Jun 14, 2020
1 parent 5575fc1 commit e16a98e
Show file tree
Hide file tree
Showing 13 changed files with 169 additions and 83 deletions.
10 changes: 7 additions & 3 deletions README.md

Large diffs are not rendered by default.

19 changes: 15 additions & 4 deletions code_dao_sqlx.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,17 @@ func addInvoices(ctx context.Context, record *model.Invoices) (result *model.Inv

rows := int64(0)

dbResult := DB.MustExecContext(ctx, sql, record.CustomerID, record.InvoiceDate, record.BillingAddress, record.BillingCity, record.BillingState, record.BillingCountry, record.BillingPostalCode, record.Total,)
dbResult, err := DB.ExecContext(ctx, sql, record.CustomerID, record.InvoiceDate, record.BillingAddress, record.BillingCity, record.BillingState, record.BillingCountry, record.BillingPostalCode, record.Total,)
if err != nil {
return nil, 0, err
}

id, err := dbResult.LastInsertId()
rows, err = dbResult.RowsAffected()

record.InvoiceID = int32(id)



return record, rows, err
}

Expand All @@ -148,7 +151,11 @@ func UpdateInvoices(ctx context.Context, argInvoiceID int32, updated *m
Logger(ctx, sql)
}

dbResult := DB.MustExecContext(ctx, sql, updated.CustomerID, updated.InvoiceDate, updated.BillingAddress, updated.BillingCity, updated.BillingState, updated.BillingCountry, updated.BillingPostalCode, updated.Total, argInvoiceID, )
dbResult, err := DB.ExecContext(ctx, sql, updated.CustomerID, updated.InvoiceDate, updated.BillingAddress, updated.BillingCity, updated.BillingState, updated.BillingCountry, updated.BillingPostalCode, updated.Total, argInvoiceID, )
if err != nil {
return nil, 0, err
}

rows, err := dbResult.RowsAffected()
updated.InvoiceID = argInvoiceID

Expand All @@ -171,7 +178,11 @@ func DeleteInvoices(ctx context.Context, argInvoiceID int32, ) (rowsAffe
Logger(ctx, sql)
}

result := DB.MustExecContext(ctx, sql, argInvoiceID, )
result, err := DB.ExecContext(ctx, sql, argInvoiceID, )
if err != nil {
return 0, err
}

return result.RowsAffected()
}

Expand Down
4 changes: 2 additions & 2 deletions code_http.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ func GetInvoices(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /invoices [post]
// echo '{"invoice_id": 27,"customer_id": 30,"billing_postal_code": "asOObOtANjAOmJFmldMAxIgVR","total": 0.34503829706689715,"invoice_date": "2136-03-04T03:20:48.298550833-05:00","billing_address": "COALgwkygQbTtrEQuiEnGZGib","billing_city": "BotWQEnhCnqIjxjpPkpXdOusm","billing_state": "IeZYXZICGPuLTLvTcWusQxpZI","billing_country": "ibsBkxCkKnthtqMXOAIsgEIno"}' | http POST "http://127.0.0.1:8080/invoices"
// echo '{"billing_city": "KFexcWKROnLINETrbmVOvTkcR","billing_state": "vhcqlIruTvNNVLldzziowZnTi","billing_country": "LFUPxhKvYOUNjkTxIuyHFhqpu","invoice_id": 22,"invoice_date": "2232-05-19T13:23:42.984104667-05:00","billing_postal_code": "ruCpAHdOcxexpzANxveifgEjs","total": 0.09440238810354037,"customer_id": 51,"billing_address": "aUXNwnUvmZIqZXIxeAEndiuXN"}' | http POST "http://127.0.0.1:8080/invoices"
func AddInvoices(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
invoices := &model.Invoices{}

Expand Down Expand Up @@ -175,7 +175,7 @@ func AddInvoices(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /invoices/{argInvoiceID} [patch]
// echo '{"invoice_id": 27,"customer_id": 30,"billing_postal_code": "asOObOtANjAOmJFmldMAxIgVR","total": 0.34503829706689715,"invoice_date": "2136-03-04T03:20:48.298550833-05:00","billing_address": "COALgwkygQbTtrEQuiEnGZGib","billing_city": "BotWQEnhCnqIjxjpPkpXdOusm","billing_state": "IeZYXZICGPuLTLvTcWusQxpZI","billing_country": "ibsBkxCkKnthtqMXOAIsgEIno"}' | http PUT "http://127.0.0.1:8080/invoices/1"
// echo '{"billing_city": "KFexcWKROnLINETrbmVOvTkcR","billing_state": "vhcqlIruTvNNVLldzziowZnTi","billing_country": "LFUPxhKvYOUNjkTxIuyHFhqpu","invoice_id": 22,"invoice_date": "2232-05-19T13:23:42.984104667-05:00","billing_postal_code": "ruCpAHdOcxexpzANxveifgEjs","total": 0.09440238810354037,"customer_id": 51,"billing_address": "aUXNwnUvmZIqZXIxeAEndiuXN"}' | http PUT "http://127.0.0.1:8080/invoices/1"
func UpdateInvoices(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {


Expand Down
35 changes: 35 additions & 0 deletions dbmeta/codegen.go
Original file line number Diff line number Diff line change
Expand Up @@ -583,5 +583,40 @@ func NewConfig(templateLoader TemplateLoader) *Config {
conf.ModelNamingTemplate = "{{FmtFieldName .}}"
conf.FieldNamingTemplate = "{{FmtFieldName (stringifyFirstChar .) }}"


outDir := "."
module := "github.com/alexj212/test"
modelPackageName := "model"
daoPackageName := "dao"
apiPackageName := "api"

conf.ModelPackageName = modelPackageName
conf.DaoPackageName = daoPackageName
conf.ApiPackageName = apiPackageName

conf.AddJSONAnnotation = true
conf.AddXMLAnnotation = true
conf.AddGormAnnotation = true
conf.AddProtobufAnnotation = true
conf.AddDBAnnotation = true
conf.UseGureguTypes = false
conf.JsonNameFormat = "snake"
conf.XMLNameFormat = "snake"
conf.ProtobufNameFormat = "snake"
conf.Verbose = false
conf.OutDir = outDir
conf.Overwrite = true

conf.ServerPort = 8080
conf.ServerHost = "127.0.0.1"
conf.Overwrite = true

conf.Module = module
conf.ModelFQPN = module + "/" + modelPackageName
conf.DaoFQPN = module + "/" + daoPackageName
conf.ApiFQPN = module + "/" + apiPackageName

conf.Swagger.Host = fmt.Sprintf("%s:%d", conf.ServerHost, conf.ServerPort)

return conf
}
123 changes: 61 additions & 62 deletions dbmeta/meta.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,75 +311,26 @@ func LoadMeta(sqlType string, db *sql.DB, sqlDatabase, tableName string) (DbTabl
return dbMeta, err
}

func checkDupeFieldName(fields []*FieldInfo, fieldName string) string {
var match bool
for _, field := range fields {
if fieldName == field.GoFieldName {
match = true
break
}
}

if match {
return fmt.Sprintf("%s_", fieldName)
}

return fieldName
}

func checkDupeJSONFieldName(fields []*FieldInfo, fieldName string) string {
var match bool
for _, field := range fields {
if fieldName == field.JSONFieldName {
match = true
break
}
}

if match {
return fmt.Sprintf("%s_", fieldName)
}

return fieldName
}

func checkDupeProtoBufFieldName(fields []*FieldInfo, fieldName string) string {
var match bool
for _, field := range fields {
if fieldName == field.ProtobufFieldName {
match = true
break
}
}

if match {
return fmt.Sprintf("%s_", fieldName)
}

return fieldName
}

// Generate fields string
func (c *Config) GenerateFieldsTypes(dbMeta DbTableMeta) ([]*FieldInfo, error) {

var fields []*FieldInfo
field := ""
for i, col := range dbMeta.Columns() {
name := col.Name()
fieldName := col.Name()

fi := &FieldInfo{
Index: i,
}

valueType, err := SQLTypeToGoType(strings.ToLower(col.DatabaseTypeName()), col.Nullable(), c.UseGureguTypes)
if err != nil { // unknown type
fmt.Printf("table: %s unable to generate struct field: %s type: %s error: %v\n", dbMeta.TableName(), name, col.DatabaseTypeName(), err)
fmt.Printf("table: %s unable to generate struct field: %s type: %s error: %v\n", dbMeta.TableName(), fieldName, col.DatabaseTypeName(), err)
continue
}

//fieldName := FmtFieldName(stringifyFirstChar(name))
//experiment
fieldName := Replace(c.FieldNamingTemplate, name)
fieldName = Replace(c.FieldNamingTemplate, fieldName)
fieldName = checkDupeFieldName(fields, fieldName)

fi.GormAnnotation = createGormAnnotation(col)
Expand Down Expand Up @@ -756,15 +707,8 @@ func GenerateModelInfo(tables map[string]*ModelInfo, dbMeta DbTableMeta,
tableName string,
conf *Config) (*ModelInfo, error) {

//structName := FmtFieldName(tableName)
//experiment
structName := Replace(conf.ModelNamingTemplate, tableName)
// fmt.Printf("tableName: %s structName: %s\n", tableName, structName)
// structName = inflection.Singular(structName)
structName = CheckForDupe(tables, structName)

conf.JsonNameFormat = strings.ToLower(conf.JsonNameFormat)
conf.XMLNameFormat = strings.ToLower(conf.XMLNameFormat)
structName = CheckForDupeTable(tables, structName)

fields, err := conf.GenerateFieldsTypes(dbMeta)
if err != nil {
Expand Down Expand Up @@ -826,7 +770,7 @@ func GenerateModelInfo(tables map[string]*ModelInfo, dbMeta DbTableMeta,
return modelInfo, nil
}

func CheckForDupe(tables map[string]*ModelInfo, name string) string {
func CheckForDupeTable(tables map[string]*ModelInfo, name string) string {
found := false

for _, model := range tables {
Expand All @@ -835,7 +779,7 @@ func CheckForDupe(tables map[string]*ModelInfo, name string) string {
}
}
if found {
name = CheckForDupe(tables, name+"_")
name = CheckForDupeTable(tables, name+"_")
}

if name == "Result" {
Expand All @@ -844,3 +788,58 @@ func CheckForDupe(tables map[string]*ModelInfo, name string) string {

return name
}


func checkDupeFieldName(fields []*FieldInfo, fieldName string) string {
var match bool
for _, field := range fields {
if fieldName == field.GoFieldName {
match = true
break
}
}

if match {
fieldName = checkDupeFieldName( fields, generateAlternativeName( fieldName))
}

return fieldName
}

func checkDupeJSONFieldName(fields []*FieldInfo, fieldName string) string {
var match bool
for _, field := range fields {
if fieldName == field.JSONFieldName {
match = true
break
}
}

if match {
fieldName = checkDupeJSONFieldName( fields, generateAlternativeName( fieldName))
}

return fieldName
}

func checkDupeProtoBufFieldName(fields []*FieldInfo, fieldName string) string {
var match bool
for _, field := range fields {
if fieldName == field.ProtobufFieldName {
match = true
break
}
}

if match {
fieldName = checkDupeProtoBufFieldName( fields, generateAlternativeName( fieldName))
}

return fieldName
}

// @TODO In progress - need more elegant renaming
func generateAlternativeName(name string)string {
name = name+"alt1"
return name
}
File renamed without changes.
6 changes: 5 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ func init() {

//Parse options
goopt.Parse(nil)

}

func saveTemplates() {
Expand Down Expand Up @@ -329,6 +328,7 @@ func initialize(conf *dbmeta.Config) {
conf.AddDBAnnotation = *AddDBAnnotation
conf.UseGureguTypes = *UseGureguTypes
conf.JsonNameFormat = *jsonNameFormat
conf.XMLNameFormat = *xmlNameFormat
conf.ProtobufNameFormat = *protoNameFormat
conf.Verbose = *verbose
conf.OutDir = *outDir
Expand Down Expand Up @@ -365,6 +365,10 @@ func initialize(conf *dbmeta.Config) {
conf.Swagger.ContactURL = *swaggerContactURL
conf.Swagger.ContactEmail = *swaggerContactEmail
conf.Swagger.Host = fmt.Sprintf("%s:%d", *serverHost, *serverPort)

conf.JsonNameFormat = strings.ToLower(conf.JsonNameFormat)
conf.XMLNameFormat = strings.ToLower(conf.XMLNameFormat)
conf.ProtobufNameFormat = strings.ToLower(conf.ProtobufNameFormat)
}

func loadDefaultDBMappings(conf *dbmeta.Config) error {
Expand Down
Loading

0 comments on commit e16a98e

Please sign in to comment.