Implements Execer

This commit is contained in:
mattn 2013-09-09 10:44:44 +09:00
parent 73ea0ad09f
commit d4673cd31c
3 changed files with 59 additions and 14 deletions

View File

@ -17,17 +17,15 @@ func main() {
} }
defer db.Close() defer db.Close()
sqls := []string{ sql := `
"create table foo (id integer not null primary key, name text)", create table foo (id integer not null primary key, name text);
"delete from foo", delete from foo;
} `
for _, sql := range sqls {
_, err = db.Exec(sql) _, err = db.Exec(sql)
if err != nil { if err != nil {
log.Printf("%q: %s\n", err, sql) log.Printf("%q: %s\n", err, sql)
return return
} }
}
tx, err := db.Begin() tx, err := db.Begin()
if err != nil { if err != nil {

View File

@ -129,10 +129,36 @@ func (tx *SQLiteTx) Rollback() error {
return nil return nil
} }
// AutoCommit return which currently auto commit or not.
func (c *SQLiteConn) AutoCommit() bool { func (c *SQLiteConn) AutoCommit() bool {
return int(C.sqlite3_get_autocommit(c.db)) != 0 return int(C.sqlite3_get_autocommit(c.db)) != 0
} }
// Implements Execer
func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error) {
for {
println(query)
ds, err := c.Prepare(query)
if err != nil {
println("FOO1")
return nil, err
}
s := ds.(*SQLiteStmt)
na := s.NumInput()
res, err := s.Exec(args[:na])
args = args[na:]
s.Close()
if err != nil {
return nil, err
}
if s.t == "" {
return res, nil
}
s.Close()
query = s.t
}
}
func (c *SQLiteConn) exec(cmd string) error { func (c *SQLiteConn) exec(cmd string) error {
pcmd := C.CString(cmd) pcmd := C.CString(cmd)
defer C.free(unsafe.Pointer(pcmd)) defer C.free(unsafe.Pointer(pcmd))
@ -244,14 +270,14 @@ func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) {
pquery := C.CString(query) pquery := C.CString(query)
defer C.free(unsafe.Pointer(pquery)) defer C.free(unsafe.Pointer(pquery))
var s *C.sqlite3_stmt var s *C.sqlite3_stmt
var perror *C.char var tail *C.char
rv := C.sqlite3_prepare_v2(c.db, pquery, -1, &s, &perror) rv := C.sqlite3_prepare_v2(c.db, pquery, -1, &s, &tail)
if rv != C.SQLITE_OK { if rv != C.SQLITE_OK {
return nil, ErrNo(rv) return nil, ErrNo(rv)
} }
var t string var t string
if perror != nil && C.strlen(perror) > 0 { if tail != nil && C.strlen(tail) > 0 {
t = C.GoString(perror) t = strings.TrimSpace(C.GoString(tail))
} }
return &SQLiteStmt{c: c, s: s, t: t}, nil return &SQLiteStmt{c: c, s: s, t: t}, nil
} }

View File

@ -579,3 +579,24 @@ func TestTransaction(t *testing.T) {
t.Fatal("Expected failure to query") t.Fatal("Expected failure to query")
} }
} }
func TestExecer(t *testing.T) {
tempFilename := TempFilename()
db, err := sql.Open("sqlite3", tempFilename)
if err != nil {
t.Fatal("Failed to open database:", err)
}
defer os.Remove(tempFilename)
defer db.Close()
_, err = db.Exec(`
create table foo (id integer)");
insert into foo values(1);
insert into foo values(2);
insert into foo values(3);
`)
if err != nil {
t.Error("Failed to call db.Exec:", err)
}
}