Browse Source

Add deleteRowByIDString func

Volodymyr Tkach 2 years ago
parent
commit
142c16097e
3 changed files with 27 additions and 0 deletions
  1. 14 0
      gosql/common/common.go
  2. 1 0
      gosql/common/common_export_test.go
  3. 12 0
      gosql/common/common_test.go

+ 14 - 0
gosql/common/common.go

@@ -135,6 +135,20 @@ func rowExistsString(row any) string {
 	return `SELECT 1 FROM ` + table + ` WHERE id = $1 LIMIT 1`
 }
 
+func deleteRowByIDString(row any) string {
+	v := reflect.ValueOf(row).Elem()
+	t := v.Type()
+	var table string
+	for i := 0; i < t.NumField(); i++ {
+		if table == "" {
+			if tag := t.Field(i).Tag.Get("table"); tag != "" {
+				table = tag
+			}
+		}
+	}
+	return `DELETE FROM ` + table + ` WHERE id = $1 LIMIT 1`
+}
+
 func ParseUrl(dbURL string) (*url.URL, error) {
 	databaseURL, err := url.Parse(dbURL)
 	if err != nil {

+ 1 - 0
gosql/common/common_export_test.go

@@ -5,3 +5,4 @@ var Log = log
 var Scans = scans
 var QueryRowByIDString = queryRowByIDString
 var RowExistsString = rowExistsString
+var DeleteRowByIDString = deleteRowByIDString

+ 12 - 0
gosql/common/common_test.go

@@ -103,6 +103,18 @@ var _ = Describe("common", func() {
 		})
 	})
 
+	Context("deleteRowByIDString", func() {
+		It("convert struct to SQL query", func() {
+			var row struct {
+				ID    int64  `field:"id" table:"users"`
+				Name  string `field:"name"`
+				Value string `field:"value"`
+			}
+
+			Expect(common.DeleteRowByIDString(&row)).To(Equal(`DELETE FROM users WHERE id = $1 LIMIT 1`))
+		})
+	})
+
 	Context("ParseUrl", func() {
 		Context("Success", func() {
 			It("for MySQL", func() {