Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

go - How to structure a generic database connection handler

How do I create a function generic enough that it doesn't have to use many switch statements within it to check what type of database the user chose?

My current approach is:

  • If a database type is supported, have a generic WriteData() function that handles all the credential details of that specific database type that were passed by the user.

  • Have a struct for each database type: mysql, postgres, connection string, etc...

  • Have a struct to represent each type of credential information used by the specific database

  • Marshal data into the struct depending which database type was chosen

  • Use maps like this:

    var GetNewDB = map[string]interface{}{
        "dbType1":          dbType1{},
        "dbType2":          dbType2{},
        "dbType3":          dbType3{},
        "dbType4":          dbType4{},
        "dbType5":          dbType5{},
     }
    
     var GetCredentials = map[string]interface{}{
        "dbType1":          Type1Creds{},
        "dbType2":          Type2Creds{},
        "dbType3":          Type3Creds{},
        "dbType4":          Type4Creds{},
        "dbType5":          Type5Creds{},
     }
    
  • Access generically the details of whatever database is chosen:

    whateverDatabase := GetNewDB[dbTypeUserChose]
    dbCredentials := GetCredentials[dbTypeUserChose]
    

In the above example, it doesn't necessarily matter that the variables are of type interface{}

Ultimately, this isn't working because each database needs specifics at certain points during the function - e.g. that one type of database needs a username and password, while another may not. It seems to be only solvable by dumping in many type switches or switch statements to give the specifics.

question from:https://stackoverflow.com/questions/65921977/how-to-structure-a-generic-database-connection-handler

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...