gosqlx

insert rows with sqlx, is it possible to avoid listing the fields explicitly?


I'm using sqlx library like the following:

type MyData {
    Field1 string `json:"db:field1"`
    Field2 string `json:"db:field2"`
}

...

res, err := db.Exec("INSERT INTO XXX (field1, field2) VALUES (?, ?)", data.XX, data.XX)

Is it possible to avoid specifying "field1, field2" explicitly, and let sqlx create the query and binding automatically, e.g

db.Exec2("table_name", data)

I didn't find a relevant method to do that.


Solution

  • No. The package sqlx is just a wrapper around the DB driver. It is not an ORM. It expects user-supplied, valid SQL query strings. You may construct the query strings programmatically, and design some method that builds the column names from struct tags using reflect package, but why reinventing the wheel? The advantage of using a lower-level package as sqlx is exactly to maintain your own queries in exchange for not introducing an ORM framework in your codebase. With an ORM instead it is the other way around.

    Gorm instead has a set of conventions that do what you want out of the box. You wouldn't even have to specify the db tags:

    GORM prefer convention over configuration, by default, GORM uses ID as primary key, pluralize struct name to snake_cases as table name, snake_case as column name, and uses CreatedAt, UpdatedAt to track creating/updating time

    type MyData {
        Field1 string `json:"field1"`
        Field2 string `json:"field2"`
    }
    
    data := MyData {
        Field1: "foo", 
        Field2: "bar",
    }
    
    result := db.Create(&data) 
    // results in something like this:
    // INSERT INTO my_datas (field1, field2) VALUES ('foo', 'bar')