細(xì)數(shù)在用golang&beego做api server過程中的坑(二)

在介紹之前先說明一下,標(biāo)題中帶有【beego】標(biāo)簽的,是beego框架使用中遇到的坑。如果沒有,那就是golang本身的坑。當(dāng)然,此坑并非人家代碼有問題,有幾個(gè)地方反而是出于性能等各方面的考量有意而為之。但這些地方卻是一門語言或框架的初學(xué)者大概率會(huì)遇到的困惑。
傳送門:細(xì)數(shù)在用golang&beego做api server過程中的坑(一)

【beego】4、orm查詢時(shí)沒有對應(yīng)結(jié)果集: now row found (error)

java程序員對于持久層框架可能都用過mybatis,對查詢操作也會(huì)比較熟悉。當(dāng)一行代碼下去,數(shù)據(jù)庫給你咔咔一頓找,發(fā)現(xiàn)沒有結(jié)果時(shí),會(huì)返回null 或 一個(gè)空的collection。beego中也有持久層框架,就叫orm。對于查詢方面的處理,如果數(shù)據(jù)庫查詢后沒有找到任何結(jié)果,orm不會(huì)返回空,而是會(huì)返回一個(gè)error??!
舉例:

var container po.OnlineAccumulateRecord
    err = o.QueryTable(new(po.OnlineAccumulateRecord)).Filter("User", user.Id).One(&container)
    if err != nil && !models.IsNoRowFoundError(err) {
        return 0, err
    }

這段代碼是我從現(xiàn)有工程里面隨便摘出來的,大意就是通過用戶id篩選出積分表里的一條記錄。這個(gè)時(shí)候如果查不到對應(yīng)的記錄,err != nil 便會(huì)成立。這時(shí)候單純的通過 err !=nil就無法判斷到底是真的出現(xiàn)數(shù)據(jù)庫查詢錯(cuò)誤,還是沒有找到對應(yīng)記錄。因此就有了models.IsNoRowFoundError(err)這一判斷。 對于是否是NoRowFoundError,可行的方法之一是判斷err是否相等:

if err == orm.ErrNoRows {
}

之二是判斷error message:

//判斷一個(gè)錯(cuò)誤是不是因?yàn)閿?shù)據(jù)庫中沒有符合條件的記錄,而拋出的錯(cuò)誤。
//這種情況是一種正常的情況,不應(yīng)該作為錯(cuò)誤拋出
func IsNoRowFoundError(err error) bool {
    if err == nil {
        return false
    }

    if strings.Contains(err.Error(), "no row found") {
        return true
    }
    return false
}

當(dāng)然對于其他的查詢方式,也會(huì)有這個(gè)問題,例如:

o := orm.NewOrm()
err = o.Read(&orderInfo, "OuterOrderId")

在此就不一一列舉。
我個(gè)人認(rèn)為astaxie大神在設(shè)計(jì)beego orm時(shí)不可能沒考慮到這一點(diǎn)。之所以這樣設(shè)計(jì),可能的一個(gè)原因是,對于剛才的查詢代碼:

var container po.OnlineAccumulateRecord
 err = o.QueryTable(new(po.OnlineAccumulateRecord)).Filter("User", user.Id).One(&container)

不能夠通過判斷container是不是nil來斷定有沒有查詢到對應(yīng)的記錄。因?yàn)樵趃olang中,一個(gè)變量由兩部分組成:type & value,只要任何一部分是明確的,則該變量就不是nil。在上例中,container的type已經(jīng)明確聲明是po.OnlineAccumulateRecord, 此時(shí)value是零值。因此它永遠(yuǎn)都不會(huì)是nil。

【beego】5、orm插入記錄,如果pk是非整型(e.g. string):no LastInsertId available error

orm設(shè)計(jì)時(shí)對于整型pk做了特別的支持:

當(dāng) Field 類型為 int, int32, int64, uint, uint32, uint64 時(shí),可以設(shè)置字段為自增健
當(dāng)模型定義里沒有主鍵時(shí),符合上述類型且名稱為 Id 的 Field 將被視為自增健。

但如果主鍵是string,通過以下代碼做insert操作時(shí)會(huì)返回"no LastInsertId available" error。因此需要增加IsNoLastInsertIdError判斷以免影響程序運(yùn)行的分支走向。

    o := orm.NewOrm()
    _, err = o.Insert(wechatNotify)
    if models.IsNoLastInsertIdError(err) {
        return nil
    }

同樣的,IsNoLastInsertIdError判斷的方法之一是根據(jù)error message判斷:

//這種情況是一種正常的情況,不應(yīng)該作為錯(cuò)誤拋出
func IsNoLastInsertIdError(err error) bool {
    if err == nil {
        return false
    }

    if strings.Contains(err.Error(), "no LastInsertId available") {
        return true
    }

    return false
}

【beego】6、報(bào)錯(cuò)誤導(dǎo):<Ormer> table: '.' not found,

好不容易把代碼擼完了,興沖沖的運(yùn)行debug,結(jié)果發(fā)現(xiàn)如下報(bào)錯(cuò)信息:

<Ormer> table: `.` not found, make sure it was registered with `RegisterModel()`

根據(jù)字面意思是說正在操作的這個(gè)名字為“.”的table沒有進(jìn)行regist操作。于是排查,但很快發(fā)現(xiàn):
1、根本就沒有一個(gè)叫"."的table
2、正在操作的表也已經(jīng)在beego啟動(dòng)的時(shí)候完成了regist操作
然后通過源碼進(jìn)行定位,報(bào)錯(cuò)位置:


func (o *orm) getMiInd(md interface{}, needPtr bool) (mi *modelInfo, ind reflect.Value) {
    val := reflect.ValueOf(md)
    ind = reflect.Indirect(val)
    typ := ind.Type()
    if needPtr && val.Kind() != reflect.Ptr {
        panic(fmt.Errorf("<Ormer> cannot use non-ptr model struct `%s`", getFullName(typ)))
    }
    name := getFullName(typ)
    if mi, ok := modelCache.getByFullName(name); ok {
        return mi, ind
    }
    panic(fmt.Errorf("<Ormer> table: `%s` not found, make sure it was registered with `RegisterModel()`", name))
}

那這個(gè)name是怎么得出來的呢?

// get reflect.Type name with package path.
func getFullName(typ reflect.Type) string {
    return typ.PkgPath() + "." + typ.Name()
}

也就是說,type.PkgPath() 和 type.Name()都是empty string 返回值。那什么時(shí)候他們返回的是empty string 呢?

    // Name returns the type's name within its package for a defined type.
    // For other (non-defined) types it returns the empty string.
    Name() string

    // PkgPath returns a defined type's package path, that is, the import path
    // that uniquely identifies the package, such as "encoding/base64".
    // If the type was predeclared (string, error) or not defined (*T, struct{},
    // []int, or A where A is an alias for a non-defined type), the package path
    // will be the empty string.
    PkgPath() string

從上述代碼可以看出,當(dāng)o.Insert()接收到參數(shù)是not defined的話,就會(huì)導(dǎo)致該項(xiàng)錯(cuò)誤,而并不是說這個(gè)玩意沒有regist(就這些玩意咋去regist嘛)。 注釋部分也說了not defined包括哪幾種:*T, struct{}, []int,以及這幾類的別名。
最后舉兩個(gè)能出現(xiàn)這個(gè)問題的例子:

//example 1
_struct := new(structExample)
o := orm.NewOrm()
o.Insert(&_pointer)

這里要特別說明golang里面new的用法:

// The new built-in function allocates memory. The first argument is a type,
// not a value, and the value returned is a pointer to a newly
// allocated zero value of that type.
func new(Type) *Type

注釋很明確的提到,new返回的是一個(gè)指針。更淺顯的犯錯(cuò)方式就像example2這樣:

//example 2
var _struct structExample
var _pointer &_struct
o := orm.NewOrm()
o.Insert(&_pointer)

【beego】7、報(bào)錯(cuò)誤導(dǎo):panic: reflect: call of reflect.Value.Interface on zero Value

再一次好不容易把代碼擼完了,興沖沖的運(yùn)行debug,結(jié)果發(fā)現(xiàn)如下報(bào)錯(cuò)信息:

panic: reflect: call of reflect.Value.Interface on zero Value
goroutine 1 [running]:
reflect.valueInterface(0x0, 0x0, 0x0, 0x1, 0x0, 0x0)
    /usr/local/Cellar/go/1.11/libexec/src/reflect/value.go:953 +0x2ce
reflect.Value.Interface(0x0, 0x0, 0x0, 0x0, 0x0)
    /usr/local/Cellar/go/1.11/libexec/src/reflect/value.go:948 +0x4c
github.com/astaxie/beego/orm.getFieldType(0x1af8900, 0xc0001e19e0, 0x196, 0x0, 0x0, 0x0)
    /Users/tangxqa/develop/code/go/src/github.com/astaxie/beego/orm/models_utils.go:181 +0xd00
github.com/astaxie/beego/orm.newFieldInfo(0xc0001f9040, 0x1af8900, 0xc0001e19e0, 0x196, 0x1a873ee, 0x4, 0x0, 0x0, 0x1e2bba0, 0x1af8900, ...)
    /Users/tangxqa/develop/code/go/src/github.com/astaxie/beego/orm/models_info_f.go:244 +0x372e
github.com/astaxie/beego/orm.addModelFields(0xc0001f9040, 0x1bf8820, 0xc0001e1980, 0x199, 0x0, 0x0, 0xc0000dd828, 0x0, 0x0)
    /Users/tangxqa/develop/code/go/src/github.com/astaxie/beego/orm/models_info_m.go:70 +0x3f4
github.com/astaxie/beego/orm.newModelInfo(0x1af8340, 0xc0001e1980, 0x16, 0xc0001f9040)
    /Users/tangxqa/develop/code/go/src/github.com/astaxie/beego/orm/models_info_m.go:45 +0x302
github.com/astaxie/beego/orm.registerModel(0x1c4b231, 0x4, 0x1af8340, 0xc0001e1980, 0x201)
    /Users/tangxqa/develop/code/go/src/github.com/astaxie/beego/orm/models_boot.go:62 +0x7b0
github.com/astaxie/beego/orm.RegisterModelWithPrefix(0x1c4b231, 0x4, 0xc0000ddd38, 0x7, 0x7)
    /Users/tangxqa/develop/code/go/src/github.com/astaxie/beego/orm/models_boot.go:320 +0x16d
rrs.com/rrsservice/models/po.init.28()
    /Users/tangxqa/develop/code/go/src/rrs.com/rrsservice/models/po/payment_wx.go:147 +0x2aa

可以通過堆棧信息看出這一報(bào)錯(cuò)發(fā)生在regist model時(shí),regist部分的代碼為:

    orm.RegisterModelWithPrefix(prefix, new(PaymentInfo))

PaymentInfo:


type PaymentInfo struct {
    Id              string                `orm:"size(32);pk;column(id)"`
    Status          string                
    OrderId         string                
    OrderSource     string               
    PayType         string               
    OrderPrice      int                   
    UnifiedOrderRes *UnifiedOrderResponse `orm:"rel(fk);null"` 
    User            *User                       
    Ts              time.Time            
}

好像代碼寫的沒毛病。只好再根據(jù)堆棧信息找到beego源碼中:github.com/astaxie/beego/orm.getFieldType 位于 astaxie/beego/orm/models_utils.go:181,getFieldType方法中是一堆類型判斷代碼:

// return field type as type constant from reflect.Value
func getFieldType(val reflect.Value) (ft int, err error) {
    switch val.Type() {
    case reflect.TypeOf(new(int8)):
        ft = TypeBitField
    case reflect.TypeOf(new(int16)):
        ft = TypeSmallIntegerField
    case reflect.TypeOf(new(int32)),
        reflect.TypeOf(new(int)):
        ft = TypeIntegerField
    case reflect.TypeOf(new(int64)):
        ft = TypeBigIntegerField
···
···

什么時(shí)候會(huì)走到這?那就看看github.com/astaxie/beego/orm.newFieldInfo 位于 gthub.com/astaxie/beego/orm/models_info_f.go:244的代碼:
這些代碼都是一些對 字段tag 的分析處理。等等,是不是忘記添加tag了??!

tag = "rel"
        tagValue = tags[tag]
        if tagValue != "" {
            switch tagValue {
            case "fk":
                fieldType = RelForeignKey
                break checkType
            case "one":
                fieldType = RelOneToOne
                break checkType
            case "m2m":
                fieldType = RelManyToMany
                if tv := tags["rel_table"]; tv != "" {
                    fi.relTable = tv
                } else if tv := tags["rel_through"]; tv != "" {
                    fi.relThrough = tv
                }
                break checkType
            default:
                err = fmt.Errorf("rel only allow these value: fk, one, m2m")
                goto wrongTag
            }
        }
        tag = "reverse"
        tagValue = tags[tag]
        if tagValue != "" {
            switch tagValue {
            case "one":
                fieldType = RelReverseOne
                break checkType
            case "many":
                fieldType = RelReverseMany
                if tv := tags["rel_table"]; tv != "" {
                    fi.relTable = tv
                } else if tv := tags["rel_through"]; tv != "" {
                    fi.relThrough = tv
                }
                break checkType
            default:
                err = fmt.Errorf("reverse only allow these value: one, many")
                goto wrongTag
            }
        }

        fieldType, err = getFieldType(addrField)

添加tag,搞定??!

   User            *User                `orm:"rel(fk)"`       

那是不是所有的字段在orm時(shí)都需要添加標(biāo)簽? 不是。當(dāng)字段是指針類型時(shí),如果沒有用orm:"-"進(jìn)行orm忽略,必須要添加標(biāo)簽來進(jìn)行表關(guān)系設(shè)置。
相關(guān)資料:https://beego.me/docs/mvc/model/models.md 參照其中的表關(guān)系設(shè)置章節(jié)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容