github.com/goplus/yap@v0.8.1/ydb/delete.go (about) 1 /* 2 * Copyright (c) 2024 The GoPlus Authors (goplus.org). All rights reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package ydb 18 19 import ( 20 "context" 21 "database/sql" 22 "log" 23 "reflect" 24 ) 25 26 // ----------------------------------------------------------------------------- 27 28 // Delete deltes rows by cond. 29 // - delete <cond>, <arg1>, <arg2>, ... 30 func (p *Class) Delete(cond string, args ...any) (sql.Result, error) { 31 tbl := p.exprTblname(cond) 32 query := makeDeleteExpr(tbl, cond) 33 iArgSlice := checkArgSlice(args) 34 if iArgSlice >= 0 { 35 return p.deleteMulti(context.TODO(), query, iArgSlice, args) 36 } 37 return p.deleteOne(context.TODO(), query, args) 38 } 39 40 func makeDeleteExpr(tbl string, cond string) string { 41 query := make([]byte, 0, 64) 42 query = append(query, "DELETE FROM "...) 43 query = append(query, tbl...) 44 query = append(query, " WHERE "...) 45 query = append(query, cond...) 46 return string(query) 47 } 48 49 func (p *Class) deleteRet(result sql.Result, err error) (sql.Result, error) { 50 if err != nil { 51 p.handleErr("delete:", err) 52 } 53 return result, err 54 } 55 56 func (p *Class) deleteOne(ctx context.Context, query string, args []any) (sql.Result, error) { 57 if debugExec { 58 log.Println("==>", query, args) 59 } 60 result, err := p.db.ExecContext(ctx, query, args...) 61 return p.deleteRet(result, err) 62 } 63 64 func (p *Class) deleteMulti(ctx context.Context, query string, iArgSlice int, args []any) (sql.Result, error) { 65 argSlice := args[iArgSlice] 66 defer func() { 67 args[iArgSlice] = argSlice 68 }() 69 vArgSlice := reflect.ValueOf(argSlice) 70 nAffected := deleteResult(0) 71 for i, n := 0, vArgSlice.Len(); i < n; i++ { 72 arg := vArgSlice.Index(i).Interface() 73 args[iArgSlice] = arg 74 result, err := p.deleteOne(ctx, query, args) 75 if err != nil { 76 return nAffected, err 77 } 78 if v, e := result.RowsAffected(); e == nil { 79 nAffected += deleteResult(v) 80 } 81 } 82 return nAffected, nil 83 } 84 85 // ----------------------------------------------------------------------------- 86 87 type deleteResult int64 88 89 func (n deleteResult) LastInsertId() (int64, error) { 90 panic("not impl") 91 } 92 93 func (n deleteResult) RowsAffected() (int64, error) { 94 return int64(n), nil 95 } 96 97 // -----------------------------------------------------------------------------