github.com/ecodeclub/eorm@v0.0.2-0.20231001112437-dae71da914d0/delete.go (about) 1 // Copyright 2021 ecodeclub 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package eorm 16 17 import ( 18 "context" 19 20 "github.com/valyala/bytebufferpool" 21 ) 22 23 var _ QueryBuilder = &Deleter[any]{} 24 25 // Deleter builds DELETE query 26 type Deleter[T any] struct { 27 builder 28 Session 29 table interface{} 30 where []Predicate 31 } 32 33 // NewDeleter 开始构建一个 DELETE 查询 34 func NewDeleter[T any](sess Session) *Deleter[T] { 35 return &Deleter[T]{ 36 builder: builder{ 37 core: sess.getCore(), 38 buffer: bytebufferpool.Get(), 39 }, 40 Session: sess, 41 } 42 } 43 44 // Build returns DELETE query 45 func (d *Deleter[T]) Build() (Query, error) { 46 defer bytebufferpool.Put(d.buffer) 47 _, _ = d.buffer.WriteString("DELETE FROM ") 48 var err error 49 if d.table == nil { 50 d.table = new(T) 51 } 52 d.meta, err = d.metaRegistry.Get(d.table) 53 if err != nil { 54 return EmptyQuery, err 55 } 56 57 d.quote(d.meta.TableName) 58 if len(d.where) > 0 { 59 d.writeString(" WHERE ") 60 err = d.buildPredicates(d.where) 61 if err != nil { 62 return EmptyQuery, err 63 } 64 } 65 d.end() 66 return Query{SQL: d.buffer.String(), Args: d.args}, nil 67 } 68 69 // From accepts model definition 70 func (d *Deleter[T]) From(table interface{}) *Deleter[T] { 71 d.table = table 72 return d 73 } 74 75 // Where accepts predicates 76 func (d *Deleter[T]) Where(predicates ...Predicate) *Deleter[T] { 77 d.where = predicates 78 return d 79 } 80 81 // Exec sql 82 func (d *Deleter[T]) Exec(ctx context.Context) Result { 83 query, err := d.Build() 84 if err != nil { 85 return Result{err: err} 86 } 87 return newQuerier[T](d.Session, query, d.meta, DELETE).Exec(ctx) 88 }