Common Methods

Insert/Replace/Save

These chained operation methods are used for data insertion and support automatic single or batch data insertion, with differences as follows:

  1. Insert

    Uses the INSERT INTO statement for database insertion. If the inserted data contains a primary key or unique index, it returns failure; otherwise, a new record is inserted.

  2. Replace

    Uses the REPLACE INTO statement for database insertion. If the inserted data contains a primary key or unique index, it deletes the existing record, ensuring that a new record is inserted.

  3. Save

    Uses the INSERT INTO statement for database insertion. If the inserted data contains a primary key or unique index, it updates the existing data; otherwise, it inserts a new record. For certain databases, such as PgSQL, SQL server, Oracle, you can use the OnConflict method to specify conflict keys.

    1. db.Model(table).Data(g.Map{
    2. "id": 1,
    3. "passport": "p1",
    4. "password": "pw1",
    5. }).OnConflict("id").Save()

Some database types do not support Replace/Save methods. Refer to the ORM - Model 🔥 section for details.

These methods need to be used in conjunction with the Data method, which is used to pass data parameters for data insertion/updating and other write operations.

InsertIgnore

This method is used to ignore errors and continue with insertion if the inserted data contains a primary key or unique index. The method is defined as follows:

  1. func (m *Model) InsertIgnore(data ...interface{}) (result sql.Result, err error)

InsertAndGetId

This method is used to insert data while directly returning the auto-increment field’s ID. The method is defined as follows:

  1. func (m *Model) InsertAndGetId(data ...interface{}) (lastInsertId int64, err error)

OnDuplicate/OnDuplicateEx

OnDuplicate/OnDuplicateEx methods need to be used together with the Save method to specify the fields to be updated/not updated for the Save operation. Parameters can be strings, string arrays, or Map. For example:

  1. OnDuplicate("nickname, age")
  2. OnDuplicate("nickname", "age")
  3. OnDuplicate(g.Map{
  4. "nickname": gdb.Raw("CONCAT('name_', VALUES(`nickname`))"),
  5. })
  6. OnDuplicate(g.Map{
  7. "nickname": "passport",
  8. })

OnDuplicateEx is used to exclude specified fields from being updated, with excluded fields already in the data set being inserted.

Usage Examples

Example 1: Basic Usage

Data insertion/save methods need to be used with the Data method. The parameter type can be Map/Struct/Slice:

  1. // INSERT INTO `user`(`name`) VALUES('john')
  2. g.Model("user").Data(g.Map{"name": "john"}).Insert()
  3. // INSERT IGNORE INTO `user`(`uid`,`name`) VALUES(10000,'john')
  4. g.Model("user").Data(g.Map{"uid": 10000, "name": "john"}).InsertIgnore()
  5. // REPLACE INTO `user`(`uid`,`name`) VALUES(10000,'john')
  6. g.Model("user").Data(g.Map{"uid": 10000, "name": "john"}).Replace()
  7. // INSERT INTO `user`(`uid`,`name`) VALUES(10001,'john') ON DUPLICATE KEY UPDATE `uid`=VALUES(`uid`),`name`=VALUES(`name`)
  8. g.Model("user").Data(g.Map{"uid": 10001, "name": "john"}).Save()

You can also directly pass data parameters to the insertion/save methods without using the Data method:

  1. g.Model("user").Insert(g.Map{"name": "john"})
  2. g.Model("user").Replace(g.Map{"uid": 10000, "name": "john"})
  3. g.Model("user").Save(g.Map{"uid": 10001, "name": "john"})

Data parameters are often struct types, for example, when the table fields are uid/name/site:

  1. type User struct {
  2. Uid int `orm:"uid"`
  3. Name string `orm:"name"`
  4. Site string `orm:"site"`
  5. }
  6. user := &User{
  7. Uid: 1,
  8. Name: "john",
  9. Site: "https://goframe.org",
  10. }
  11. // INSERT INTO `user`(`uid`,`name`,`site`) VALUES(1,'john','https://goframe.org')
  12. g.Model("user").Data(user).Insert()

Example 2: Batch Data Insertion

Batch insertion is achieved by passing a Slice array type parameter to the Data method. Array elements need to be of Map or Struct type to automatically derive field information and generate batch operation SQL.

  1. // INSERT INTO `user`(`name`) VALUES('john_1'),('john_2'),('john_3')
  2. g.Model("user").Data(g.List{
  3. {"name": "john_1"},
  4. {"name": "john_2"},
  5. {"name": "john_3"},
  6. }).Insert()

You can specify the number of records to be written in batches using the Batch method (default is 10). The following example will be split into two insertion requests:

  1. // INSERT INTO `user`(`name`) VALUES('john_1'),('john_2')
  2. // INSERT INTO `user`(`name`) VALUES('john_3')
  3. g.Model("user").Data(g.List{
  4. {"name": "john_1"},
  5. {"name": "john_2"},
  6. {"name": "john_3"},
  7. }).Batch(2).Insert()

Example 3: Batch Data Save

The principle of batch save operations is the same as single save operations. When the inserted data contains a primary key or unique index, it updates the existing record; otherwise, a new record is inserted.

oracle, dm, mssql do not support batch savings.

  1. // INSERT INTO `user`(`uid`,`name`) VALUES(10000,'john_1'),(10001,'john_2'),(10002,'john_3')
  2. // ON DUPLICATE KEY UPDATE `uid`=VALUES(`uid`),`name`=VALUES(`name`)
  3. g.Model("user").Data(g.List{
  4. {"uid":10000, "name": "john_1"},
  5. {"uid":10001, "name": "john_2"},
  6. {"uid":10002, "name": "john_3"},
  7. }).Save()

RawSQL Statement Embedding

gdb.Raw is a string type whose parameters will be directly embedded as SQL fragments into the final SQL statement submitted to the underlying database, not automatically converted to string parameter types, nor treated as preprocessed parameters. For more details, refer to the section: ORM Senior - RawSQL. For example:

  1. // INSERT INTO `user`(`id`,`passport`,`password`,`nickname`,`create_time`) VALUES('id+2','john','123456','now()')
  2. g.Model("user").Data(g.Map{
  3. "id": "id+2",
  4. "passport": "john",
  5. "password": "123456",
  6. "nickname": "JohnGuo",
  7. "create_time": "now()",
  8. }).Insert()
  9. // Execution Error: Error Code: 1136. Column count doesn't match value count at row 1

Revised using gdb.Raw:

  1. // INSERT INTO `user`(`id`,`passport`,`password`,`nickname`,`create_time`) VALUES(id+2,'john','123456',now())
  2. g.Model("user").Data(g.Map{
  3. "id": gdb.Raw("id+2"),
  4. "passport": "john",
  5. "password": "123456",
  6. "nickname": "JohnGuo",
  7. "create_time": gdb.Raw("now()"),
  8. }).Insert()