Browse Source

Automatically populate created_at, and updated_at on insert

Volodymyr Tkach 2 years ago
parent
commit
ab29eda543
2 changed files with 32 additions and 7 deletions
  1. 12 7
      gosql/common/common.go
  2. 20 0
      gosql/common/common_test.go

+ 12 - 7
gosql/common/common.go

@@ -78,6 +78,7 @@ func insertRowString(row any) (string, []any) {
 	values := []string{}
 	args := []any{}
 	position := 1
+	created_at := currentUnixTimestamp()
 	for i := 0; i < t.NumField(); i++ {
 		if table == "" {
 			if tag := t.Field(i).Tag.Get("table"); tag != "" {
@@ -87,13 +88,17 @@ func insertRowString(row any) (string, []any) {
 		if tag := t.Field(i).Tag.Get("field"); tag != "" && tag != "id" {
 			fields = append(fields, tag)
 			values = append(values, "$"+strconv.Itoa(position))
-			switch t.Field(i).Type.Kind() {
-			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
-				args = append(args, v.Field(i).Int())
-			case reflect.Float32, reflect.Float64:
-				args = append(args, v.Field(i).Float())
-			case reflect.String:
-				args = append(args, v.Field(i).String())
+			if tag == "created_at" || tag == "updated_at" {
+				args = append(args, created_at)
+			} else {
+				switch t.Field(i).Type.Kind() {
+				case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+					args = append(args, v.Field(i).Int())
+				case reflect.Float32, reflect.Float64:
+					args = append(args, v.Field(i).Float())
+				case reflect.String:
+					args = append(args, v.Field(i).String())
+				}
 			}
 			position++
 		}

+ 20 - 0
gosql/common/common_test.go

@@ -61,6 +61,26 @@ var _ = Describe("common", func() {
 			Expect(args[1]).To(Equal("Value"))
 			Expect(args[2]).To(Equal(int64(59)))
 		})
+
+		It("convert struct to SQL query and populate created_at and updated_at", func() {
+			var row struct {
+				ID        int64  `field:"id" table:"users"`
+				CreatedAt int64  `field:"created_at"`
+				UpdatedAt int64  `field:"updated_at"`
+				Name      string `field:"name"`
+			}
+
+			row.Name = "Name"
+
+			sql, args := common.InsertRowString(&row)
+
+			Expect(sql).To(Equal(`INSERT INTO users (created_at, updated_at, name) VALUES ($1, $2, $3)`))
+
+			Expect(len(args)).To(Equal(3))
+			Expect(args[0].(int64) > 0).To(BeTrue())
+			Expect(args[1].(int64) > 0).To(BeTrue())
+			Expect(args[2]).To(Equal("Name"))
+		})
 	})
 
 	Context("log", func() {