Introduction to golang structure and database table field reflection automatic mapping sqlmapper library

There is a ready-made library "database/sql" for operating databases in Golang, but "database/sql" only provides the most basic operation interface;

For operations such as adding, deleting, modifying, and querying a table in the database, you must manually write the sql string, which is usually a hard-coded string (Hard-Code),

And it is necessary to manually maintain the mapping relationship between fields in sql and variables in Golang, which has poor scalability and is very error-prone.

Under normal circumstances, we expect that there is a Struct in Golang and a Table in DB to establish a mapping relationship ( Mapper ),

After that, we will operate the corresponding Table in the DB by operating this Struct, without Hard-Coded sql string, and without manually maintaining the field mapping relationship.

sqlmapper  is such a minimalist tool library (as simple as only one go file).

Original address: https://github.com/arthas29/sqlmapper

For example, there is a table in DB with the following structure:

CREATE TABLE `test_table` (
  `field_key` varchar(64) NOT NULL DEFAULT '',
  `field_one` varchar(64) DEFAULT NULL,
  `field_two` tinyint(1) DEFAULT NULL,
  `field_thr` int(12) DEFAULT NULL,
  `field_fou` float DEFAULT NULL,
  PRIMARY KEY (`field_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

In Golang, create the corresponding Struct as follows:

// struct in go such as:
type DemoRow struct {
	FieldKey string  `sql:"field_key"`
	FieldOne string  `sql:"field_one"`
	FieldTwo bool    `sql:"field_two"`
	FieldThr int64   `sql:"field_thr"`
	FieldFou float64 `sql:"field_fou"`
}

Then, we can perform on the Struct by the  SELECT/ INSERT/ UPDATE/ DELETE operation, no hard-coded lengthy sql string;

Example (see fields_map_test.go for more examples  ):

// select single row
// Query by primary key (field[0])
func QueryByKey(ctx context.Context, tx *sql.Tx, db *sql.DB, fieldKey string) (
	*DemoRow, error) {

	var row DemoRow
	row.FieldKey = fieldKey
	fm, err := NewFieldsMap(table, &row)
	if err != nil {
		return nil, err
	}

	objptr, err := fm.SQLSelectByPriKey(ctx, tx, db)
	if err != nil {
		return nil, err
	}

	return objptr.(*DemoRow), nil
}
    

 

 

Guess you like

Origin blog.csdn.net/whatday/article/details/113772272