dousuohe5882 2015-06-24 23:26
浏览 215
已采纳

如何使用gorm从数据库中删除项目范围

Every time I run a gorm query to delete a range of rows from a table I get the following error.

(/home/gregf/code/go/src/github.com/gregf/gormtest/main.go:39)
[2015-06-24 18:55:56]  [0.34ms]  SELECT  id FROM "podcasts"

(/home/gregf/code/go/src/github.com/gregf/gormtest/main.go:50)
[2015-06-24 18:55:56]  near "LIMIT": syntax error

(/home/gregf/code/go/src/github.com/gregf/gormtest/main.go:50)
[2015-06-24 18:55:56]  [0.82ms]  DELETE FROM "episodes"  WHERE (podcast_id = '1') LIMIT 4 OFFSET 2
2015/06/24 18:55:56 &{{0 0   false } near "LIMIT": syntax error 0 <nil> 0xc20802c280 0xc20802c140 0xc20802f900 2 <nil> <nil> false  map[gorm:started_transaction0xc2080380c00xc20805a1c0:true] map[]}

Running the query in sqlite3 directly returns just fine

DELETE FROM "episodes"  WHERE (podcast_id = '1') LIMIT 4 OFFSET 2;
Run Time: real 0.000 user 0.000000 sys 0.000000

Example code

package main

import (
    "log"

    "github.com/jinzhu/gorm"
    _ "github.com/mattn/go-sqlite3"
)

type Podcast struct {
    Id       int
    Title    string
    RssUrl   string `sql:"unique_index"`
    Episodes []Episode
}

type Episode struct {
    Id         int
    PodcastID  int
    Title      string
    Url        string `sql:"unique_index"`
    Downloaded bool
    Guid       string `sql:"unique_index"`
}

func main() {
    db, err := gorm.Open("sqlite3", "cache.db")
    if err != nil {
        log.Fatal(err)
    }
    db.LogMode(true)

    db.CreateTable(&Podcast{})
    db.CreateTable(&Episode{})

    rows, err := db.Table("podcasts").Select("id").Rows()
    if err != nil {
        log.Fatal(err)
    }

    for rows.Next() {
        var podcastId int
        rows.Scan(&podcastId)
        err := db.Table("episodes").Where("podcast_id = ?", podcastId).
            Limit(4).
            Offset(2).
            Delete(Episode{})

        if err != nil {
            log.Printf("%s
", err)
        }
    }
}
  • 写回答

1条回答 默认 最新

  • dongtuoleng8624 2015-06-25 03:29
    关注

    Looks like it's a problem of sqlite3 driver. Please check this thread: How do you enable LIMIT for DELETE in SQLite?

    You need to pass flag SQLITE_ENABLE_UPDATE_DELETE_LIMIT to this driver somehow. Unfortunately, I have no idea how, because the driver uses "amalgamation" of SQLite source code and documentation says that you cannot use SQLITE_ENABLE_UPDATE_DELETE_LIMIT with it (https://www.sqlite.org/compile.html).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序