douzao9845 2019-06-11 04:20 采纳率: 0%
浏览 225

建立SQL查询以从map [string] interface {}添加新的列和值

I am new to Go & CQL and I need some help with the following (couldn't find an answer to my question on the platform): I have a map[string]interface{} and for each k,v pair in this map, I need to check if the column (represented by k) exists in the field slice...and if not - add it as a new column to the table (with the specific type, based on the value type), as well as the value. I am struggling finding a way to get the value type, convert it to a Cassandra data type & include it in the query string as a column type. My code so far looks like this:

//takes as arguments the map and a slice that holds the columns that are already in the table. Is there 
//A fucntion that returns a string to be executed later by //session.Query(...).Exec() to add columns that are missing in the table
func AddColumns(myInterfaceMap map[string]string, fields []string) string {

    var columnsToBeAdded []string

    var sb strings.Builder
    sb.WriteString("ALTER TABLE sample_demo.main ADD (")
    for k := range myInterfaceMap {

        if !contains(fields, k) {
            columnsToBeAdded = append(columnsToBeAdded, k)
            fields = append(Fields, k)
        }
    }
    for idx, column := range columnsToBeAdded {
        if idx == (len(columnsToBeAdded) - 1) {
            sb.WriteString(column)
            //I need to dynamically specify the column type, depending on value   for the 
            //concrete key...need help how to do it
            sb.WriteString(" text)") 

        } else {
            sb.WriteString(column)
            sb.WriteString(" text, ")
        }
    }
    log.Println(sb.String())
    log.Println(fields)
    return sb.String()
}

If someone can help, that would be indeed appreciated :)

展开全部

  • 写回答

0条回答 默认 最新

      编辑
      预览

      报告相同问题?

      手机看
      程序员都在用的中文IT技术交流社区

      程序员都在用的中文IT技术交流社区

      专业的中文 IT 技术社区,与千万技术人共成长

      专业的中文 IT 技术社区,与千万技术人共成长

      关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

      关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

      客服 返回
      顶部