2016-11-05 31 views
0

我正在實施數據庫API。我有模特。我需要對每個模型實施CRUD操作。現在我爲每個模型創建一個單獨的GetAllModels函數和Get方法。我怎麼能爲所有模型做一次,如果需要的話只是傳遞一些變量?如何在Golang中爲任何模型實現基本的CRUD動作?

下面我用每個模型的模式:

type City struct { 
    Attr1 string 
    Attr2 string 
} 

type Country struct { 
    Attr1 string 
    Attr2 string 
} 

func GetAllCities(db *sqlx.DB) ([]*City, error) { 
    items := []*City{} 
    err := db.Select(&items, "SELECT * FROM cities") 
    // check err 
    return items, nil 
} 

func (m *City) Get(db *sqlx.DB, id string) error { 
    if err := db.Get(m, "SELECT FROM cities WHERE id = ?", id); err != nil { 
     return err 
    } 
    return nil 
} 

func GetAllCountries(db *sqlx.DB) ([]*Country, error) { 
    items := []*Country{} 
    err := db.Select(&items, "SELECT * FROM countries") 
    // check err 
    return items, nil 
} 

func (m *Country) Get(db *sqlx.DB, id string) error { 
    if err := db.Get(m, "SELECT FROM countries WHERE id = ?", id); err != nil { 
     return err 
    } 
    return nil 
} 

但是從模型實際上變成模型是查詢字符串和切片對象的類型。

如何爲所有未來的模型製作一個通用的GetAll函數和Get方法?

+0

我看到的問題是downvoted。有人可以解釋爲什麼嗎? – hsrv

+0

我沒有低調,但我想知道模特在這裏的角色是什麼。我可以看到它在面向對象的語言中用作抽象類,但我不認爲它會像其他任何東西一樣有用。模型究竟做了什麼? –

+0

@ChronoKitsune,也許我還不夠清楚。我不想創建一個抽象類。我已經更新了問題中的代碼示例,請仔細閱讀。我有幾個結構。並有非常相似的功能和方法從數據庫中獲取數據。每個這樣的函數具有相同的結構,但是不同的*查詢字符串*和不同的*類型*。所以我認爲這些funcs不必是不同的funcs,它們可能是唯一一套CRUD funcs,但有不同的變量。但我堅持實施這個。 – hsrv

回答

0

我沒有測試過這個,但它應該工作。如果您收到每個請求的表名和列名(或者您知道它們),您可以從db中獲取interface作爲變量傳遞表和列。

包主要

import (
    "errors" 
    "fmt" 

    "github.com/jmoiron/sqlx" 
) 

func selectAll(table string) string { 
    return fmt.Sprintf("SELECT * FROM %s", table) 
} 

func selectWhere(table string, column string) string { 
    return fmt.Sprintf("SELECT * FROM %s WHERE %s = ?", table, column) 
} 

func validTableStr(table string) bool { 
    // real validation here 
    return true 
} 

func validColumnStr(table string, column string) bool { 
    // real validation here 
    return true 
} 

func GetAll(db *sqlx.DB, table string) ([]interface{}, error) { 

    if !validTableStr(table) { 
     return nil, errors.New("invalid table name") 
    } 

    items := []interface{}{} 
    err := db.Select(&items, selectAll(table)) 
    return items, err 
} 

func GetWhere(db *sqlx.DB, table string, column string, value interface{}) ([]interface{}, error) { 

    if !validTableStr(table) { 
     return nil, errors.New("invalid table name") 
    } 

    if !validColumnStr(table, column) { 
     return nil, errors.New("invalid column name") 
    } 

    items := []interface{}{} 
    err := db.Select(&items, selectWhere(table, column), value) 
    return items, err 
} 
相關問題