github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/db/entity_action.go (about)

     1  // This file is part of the Smart Home
     2  // Program complex distribution https://github.com/e154/smart-home
     3  // Copyright (C) 2016-2023, Filippov Alex
     4  //
     5  // This library is free software: you can redistribute it and/or
     6  // modify it under the terms of the GNU Lesser General Public
     7  // License as published by the Free Software Foundation; either
     8  // version 3 of the License, or (at your option) any later version.
     9  //
    10  // This library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13  // Library General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public
    16  // License along with this library.  If not, see
    17  // <https://www.gnu.org/licenses/>.
    18  
    19  package db
    20  
    21  import (
    22  	"context"
    23  	"fmt"
    24  	"strings"
    25  	"time"
    26  
    27  	"github.com/jackc/pgerrcode"
    28  	"github.com/jackc/pgx/v5/pgconn"
    29  
    30  	"github.com/e154/smart-home/common/apperr"
    31  
    32  	"github.com/e154/smart-home/common"
    33  	"github.com/pkg/errors"
    34  	"gorm.io/gorm"
    35  )
    36  
    37  // EntityActions ...
    38  type EntityActions struct {
    39  	Db *gorm.DB
    40  }
    41  
    42  // EntityAction ...
    43  type EntityAction struct {
    44  	Id          int64 `gorm:"primary_key"`
    45  	Name        string
    46  	Description string
    47  	Icon        *string
    48  	Entity      *Entity
    49  	EntityId    common.EntityId
    50  	Image       *Image
    51  	ImageId     *int64
    52  	Script      *Script
    53  	ScriptId    *int64
    54  	Type        string
    55  	CreatedAt   time.Time `gorm:"<-:create"`
    56  	UpdatedAt   time.Time
    57  }
    58  
    59  // TableName ...
    60  func (d *EntityAction) TableName() string {
    61  	return "entity_actions"
    62  }
    63  
    64  // Add ...
    65  func (n EntityActions) Add(ctx context.Context, v *EntityAction) (id int64, err error) {
    66  	if err = n.Db.WithContext(ctx).Create(&v).Error; err != nil {
    67  		var pgErr *pgconn.PgError
    68  		if errors.As(err, &pgErr) {
    69  			switch pgErr.Code {
    70  			case pgerrcode.UniqueViolation:
    71  				if strings.Contains(pgErr.Message, "name_at_entity_actions_unq") {
    72  					err = errors.Wrap(apperr.ErrEntityActionAdd, fmt.Sprintf("action name \"%s\" not unique", v.Name))
    73  					return
    74  				}
    75  			default:
    76  				fmt.Printf("unknown code \"%s\"\n", pgErr.Code)
    77  			}
    78  		}
    79  		err = errors.Wrap(apperr.ErrEntityActionAdd, err.Error())
    80  		return
    81  	}
    82  	id = v.Id
    83  	return
    84  }
    85  
    86  // GetById ...
    87  func (n EntityActions) GetById(ctx context.Context, id int64) (v *EntityAction, err error) {
    88  	v = &EntityAction{Id: id}
    89  	if err = n.Db.WithContext(ctx).First(&v).Error; err != nil {
    90  		if errors.Is(err, gorm.ErrRecordNotFound) {
    91  			err = errors.Wrap(apperr.ErrEntityActionNotFound, fmt.Sprintf("id \"%d\"", id))
    92  			return
    93  		}
    94  		err = errors.Wrap(apperr.ErrEntityActionGet, err.Error())
    95  	}
    96  	return
    97  }
    98  
    99  // Update ...
   100  func (n EntityActions) Update(ctx context.Context, m *EntityAction) (err error) {
   101  	err = n.Db.WithContext(ctx).Model(&EntityAction{Id: m.Id}).Updates(map[string]interface{}{
   102  		"name":        m.Name,
   103  		"description": m.Description,
   104  		"icon":        m.Icon,
   105  		"entity_id":   m.EntityId,
   106  		"image_id":    m.ImageId,
   107  		"script_id":   m.ScriptId,
   108  		"type":        m.Type,
   109  	}).Error
   110  
   111  	if err != nil {
   112  		var pgErr *pgconn.PgError
   113  		if errors.As(err, &pgErr) {
   114  			switch pgErr.Code {
   115  			case pgerrcode.UniqueViolation:
   116  				if strings.Contains(pgErr.Message, "name_at_entity_actions_unq") {
   117  					err = errors.Wrap(apperr.ErrEntityActionUpdate, fmt.Sprintf("action name \"%s\" not unique", m.Name))
   118  					return
   119  				}
   120  			default:
   121  				fmt.Printf("unknown code \"%s\"\n", pgErr.Code)
   122  			}
   123  		}
   124  		err = errors.Wrap(apperr.ErrEntityActionUpdate, err.Error())
   125  	}
   126  	return
   127  }
   128  
   129  // DeleteByEntityId ...
   130  func (n EntityActions) DeleteByEntityId(ctx context.Context, deviceId common.EntityId) (err error) {
   131  	if err = n.Db.WithContext(ctx).Delete(&EntityAction{}, "entity_id = ?", deviceId).Error; err != nil {
   132  		err = errors.Wrap(apperr.ErrEntityActionDelete, err.Error())
   133  	}
   134  	return
   135  }
   136  
   137  // List ...
   138  func (n *EntityActions) List(ctx context.Context, limit, offset int, orderBy, sort string) (list []*EntityAction, total int64, err error) {
   139  
   140  	if err = n.Db.WithContext(ctx).Model(EntityAction{}).Count(&total).Error; err != nil {
   141  		err = errors.Wrap(apperr.ErrEntityActionList, err.Error())
   142  		return
   143  	}
   144  
   145  	list = make([]*EntityAction, 0)
   146  	err = n.Db.WithContext(ctx).
   147  		Limit(limit).
   148  		Offset(offset).
   149  		Order(fmt.Sprintf("%s %s", sort, orderBy)).
   150  		Find(&list).
   151  		Error
   152  
   153  	if err != nil {
   154  		err = errors.Wrap(apperr.ErrEntityActionList, err.Error())
   155  	}
   156  	return
   157  }
   158  
   159  // AddMultiple ...
   160  func (n *EntityActions) AddMultiple(ctx context.Context, actions []*EntityAction) (err error) {
   161  	if err = n.Db.WithContext(ctx).Create(&actions).Error; err != nil {
   162  		var pgErr *pgconn.PgError
   163  		if errors.As(err, &pgErr) {
   164  			switch pgErr.Code {
   165  			case pgerrcode.UniqueViolation:
   166  				if strings.Contains(pgErr.Message, "name_at_entity_states_unq") {
   167  					err = errors.Wrap(apperr.ErrEntityActionAdd, "multiple insert")
   168  					return
   169  				}
   170  			default:
   171  				fmt.Printf("unknown code \"%s\"\n", pgErr.Code)
   172  			}
   173  		}
   174  		err = errors.Wrap(apperr.ErrEntityActionAdd, err.Error())
   175  	}
   176  	return
   177  }