在编译EasyNVR的时候,我们为了防止数据库内的表重复,使用了sqlite3_exec函数来判断一个表是否存在。但在EasyDSS中,我们使用的是GORM方式。ORM是Golang目前比较热门的数据库ORM操作库,对开发者比较友好,使用也方便简单。

在EasyDSS在调用该方式过程中,出现了以下错误:

具体函数代码如下:

// 根据主键,判断是否存在
func (impl *BaseDaoImpl) Exists(id string) bool {
   dataType := reflect.TypeOf(impl.TableStruct)
   data := reflect.New(dataType)

   rowsAffects := impl.fromTable().First(&data, impl.WherePrimaryKey, id).RowsAffected

   if rowsAffects == 0 {
      return false
   }

   return true
}

可以看到以上代码使用了First函数查询数据,查看对应的描述:

// First find first record that match given conditions, order by primary key

说明此函数需要使用传入主键,才能解决此问题,因此我们需要将data数据传入主键。但是代码中因为data为反射出来的数据添加id数据不够方便,因此直接使用Find函数代替First函数,即解决此问题。

// 根据主键,判断是否存在
func (impl *BaseDaoImpl) Exists(id string) bool {
   dataType := reflect.TypeOf(impl.TableStruct)
   data := reflect.New(dataType)

   rowsAffects := impl.fromTable().Find(&data, impl.WherePrimaryKey, id).RowsAffected

   if rowsAffects == 0 {
      return false
   }

   return true
}

随后检查,该模块可以正常使用。

如果大家想了解我们在EasyNVR上的实现过程,可以阅读此文:EasyNVR使用sqlite3如何判断一个表是否在数据库中已经存在。关于其他TSINGSEE青犀视频流媒体服务器的相关解决方案,欢迎访问TSINGSEE青犀视频官方网站。

posted on 2021-02-20 14:11  EasyDSS  阅读(58)  评论(0编辑  收藏  举报