【问题标题】:How to delete range of items from database with gorm如何使用gorm从数据库中删除项目范围
【发布时间】:2015-09-11 09:05:13
【问题描述】:

每次我运行 gorm 查询以从表中删除一系列行时,都会收到以下错误。

(/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[]}

在sqlite3中直接运行查询返回就好了

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

示例代码

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\n", err)
        }
    }
}

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    看起来是 sqlite3 驱动的问题。 请检查此线程:How do you enable LIMIT for DELETE in SQLite?

    您需要以某种方式将标志 SQLITE_ENABLE_UPDATE_DELETE_LIMIT 传递给此驱动程序。不幸的是,我不知道如何,因为驱动程序使用 SQLite 源代码的“合并”,并且文档说你不能使用 SQLITE_ENABLE_UPDATE_DELETE_LIMIT (https://www.sqlite.org/compile.html)。

    【讨论】:

    • 我不相信是这样的。如上所示,我可以在 sqlite3 中很好地运行查询。我只是在 gorm 中遇到了这个问题。
    • 你可能已经用这个标志构建了你的 sqlite3 客户端,但是 gorm 使用带有自己的 sqlite3 客户端的github.com/mattn/go-sqlite3 驱动程序:github.com/mattn/go-sqlite3/blob/master/sqlite3-binding.c
    • 感谢您的澄清。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多