Example #1
0
func (stmt Stmt) bind(args []driver.Value) error {
	if C.sqlite3_clear_bindings(stmt.stmt) != C.SQLITE_OK {
		return stmtError(stmt.stmt)
	}
	for i, arg := range args {
		r := C.int(-1)
		switch val := arg.(type) {
		case int64:
			r = C.sqlite3_bind_int64(stmt.stmt, C.int(i+1), C.sqlite3_int64(val))
		case float64:
			r = C.sqlite3_bind_double(stmt.stmt, C.int(i+1), C.double(val))
		case bool:
			if val {
				r = C.sqlite3_bind_int64(stmt.stmt, C.int(i+1), C.sqlite3_int64(1))
			} else {
				r = C.sqlite3_bind_int64(stmt.stmt, C.int(i+1), C.sqlite3_int64(0))
			}
		case nil:
			r = C.sqlite3_bind_null(stmt.stmt, C.int(i+1))
		case string:
			str := C.CString(val)
			defer C.free(unsafe.Pointer(str))
			l := C.int(C.strlen(str))
			r = C.bind_text(stmt.stmt, C.int(i+1), str, l)
		default:
			panic("unsupported type")
		}

		if r != C.SQLITE_OK {
			return stmtError(stmt.stmt)
		}
	}
	return nil
}
Example #2
0
// bind binds statement parameter i (starting at 1) to the value v. The
// parameter name is only used for error reporting.
func (s *Stmt) bind(i C.int, v interface{}, name string) error {
	if v == nil {
		return nil // Unbound parameters are NULL by default
	}
	var rc C.int
	switch v := v.(type) {
	case int:
		rc = C.sqlite3_bind_int64(s.stmt, i, C.sqlite3_int64(v))
	case int64:
		rc = C.sqlite3_bind_int64(s.stmt, i, C.sqlite3_int64(v))
	case float64:
		rc = C.sqlite3_bind_double(s.stmt, i, C.double(v))
	case bool:
		rc = C.sqlite3_bind_int64(s.stmt, i, C.sqlite3_int64(cBool(v)))
	case string:
		rc = C.bind_text(s.stmt, i, cStr(v), C.int(len(v)), 1)
	case []byte:
		rc = C.bind_blob(s.stmt, i, cBytes(v), C.int(len(v)), 1)
	case time.Time:
		rc = C.sqlite3_bind_int64(s.stmt, i, C.sqlite3_int64(v.Unix()))
	case RawString:
		rc = C.bind_text(s.stmt, i, cStr(string(v)), C.int(len(v)), 0)
	case RawBytes:
		rc = C.bind_blob(s.stmt, i, cBytes(v), C.int(len(v)), 0)
	case ZeroBlob:
		rc = C.sqlite3_bind_zeroblob(s.stmt, i, C.int(v))
	default:
		if name != "" {
			return pkgErr(MISUSE, "unsupported type for %s (%T)", name, v)
		}
		return pkgErr(MISUSE, "unsupported type at index %d (%T)", int(i-1), v)
	}
	if rc != OK {
		return libErr(rc, s.conn.db)
	}
	return nil
}