run gofmt

This commit is contained in:
Cadey Ratio 2017-07-15 13:50:10 -07:00
parent edf576cd33
commit 40a5e952d2
10 changed files with 367 additions and 372 deletions

33
api.go
View File

@ -36,13 +36,13 @@ func (conn *Connection) rqliteApiGet(apiOp apiOperation) ([]byte, error) {
trace("%s: rqliteApiGet() called", conn.ID) trace("%s: rqliteApiGet() called", conn.ID)
// only api_STATUS now - maybe someday BACKUP // only api_STATUS now - maybe someday BACKUP
if ( apiOp != api_STATUS ) { if apiOp != api_STATUS {
return responseBody, errors.New("rqliteApiGet() called for invalid api operation") return responseBody, errors.New("rqliteApiGet() called for invalid api operation")
} }
// just to be safe, check this // just to be safe, check this
peersToTry := conn.cluster.makePeerList() peersToTry := conn.cluster.makePeerList()
if ( len(peersToTry) < 1 ) { if len(peersToTry) < 1 {
return responseBody, errors.New("I don't have any cluster info") return responseBody, errors.New("I don't have any cluster info")
} }
trace("%s: I have a peer list %d peers long", conn.ID, len(peersToTry)) trace("%s: I have a peer list %d peers long", conn.ID, len(peersToTry))
@ -57,7 +57,7 @@ PeerLoop:
// docs say default GET policy is up to 10 follows automatically // docs say default GET policy is up to 10 follows automatically
url := conn.assembleURL(api_STATUS, peerToTry) url := conn.assembleURL(api_STATUS, peerToTry)
req, err := http.NewRequest("GET", url, nil) req, err := http.NewRequest("GET", url, nil)
if ( err != nil ) { if err != nil {
trace("%s: got error '%s' doing http.NewRequest", conn.ID, err.Error()) trace("%s: got error '%s' doing http.NewRequest", conn.ID, err.Error())
failureLog = append(failureLog, fmt.Sprintf("%s failed due to %s", url, err.Error())) failureLog = append(failureLog, fmt.Sprintf("%s failed due to %s", url, err.Error()))
continue PeerLoop continue PeerLoop
@ -67,7 +67,7 @@ PeerLoop:
client := &http.Client{} client := &http.Client{}
client.Timeout = time.Duration(conn.timeout) * time.Second client.Timeout = time.Duration(conn.timeout) * time.Second
response, err := client.Do(req) response, err := client.Do(req)
if ( err != nil ) { if err != nil {
trace("%s: got error '%s' doing client.Do", conn.ID, err.Error()) trace("%s: got error '%s' doing client.Do", conn.ID, err.Error())
failureLog = append(failureLog, fmt.Sprintf("%s failed due to %s", url, err.Error())) failureLog = append(failureLog, fmt.Sprintf("%s failed due to %s", url, err.Error()))
continue PeerLoop continue PeerLoop
@ -75,13 +75,13 @@ PeerLoop:
defer response.Body.Close() defer response.Body.Close()
trace("%s: client.Do() OK") trace("%s: client.Do() OK")
responseBody, err := ioutil.ReadAll(response.Body) responseBody, err := ioutil.ReadAll(response.Body)
if ( err != nil ) { if err != nil {
trace("%s: got error '%s' doing ioutil.ReadAll", conn.ID, err.Error()) trace("%s: got error '%s' doing ioutil.ReadAll", conn.ID, err.Error())
failureLog = append(failureLog, fmt.Sprintf("%s failed due to %s", url, err.Error())) failureLog = append(failureLog, fmt.Sprintf("%s failed due to %s", url, err.Error()))
continue PeerLoop continue PeerLoop
} }
trace("%s: ioutil.ReadAll() OK") trace("%s: ioutil.ReadAll() OK")
if ( response.Status != "200 OK" ) { if response.Status != "200 OK" {
trace("%s: got code %s", conn.ID, response.Status) trace("%s: got code %s", conn.ID, response.Status)
failureLog = append(failureLog, fmt.Sprintf("%s failed, got: %s", url, response.Status)) failureLog = append(failureLog, fmt.Sprintf("%s failed, got: %s", url, response.Status))
continue PeerLoop continue PeerLoop
@ -117,7 +117,7 @@ PeerLoop:
func (conn *Connection) rqliteApiPost(apiOp apiOperation, sqlStatements []string) ([]byte, error) { func (conn *Connection) rqliteApiPost(apiOp apiOperation, sqlStatements []string) ([]byte, error) {
var responseBody []byte var responseBody []byte
switch (apiOp) { switch apiOp {
case api_QUERY: case api_QUERY:
trace("%s: rqliteApiGet() post called for a QUERY of %d statements", conn.ID, len(sqlStatements)) trace("%s: rqliteApiGet() post called for a QUERY of %d statements", conn.ID, len(sqlStatements))
case api_WRITE: case api_WRITE:
@ -130,11 +130,13 @@ func (conn *Connection) rqliteApiPost (apiOp apiOperation, sqlStatements []strin
// case of api_STATUS but doesn't hurt // case of api_STATUS but doesn't hurt
jStatements, err := json.Marshal(sqlStatements) jStatements, err := json.Marshal(sqlStatements)
if ( err != nil ) { return nil, err } if err != nil {
return nil, err
}
// just to be safe, check this // just to be safe, check this
peersToTry := conn.cluster.makePeerList() peersToTry := conn.cluster.makePeerList()
if ( len(peersToTry) < 1 ) { if len(peersToTry) < 1 {
return responseBody, errors.New("I don't have any cluster info") return responseBody, errors.New("I don't have any cluster info")
} }
@ -151,10 +153,10 @@ PeerLoop:
responseStatus := "Haven't Tried Yet" responseStatus := "Haven't Tried Yet"
var url string var url string
for ( responseStatus == "Haven't Tried Yet" || responseStatus == "301 Moved Permanently" ) { for responseStatus == "Haven't Tried Yet" || responseStatus == "301 Moved Permanently" {
url = conn.assembleURL(apiOp, peer) url = conn.assembleURL(apiOp, peer)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jStatements)) req, err := http.NewRequest("POST", url, bytes.NewBuffer(jStatements))
if ( err != nil ) { if err != nil {
trace("%s: got error '%s' doing http.NewRequest", conn.ID, err.Error()) trace("%s: got error '%s' doing http.NewRequest", conn.ID, err.Error())
failureLog = append(failureLog, fmt.Sprintf("%s failed due to %s", url, err.Error())) failureLog = append(failureLog, fmt.Sprintf("%s failed due to %s", url, err.Error()))
continue PeerLoop continue PeerLoop
@ -162,25 +164,25 @@ PeerLoop:
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
client := &http.Client{} client := &http.Client{}
response, err := client.Do(req) response, err := client.Do(req)
if ( err != nil ) { if err != nil {
trace("%s: got error '%s' doing client.Do", conn.ID, err.Error()) trace("%s: got error '%s' doing client.Do", conn.ID, err.Error())
failureLog = append(failureLog, fmt.Sprintf("%s failed due to %s", url, err.Error())) failureLog = append(failureLog, fmt.Sprintf("%s failed due to %s", url, err.Error()))
continue PeerLoop continue PeerLoop
} }
defer response.Body.Close() defer response.Body.Close()
responseBody, err = ioutil.ReadAll(response.Body) responseBody, err = ioutil.ReadAll(response.Body)
if ( err != nil ) { if err != nil {
trace("%s: got error '%s' doing ioutil.ReadAll", conn.ID, err.Error()) trace("%s: got error '%s' doing ioutil.ReadAll", conn.ID, err.Error())
failureLog = append(failureLog, fmt.Sprintf("%s failed due to %s", url, err.Error())) failureLog = append(failureLog, fmt.Sprintf("%s failed due to %s", url, err.Error()))
continue PeerLoop continue PeerLoop
} }
responseStatus = response.Status responseStatus = response.Status
if ( responseStatus == "301 Moved Permanently" ) { if responseStatus == "301 Moved Permanently" {
v := response.Header["Location"] v := response.Header["Location"]
failureLog = append(failureLog, fmt.Sprintf("%s redirected me to %s", url, v[0])) failureLog = append(failureLog, fmt.Sprintf("%s redirected me to %s", url, v[0]))
url = v[0] url = v[0]
continue PeerLoop continue PeerLoop
} else if ( responseStatus == "200 OK" ) { } else if responseStatus == "200 OK" {
trace("%s: api call OK, returning", conn.ID) trace("%s: api call OK, returning", conn.ID)
return responseBody, nil return responseBody, nil
} else { } else {
@ -199,4 +201,3 @@ PeerLoop:
} }
return responseBody, errors.New(stringBuffer.String()) return responseBody, errors.New(stringBuffer.String())
} }

View File

@ -37,7 +37,6 @@ import "strings"
* *****************************************************************/ * *****************************************************************/
type peer struct { type peer struct {
hostname string // hostname or "localhost" hostname string // hostname or "localhost"
port string // "4001" or port, only ever used as a string port string // "4001" or port, only ever used as a string
@ -105,13 +104,13 @@ func (rc *rqliteCluster) makePeerList() []peer {
func (conn *Connection) assembleURL(apiOp apiOperation, p peer) string { func (conn *Connection) assembleURL(apiOp apiOperation, p peer) string {
var stringBuffer bytes.Buffer var stringBuffer bytes.Buffer
if ( conn.wantsHTTPS == true ) { if conn.wantsHTTPS == true {
stringBuffer.WriteString("https") stringBuffer.WriteString("https")
} else { } else {
stringBuffer.WriteString("http") stringBuffer.WriteString("http")
} }
stringBuffer.WriteString("://") stringBuffer.WriteString("://")
if ( conn.username != "" && conn.password != "" ) { if conn.username != "" && conn.password != "" {
stringBuffer.WriteString(conn.username) stringBuffer.WriteString(conn.username)
stringBuffer.WriteString(":") stringBuffer.WriteString(":")
stringBuffer.WriteString(conn.password) stringBuffer.WriteString(conn.password)
@ -130,7 +129,7 @@ func (conn *Connection) assembleURL(apiOp apiOperation, p peer) string {
stringBuffer.WriteString("/db/execute") stringBuffer.WriteString("/db/execute")
} }
if ( apiOp == api_QUERY || apiOp == api_WRITE ) { if apiOp == api_QUERY || apiOp == api_WRITE {
stringBuffer.WriteString("?timings&transaction&level=") stringBuffer.WriteString("?timings&transaction&level=")
stringBuffer.WriteString(consistencyLevelNames[conn.consistencyLevel]) stringBuffer.WriteString(consistencyLevelNames[conn.consistencyLevel])
} }
@ -167,12 +166,16 @@ func (conn *Connection) updateClusterInfo() error {
rc.conn = conn rc.conn = conn
responseBody, err := conn.rqliteApiGet(api_STATUS) responseBody, err := conn.rqliteApiGet(api_STATUS)
if ( err != nil ) { return err } if err != nil {
return err
}
trace("%s: updateClusterInfo() back from api call OK", conn.ID) trace("%s: updateClusterInfo() back from api call OK", conn.ID)
sections := make(map[string]interface{}) sections := make(map[string]interface{})
err = json.Unmarshal(responseBody, &sections) err = json.Unmarshal(responseBody, &sections)
if ( err != nil ) { return err } if err != nil {
return err
}
sMap := sections["store"].(map[string]interface{}) sMap := sections["store"].(map[string]interface{})
leaderRaftAddr := sMap["leader"].(string) leaderRaftAddr := sMap["leader"].(string)
trace("%s: leader from store section is %s", conn.ID, leaderRaftAddr) trace("%s: leader from store section is %s", conn.ID, leaderRaftAddr)
@ -194,7 +197,7 @@ func (conn *Connection) updateClusterInfo() error {
p.port = parts[1] p.port = parts[1]
// so is this the leader? // so is this the leader?
if ( leaderRaftAddr == raftAddr ) { if leaderRaftAddr == raftAddr {
trace("%s: found leader at %s", conn.ID, httpAddr) trace("%s: found leader at %s", conn.ID, httpAddr)
rc.leader = p rc.leader = p
} else { } else {
@ -202,7 +205,7 @@ func (conn *Connection) updateClusterInfo() error {
} }
} }
if ( rc.leader.hostname == "" ) { if rc.leader.hostname == "" {
return errors.New("could not determine leader from API status call") return errors.New("could not determine leader from API status call")
} }
@ -218,4 +221,3 @@ func (conn *Connection) updateClusterInfo() error {
return nil return nil
} }

View File

@ -9,31 +9,30 @@ func TestInitCluster(t *testing.T) {
TraceOn(os.Stderr) TraceOn(os.Stderr)
t.Logf("trying Open") t.Logf("trying Open")
conn, err := Open(testUrl()) conn, err := Open(testUrl())
if ( err != nil ) { if err != nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fatal(err) t.Fatal(err)
} }
l, err := conn.Leader() l, err := conn.Leader()
if ( err != nil ) { if err != nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
if ( len(l) < 1 ) { if len(l) < 1 {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
p, err := conn.Peers() p, err := conn.Peers()
if ( err != nil ) { if err != nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
if ( len(p) < 1 ) { if len(p) < 1 {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
} }

43
conn.go
View File

@ -49,7 +49,6 @@ var wantsTrace bool
*/ */
type Connection struct { type Connection struct {
cluster rqliteCluster cluster rqliteCluster
/* /*
@ -86,7 +85,7 @@ func (conn *Connection) Close() {
* *****************************************************************/ * *****************************************************************/
func (conn *Connection) ConsistencyLevel() (string, error) { func (conn *Connection) ConsistencyLevel() (string, error) {
if ( conn.hasBeenClosed) { if conn.hasBeenClosed {
return "", errClosed return "", errClosed
} }
return consistencyLevelNames[conn.consistencyLevel], nil return consistencyLevelNames[conn.consistencyLevel], nil
@ -99,12 +98,12 @@ func (conn *Connection) ConsistencyLevel() (string, error) {
* *****************************************************************/ * *****************************************************************/
func (conn *Connection) Leader() (string, error) { func (conn *Connection) Leader() (string, error) {
if ( conn.hasBeenClosed) { if conn.hasBeenClosed {
return "", errClosed return "", errClosed
} }
trace("%s: Leader(), calling updateClusterInfo()", conn.ID) trace("%s: Leader(), calling updateClusterInfo()", conn.ID)
err := conn.updateClusterInfo() err := conn.updateClusterInfo()
if ( err != nil ) { if err != nil {
trace("%s: Leader() got error from updateClusterInfo(): %s", conn.ID, err.Error()) trace("%s: Leader() got error from updateClusterInfo(): %s", conn.ID, err.Error())
return "", err return "", err
} else { } else {
@ -120,7 +119,7 @@ func (conn *Connection) Leader() (string, error) {
* *****************************************************************/ * *****************************************************************/
func (conn *Connection) Peers() ([]string, error) { func (conn *Connection) Peers() ([]string, error) {
if ( conn.hasBeenClosed) { if conn.hasBeenClosed {
var ans []string var ans []string
return ans, errClosed return ans, errClosed
} }
@ -128,7 +127,7 @@ func (conn *Connection) Peers() ([]string, error) {
trace("%s: Peers(), calling updateClusterInfo()", conn.ID) trace("%s: Peers(), calling updateClusterInfo()", conn.ID)
err := conn.updateClusterInfo() err := conn.updateClusterInfo()
if ( err != nil ) { if err != nil {
trace("%s: Peers() got error from updateClusterInfo(): %s", conn.ID, err.Error()) trace("%s: Peers() got error from updateClusterInfo(): %s", conn.ID, err.Error())
return plist, err return plist, err
} else { } else {
@ -148,11 +147,11 @@ func (conn *Connection) Peers() ([]string, error) {
* *****************************************************************/ * *****************************************************************/
func (conn *Connection) SetConsistencyLevel(levelDesired string) error { func (conn *Connection) SetConsistencyLevel(levelDesired string) error {
if ( conn.hasBeenClosed) { if conn.hasBeenClosed {
return errClosed return errClosed
} }
_, ok := consistencyLevels[levelDesired] _, ok := consistencyLevels[levelDesired]
if ( ok ) { if ok {
conn.consistencyLevel = consistencyLevels[levelDesired] conn.consistencyLevel = consistencyLevels[levelDesired]
return nil return nil
} }
@ -204,21 +203,21 @@ func (conn *Connection) initConnection(url string) error {
// do some sanity checks. You know users. // do some sanity checks. You know users.
if ( len(url) < 7 ) { if len(url) < 7 {
return errors.New("url specified is impossibly short") return errors.New("url specified is impossibly short")
} }
if ( strings.HasPrefix(url,"http") == false ) { if strings.HasPrefix(url, "http") == false {
return errors.New("url does not start with 'http'") return errors.New("url does not start with 'http'")
} }
u, err := nurl.Parse(url) u, err := nurl.Parse(url)
if ( err != nil ) { if err != nil {
return err return err
} }
trace("%s: net.url.Parse() OK", conn.ID) trace("%s: net.url.Parse() OK", conn.ID)
if ( u.Scheme == "https" ) { if u.Scheme == "https" {
conn.wantsHTTPS = true conn.wantsHTTPS = true
} }
@ -233,27 +232,27 @@ func (conn *Connection) initConnection(url string) error {
// not guaranteed, so test if set // not guaranteed, so test if set
pass, isset := u.User.Password() pass, isset := u.User.Password()
if ( isset ) { if isset {
conn.password = pass conn.password = pass
} else { } else {
conn.password = "" conn.password = ""
} }
} }
if ( u.Host == "" ) { if u.Host == "" {
conn.cluster.leader.hostname = "localhost" conn.cluster.leader.hostname = "localhost"
} else { } else {
conn.cluster.leader.hostname = u.Host conn.cluster.leader.hostname = u.Host
} }
if ( u.Host == "" ) { if u.Host == "" {
conn.cluster.leader.hostname = "localhost" conn.cluster.leader.hostname = "localhost"
conn.cluster.leader.port = "4001" conn.cluster.leader.port = "4001"
} else { } else {
// SplitHostPort() should only return an error if there is no host port. // SplitHostPort() should only return an error if there is no host port.
// I think. // I think.
h, p, err := net.SplitHostPort(u.Host) h, p, err := net.SplitHostPort(u.Host)
if ( err != nil ) { if err != nil {
conn.cluster.leader.hostname = u.Host conn.cluster.leader.hostname = u.Host
} else { } else {
conn.cluster.leader.hostname = h conn.cluster.leader.hostname = h
@ -271,12 +270,12 @@ func (conn *Connection) initConnection(url string) error {
// default // default
conn.consistencyLevel = cl_WEAK conn.consistencyLevel = cl_WEAK
if ( u.RawQuery != "" ) { if u.RawQuery != "" {
if ( u.RawQuery == "level=weak") { if u.RawQuery == "level=weak" {
// that's ok but nothing to do // that's ok but nothing to do
} else if ( u.RawQuery == "level=strong" ) { } else if u.RawQuery == "level=strong" {
conn.consistencyLevel = cl_STRONG conn.consistencyLevel = cl_STRONG
} else if ( u.RawQuery == "level=none" ) { // the fools! } else if u.RawQuery == "level=none" { // the fools!
conn.consistencyLevel = cl_NONE conn.consistencyLevel = cl_NONE
} else { } else {
return errors.New("don't know what to do with this query: " + u.RawQuery) return errors.New("don't know what to do with this query: " + u.RawQuery)
@ -284,7 +283,7 @@ func (conn *Connection) initConnection(url string) error {
} }
trace("%s: parseDefaultPeer() is done:", conn.ID) trace("%s: parseDefaultPeer() is done:", conn.ID)
if ( conn.wantsHTTPS == true ) { if conn.wantsHTTPS == true {
trace("%s: %s -> %s", conn.ID, "wants https?", "yes") trace("%s: %s -> %s", conn.ID, "wants https?", "yes")
} else { } else {
trace("%s: %s -> %s", conn.ID, "wants https?", "no") trace("%s: %s -> %s", conn.ID, "wants https?", "no")
@ -299,5 +298,3 @@ func (conn *Connection) initConnection(url string) error {
return nil return nil
} }

View File

@ -33,16 +33,19 @@ import "strings"
* *****************************************************************/ * *****************************************************************/
type consistencyLevel int type consistencyLevel int
const ( const (
cl_NONE consistencyLevel = iota cl_NONE consistencyLevel = iota
cl_WEAK cl_WEAK
cl_STRONG cl_STRONG
) )
// used in several places, actually // used in several places, actually
var consistencyLevelNames map[consistencyLevel]string var consistencyLevelNames map[consistencyLevel]string
var consistencyLevels map[string]consistencyLevel var consistencyLevels map[string]consistencyLevel
type apiOperation int type apiOperation int
const ( const (
api_QUERY apiOperation = iota api_QUERY apiOperation = iota
api_STATUS api_STATUS
@ -70,7 +73,6 @@ func init() {
} }
/* ***************************************************************** /* *****************************************************************
Open() creates and returns a "connection" to rqlite. Open() creates and returns a "connection" to rqlite.
@ -107,7 +109,7 @@ func Open(connURL string) (Connection, error) {
// parse the URL given // parse the URL given
err = conn.initConnection(connURL) err = conn.initConnection(connURL)
if ( err != nil ) { if err != nil {
return conn, err return conn, err
} }
@ -146,7 +148,7 @@ func Open(connURL string) (Connection, error) {
func trace(pattern string, args ...interface{}) { func trace(pattern string, args ...interface{}) {
// don't do the probably expensive Sprintf() if not needed // don't do the probably expensive Sprintf() if not needed
if ( wantsTrace == false ) { if wantsTrace == false {
return return
} }

View File

@ -91,7 +91,7 @@ QueryOne() is a convenience method that wraps Query() into a single-statement
method. method.
*/ */
func (conn *Connection) QueryOne(sqlStatement string) (qr QueryResult, err error) { func (conn *Connection) QueryOne(sqlStatement string) (qr QueryResult, err error) {
if ( conn.hasBeenClosed) { if conn.hasBeenClosed {
qr.Err = errClosed qr.Err = errClosed
return qr, errClosed return qr, errClosed
} }
@ -109,7 +109,7 @@ It takes an array of SQL statements and executes them in a single transaction, r
func (conn *Connection) Query(sqlStatements []string) (results []QueryResult, err error) { func (conn *Connection) Query(sqlStatements []string) (results []QueryResult, err error) {
results = make([]QueryResult, 0) results = make([]QueryResult, 0)
if ( conn.hasBeenClosed) { if conn.hasBeenClosed {
var errResult QueryResult var errResult QueryResult
errResult.Err = errClosed errResult.Err = errClosed
results = append(results, errResult) results = append(results, errResult)
@ -119,7 +119,7 @@ func (conn *Connection) Query(sqlStatements []string) (results []QueryResult, er
// if we get an error POSTing, that's a showstopper // if we get an error POSTing, that's a showstopper
response, err := conn.rqliteApiPost(api_QUERY, sqlStatements) response, err := conn.rqliteApiPost(api_QUERY, sqlStatements)
if ( err != nil ) { if err != nil {
trace("%s: rqliteApiCall() ERROR: %s", conn.ID, err.Error()) trace("%s: rqliteApiCall() ERROR: %s", conn.ID, err.Error())
var errResult QueryResult var errResult QueryResult
errResult.Err = err errResult.Err = err
@ -131,7 +131,7 @@ func (conn *Connection) Query(sqlStatements []string) (results []QueryResult, er
// if we get an error Unmarshaling, that's a showstopper // if we get an error Unmarshaling, that's a showstopper
var sections map[string]interface{} var sections map[string]interface{}
err = json.Unmarshal(response, &sections) err = json.Unmarshal(response, &sections)
if ( err != nil ) { if err != nil {
trace("%s: json.Unmarshal() ERROR: %s", conn.ID, err.Error()) trace("%s: json.Unmarshal() ERROR: %s", conn.ID, err.Error())
var errResult QueryResult var errResult QueryResult
errResult.Err = err errResult.Err = err
@ -178,7 +178,7 @@ func (conn *Connection) Query(sqlStatements []string) (results []QueryResult, er
} }
// and values are an array of arrays // and values are an array of arrays
if ( thisResult["values"] != nil ) { if thisResult["values"] != nil {
thisQR.values = thisResult["values"].([]interface{}) thisQR.values = thisResult["values"].([]interface{})
} else { } else {
trace("%s: fyi, no values this query", conn.ID) trace("%s: fyi, no values this query", conn.ID)
@ -192,7 +192,7 @@ func (conn *Connection) Query(sqlStatements []string) (results []QueryResult, er
trace("%s: finished parsing, returning %d results", conn.ID, len(results)) trace("%s: finished parsing, returning %d results", conn.ID, len(results))
if ( numStatementErrors > 0 ) { if numStatementErrors > 0 {
return results, errors.New(fmt.Sprintf("there were %d statement errors", numStatementErrors)) return results, errors.New(fmt.Sprintf("there were %d statement errors", numStatementErrors))
} else { } else {
return results, nil return results, nil
@ -261,7 +261,7 @@ func (qr *QueryResult) Map() (map[string]interface{}, error) {
trace("%s: Map() called for row %d", qr.conn.ID, qr.rowNumber) trace("%s: Map() called for row %d", qr.conn.ID, qr.rowNumber)
ans := make(map[string]interface{}) ans := make(map[string]interface{})
if ( qr.rowNumber == -1 ) { if qr.rowNumber == -1 {
return ans, errors.New("you need to Next() before you Map(), sorry, it's complicated") return ans, errors.New("you need to Next() before you Map(), sorry, it's complicated")
} }
@ -293,7 +293,7 @@ A common idiom:
} }
*/ */
func (qr *QueryResult) Next() bool { func (qr *QueryResult) Next() bool {
if ( qr.rowNumber >= int64(len(qr.values) - 1 )) { if qr.rowNumber >= int64(len(qr.values)-1) {
return false return false
} }
@ -349,11 +349,11 @@ since sqlite does not support them.
func (qr *QueryResult) Scan(dest ...interface{}) error { func (qr *QueryResult) Scan(dest ...interface{}) error {
trace("%s: Scan() called for %d vars", qr.conn.ID, len(dest)) trace("%s: Scan() called for %d vars", qr.conn.ID, len(dest))
if ( qr.rowNumber == -1 ) { if qr.rowNumber == -1 {
return errors.New("you need to Next() before you Scan(), sorry, it's complicated") return errors.New("you need to Next() before you Scan(), sorry, it's complicated")
} }
if ( len(dest) != len(qr.columns) ) { if len(dest) != len(qr.columns) {
return errors.New(fmt.Sprintf("expected %d columns but got %d vars\n", len(qr.columns), len(dest))) return errors.New(fmt.Sprintf("expected %d columns but got %d vars\n", len(qr.columns), len(dest)))
} }
@ -393,4 +393,3 @@ This info may additionally conflict with the reality that your data is being JSO
func (qr *QueryResult) Types() []string { func (qr *QueryResult) Types() []string {
return qr.types return qr.types
} }

View File

@ -11,21 +11,21 @@ func TestQueryOne (t *testing.T) {
t.Logf("trying Open") t.Logf("trying Open")
conn, err := Open(testUrl()) conn, err := Open(testUrl())
if ( err != nil ) { if err != nil {
t.Logf("--> FATAL") t.Logf("--> FATAL")
t.Fatal() t.Fatal()
} }
t.Logf("trying WriteOne DROP") t.Logf("trying WriteOne DROP")
wr, err = conn.WriteOne("DROP TABLE IF EXISTS " + testTableName()) wr, err = conn.WriteOne("DROP TABLE IF EXISTS " + testTableName())
if ( err != nil ) { if err != nil {
t.Logf("--> FATAL") t.Logf("--> FATAL")
t.Fatal() t.Fatal()
} }
t.Logf("trying WriteOne CREATE") t.Logf("trying WriteOne CREATE")
wr, err = conn.WriteOne("CREATE TABLE " + testTableName() + " (id integer, name text)") wr, err = conn.WriteOne("CREATE TABLE " + testTableName() + " (id integer, name text)")
if ( err != nil ) { if err != nil {
t.Logf("--> FATAL") t.Logf("--> FATAL")
t.Fatal() t.Fatal()
} }
@ -38,32 +38,32 @@ func TestQueryOne (t *testing.T) {
s = append(s, "INSERT INTO "+testTableName()+" (id, name) VALUES ( 4, 'Ferengi' )") s = append(s, "INSERT INTO "+testTableName()+" (id, name) VALUES ( 4, 'Ferengi' )")
s = append(s, "INSERT INTO "+testTableName()+" (id, name) VALUES ( 5, 'Cardassian' )") s = append(s, "INSERT INTO "+testTableName()+" (id, name) VALUES ( 5, 'Cardassian' )")
wResults, err = conn.Write(s) wResults, err = conn.Write(s)
if ( err != nil ) { if err != nil {
t.Logf("--> FATAL") t.Logf("--> FATAL")
t.Fatal() t.Fatal()
} }
t.Logf("trying QueryOne") t.Logf("trying QueryOne")
qr, err = conn.QueryOne("SELECT name FROM " + testTableName() + " WHERE id > 3") qr, err = conn.QueryOne("SELECT name FROM " + testTableName() + " WHERE id > 3")
if ( err != nil ) { if err != nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
t.Logf("trying Next()") t.Logf("trying Next()")
na := qr.Next() na := qr.Next()
if ( na != true ) { if na != true {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
t.Logf("trying Map()") t.Logf("trying Map()")
r, err := qr.Map() r, err := qr.Map()
if ( err != nil ) { if err != nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
if ( r["name"].(string) != "Ferengi" ) { if r["name"].(string) != "Ferengi" {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
@ -72,29 +72,29 @@ func TestQueryOne (t *testing.T) {
var id int64 var id int64
var name string var name string
err = qr.Scan(&id, &name) err = qr.Scan(&id, &name)
if ( err == nil ) { if err == nil {
t.Logf("--> FAILED (%s)", err.Error()) t.Logf("--> FAILED (%s)", err.Error())
t.Fail() t.Fail()
} }
err = qr.Scan(&name) err = qr.Scan(&name)
if ( err != nil ) { if err != nil {
t.Logf("--> FAILED (%s)", err.Error()) t.Logf("--> FAILED (%s)", err.Error())
t.Fail() t.Fail()
} }
if ( name != "Ferengi" ) { if name != "Ferengi" {
t.Logf("--> FAILED, name should be 'Ferengi' but it's '%s'", name) t.Logf("--> FAILED, name should be 'Ferengi' but it's '%s'", name)
t.Fail() t.Fail()
} }
qr.Next() qr.Next()
err = qr.Scan(&name) err = qr.Scan(&name)
if ( name != "Cardassian" ) { if name != "Cardassian" {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
t.Logf("trying WriteOne DROP") t.Logf("trying WriteOne DROP")
wr, err = conn.WriteOne("DROP TABLE IF EXISTS " + testTableName() + "") wr, err = conn.WriteOne("DROP TABLE IF EXISTS " + testTableName() + "")
if ( err != nil ) { if err != nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
@ -104,7 +104,7 @@ func TestQueryOne (t *testing.T) {
t.Logf("trying WriteOne after Close") t.Logf("trying WriteOne after Close")
wr, err = conn.WriteOne("DROP TABLE IF EXISTS " + testTableName() + "") wr, err = conn.WriteOne("DROP TABLE IF EXISTS " + testTableName() + "")
if ( err == nil ) { if err == nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
@ -115,7 +115,7 @@ func TestQueryOne (t *testing.T) {
t1 = append(t1, "DROP TABLE IF EXISTS "+testTableName()+"") t1 = append(t1, "DROP TABLE IF EXISTS "+testTableName()+"")
t1 = append(t1, "DROP TABLE IF EXISTS "+testTableName()+"") t1 = append(t1, "DROP TABLE IF EXISTS "+testTableName()+"")
wResults, err = conn.Write(t1) wResults, err = conn.Write(t1)
if ( err == nil ) { if err == nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
@ -123,7 +123,7 @@ func TestQueryOne (t *testing.T) {
t.Logf("trying QueryOne after Close") t.Logf("trying QueryOne after Close")
qr, err = conn.QueryOne("SELECT id FROM " + testTableName() + "") qr, err = conn.QueryOne("SELECT id FROM " + testTableName() + "")
if ( err == nil ) { if err == nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
@ -135,12 +135,10 @@ func TestQueryOne (t *testing.T) {
t2 = append(t2, "SELECT name FROM "+testTableName()+"") t2 = append(t2, "SELECT name FROM "+testTableName()+"")
t2 = append(t2, "SELECT id,name FROM "+testTableName()+"") t2 = append(t2, "SELECT id,name FROM "+testTableName()+"")
qResults, err = conn.Query(t2) qResults, err = conn.Query(t2)
if ( err == nil ) { if err == nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
_ = qResults _ = qResults
} }

View File

@ -8,7 +8,7 @@ import "os"
func testUrl() string { func testUrl() string {
url := os.Getenv("GORQLITE_TEST_URL") url := os.Getenv("GORQLITE_TEST_URL")
if ( url == "" ) { if url == "" {
url = "http://" url = "http://"
} }
return url return url
@ -16,10 +16,8 @@ func testUrl() string {
func testTableName() string { func testTableName() string {
tableName := os.Getenv("GORQLITE_TEST_TABLE") tableName := os.Getenv("GORQLITE_TEST_TABLE")
if ( tableName == "" ) { if tableName == "" {
tableName = "gorqlite_test" tableName = "gorqlite_test"
} }
return tableName return tableName
} }

View File

@ -58,7 +58,7 @@ method.
*/ */
func (conn *Connection) WriteOne(sqlStatement string) (wr WriteResult, err error) { func (conn *Connection) WriteOne(sqlStatement string) (wr WriteResult, err error) {
if ( conn.hasBeenClosed) { if conn.hasBeenClosed {
wr.Err = errClosed wr.Err = errClosed
return wr, errClosed return wr, errClosed
} }
@ -80,7 +80,7 @@ Write() returns an error if one is encountered during its operation. If it's so
func (conn *Connection) Write(sqlStatements []string) (results []WriteResult, err error) { func (conn *Connection) Write(sqlStatements []string) (results []WriteResult, err error) {
results = make([]WriteResult, 0) results = make([]WriteResult, 0)
if ( conn.hasBeenClosed) { if conn.hasBeenClosed {
var errResult WriteResult var errResult WriteResult
errResult.Err = errClosed errResult.Err = errClosed
results = append(results, errResult) results = append(results, errResult)
@ -90,7 +90,7 @@ func (conn *Connection) Write(sqlStatements []string) (results []WriteResult, er
trace("%s: Write() for %d statements", conn.ID, len(sqlStatements)) trace("%s: Write() for %d statements", conn.ID, len(sqlStatements))
response, err := conn.rqliteApiPost(api_WRITE, sqlStatements) response, err := conn.rqliteApiPost(api_WRITE, sqlStatements)
if ( err != nil ) { if err != nil {
trace("%s: rqliteApiCall() ERROR: %s", conn.ID, err.Error()) trace("%s: rqliteApiCall() ERROR: %s", conn.ID, err.Error())
var errResult WriteResult var errResult WriteResult
errResult.Err = err errResult.Err = err
@ -101,7 +101,7 @@ func (conn *Connection) Write(sqlStatements []string) (results []WriteResult, er
var sections map[string]interface{} var sections map[string]interface{}
err = json.Unmarshal(response, &sections) err = json.Unmarshal(response, &sections)
if ( err != nil ) { if err != nil {
trace("%s: json.Unmarshal() ERROR: %s", conn.ID, err.Error()) trace("%s: json.Unmarshal() ERROR: %s", conn.ID, err.Error())
var errResult WriteResult var errResult WriteResult
errResult.Err = err errResult.Err = err
@ -151,7 +151,7 @@ func (conn *Connection) Write(sqlStatements []string) (results []WriteResult, er
trace("%s: finished parsing, returning %d results", conn.ID, len(results)) trace("%s: finished parsing, returning %d results", conn.ID, len(results))
if ( numStatementErrors > 0 ) { if numStatementErrors > 0 {
return results, errors.New(fmt.Sprintf("there were %d statement errors", numStatementErrors)) return results, errors.New(fmt.Sprintf("there were %d statement errors", numStatementErrors))
} else { } else {
return results, nil return results, nil
@ -176,4 +176,3 @@ type WriteResult struct {
LastInsertID int64 // if relevant, otherwise zero value LastInsertID int64 // if relevant, otherwise zero value
conn *Connection conn *Connection
} }

View File

@ -1,6 +1,7 @@
package gorqlite package gorqlite
import "testing" import "testing"
// import "os" // import "os"
func TestWriteOne(t *testing.T) { func TestWriteOne(t *testing.T) {
@ -9,48 +10,48 @@ func TestWriteOne (t *testing.T) {
t.Logf("trying Open") t.Logf("trying Open")
conn, err := Open(testUrl()) conn, err := Open(testUrl())
if ( err != nil ) { if err != nil {
t.Logf("--> FATAL") t.Logf("--> FATAL")
t.Fatal(err) t.Fatal(err)
} }
t.Logf("trying WriteOne DROP") t.Logf("trying WriteOne DROP")
wr, err = conn.WriteOne("DROP TABLE IF EXISTS " + testTableName() + "") wr, err = conn.WriteOne("DROP TABLE IF EXISTS " + testTableName() + "")
if ( err != nil ) { if err != nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
t.Logf("trying WriteOne CTHULHU (should fail, bad SQL)") t.Logf("trying WriteOne CTHULHU (should fail, bad SQL)")
wr, err = conn.WriteOne("CTHULHU") wr, err = conn.WriteOne("CTHULHU")
if ( err == nil ) { if err == nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
t.Logf("trying WriteOne CREATE") t.Logf("trying WriteOne CREATE")
wr, err = conn.WriteOne("CREATE TABLE " + testTableName() + " (id integer, name text)") wr, err = conn.WriteOne("CREATE TABLE " + testTableName() + " (id integer, name text)")
if ( err != nil ) { if err != nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
t.Logf("trying WriteOne INSERT") t.Logf("trying WriteOne INSERT")
wr, err = conn.WriteOne("INSERT INTO " + testTableName() + " (id, name) VALUES ( 1, 'aaa bbb ccc' )") wr, err = conn.WriteOne("INSERT INTO " + testTableName() + " (id, name) VALUES ( 1, 'aaa bbb ccc' )")
if ( err != nil ) { if err != nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
t.Logf("checking WriteOne RowsAffected") t.Logf("checking WriteOne RowsAffected")
if ( wr.RowsAffected != 1 ) { if wr.RowsAffected != 1 {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
t.Logf("trying WriteOne DROP") t.Logf("trying WriteOne DROP")
wr, err = conn.WriteOne("DROP TABLE IF EXISTS " + testTableName() + "") wr, err = conn.WriteOne("DROP TABLE IF EXISTS " + testTableName() + "")
if ( err != nil ) { if err != nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
@ -64,7 +65,7 @@ func TestWrite (t *testing.T) {
t.Logf("trying Open") t.Logf("trying Open")
conn, err := Open(testUrl()) conn, err := Open(testUrl())
if ( err != nil ) { if err != nil {
t.Logf("--> FATAL") t.Logf("--> FATAL")
t.Fatal(err) t.Fatal(err)
} }
@ -74,7 +75,7 @@ func TestWrite (t *testing.T) {
s = append(s, "DROP TABLE IF EXISTS "+testTableName()+"") s = append(s, "DROP TABLE IF EXISTS "+testTableName()+"")
s = append(s, "CREATE TABLE "+testTableName()+" (id integer, name text)") s = append(s, "CREATE TABLE "+testTableName()+" (id integer, name text)")
results, err = conn.Write(s) results, err = conn.Write(s)
if ( err != nil ) { if err != nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
@ -86,11 +87,11 @@ func TestWrite (t *testing.T) {
s = append(s, "INSERT INTO "+testTableName()+" (id, name) VALUES ( 3, 'ggg hhh iii' )") s = append(s, "INSERT INTO "+testTableName()+" (id, name) VALUES ( 3, 'ggg hhh iii' )")
s = append(s, "INSERT INTO "+testTableName()+" (id, name) VALUES ( 4, 'jjj kkk lll' )") s = append(s, "INSERT INTO "+testTableName()+" (id, name) VALUES ( 4, 'jjj kkk lll' )")
results, err = conn.Write(s) results, err = conn.Write(s)
if ( err != nil ) { if err != nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
if ( len(results) != 4 ) { if len(results) != 4 {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
@ -99,10 +100,9 @@ func TestWrite (t *testing.T) {
s = make([]string, 0) s = make([]string, 0)
s = append(s, "DROP TABLE IF EXISTS "+testTableName()+"") s = append(s, "DROP TABLE IF EXISTS "+testTableName()+"")
results, err = conn.Write(s) results, err = conn.Write(s)
if ( err != nil ) { if err != nil {
t.Logf("--> FAILED") t.Logf("--> FAILED")
t.Fail() t.Fail()
} }
} }