diff --git a/ksql.go b/ksql.go index 5791fa8..03a56f2 100644 --- a/ksql.go +++ b/ksql.go @@ -526,21 +526,27 @@ func (c DB) insertWithLastInsertID( } vID := reflect.ValueOf(id) - tID := vID.Type() fieldAddr := v.Elem().Field(info.ByName(idName).Index).Addr() fieldType := fieldAddr.Type().Elem() - if !tID.ConvertibleTo(fieldType) { + switch fieldType.Kind() { + case reflect.Int, reflect.Int64, reflect.Uint, reflect.Uint64: + fieldAddr.Elem().Set(vID.Convert(fieldType)) + return nil + + case reflect.String: + // In case the record's ID is a string, + // we cannot retrieve it, so we just return: + return nil + + default: return fmt.Errorf( "can't convert last insert id of type int64 into field `%s` of type %v", idName, fieldType, ) } - - fieldAddr.Elem().Set(vID.Convert(fieldType)) - return nil } func (c DB) insertWithNoIDRetrieval( diff --git a/test_adapters.go b/test_adapters.go index 59b253d..7fdca45 100644 --- a/test_adapters.go +++ b/test_adapters.go @@ -786,6 +786,28 @@ func InsertTest( tt.AssertEqual(t, result.Address, u.Address) }) + t.Run("should insert one user correctly with a string ID", func(t *testing.T) { + c := newTestDB(db, dialect) + + u := user{ + Name: "FernandaIsTheID", + Address: address{ + Country: "Brazil", + }, + } + + err := c.Insert(ctx, NewTable("users", "name"), &u) + tt.AssertNoErr(t, err) + tt.AssertEqual(t, u.Name, "FernandaIsTheID") + + result := user{} + err = getUserByName(db, dialect, &result, "FernandaIsTheID") + tt.AssertNoErr(t, err) + + tt.AssertEqual(t, result.Name, u.Name) + tt.AssertEqual(t, result.Address, u.Address) + }) + t.Run("should insert ignoring the ID with multiple ids", func(t *testing.T) { if dialect.InsertMethod() != sqldialect.InsertWithLastInsertID { return