Add errcheck linter (#238)

* Add errcheck linter

* Add config for 'fast' linters

* Fix errcheck lint stuff

* Fix errcheck lint
main
Erik Johnston 2017-09-20 10:59:19 +01:00 committed by Mark Haines
parent b91b3e729a
commit 8a36a7e89b
40 changed files with 186 additions and 98 deletions

15
linter-fast.json Normal file
View File

@ -0,0 +1,15 @@
{
"Vendor": true,
"Cyclo": 12,
"Deadline": "5m",
"Enable": [
"vetshadow",
"gotype",
"deadcode",
"gocyclo",
"ineffassign",
"gas",
"misspell",
"errcheck"
]
}

View File

@ -14,6 +14,7 @@
"ineffassign",
"gas",
"misspell",
"unparam"
"unparam",
"errcheck"
]
}

View File

@ -108,7 +108,7 @@ func (s *membershipStatements) selectMembershipsByLocalpart(
memberships = []authtypes.Membership{}
defer rows.Close()
defer rows.Close() // nolint: errcheck
for rows.Next() {
var m authtypes.Membership
m.Localpart = localpart

View File

@ -69,7 +69,10 @@ func BuildEvent(
authEvents := gomatrixserverlib.NewAuthEvents(nil)
for i := range queryRes.StateEvents {
authEvents.AddEvent(&queryRes.StateEvents[i])
err = authEvents.AddEvent(&queryRes.StateEvents[i])
if err != nil {
return nil, err
}
}
refs, err := eventsNeeded.AuthEventReferences(&authEvents)

View File

@ -25,7 +25,7 @@ import (
// UnmarshalJSONRequest into the given interface pointer. Returns an error JSON response if
// there was a problem unmarshalling. Calling this function consumes the request body.
func UnmarshalJSONRequest(req *http.Request, iface interface{}) *util.JSONResponse {
defer req.Body.Close()
defer req.Body.Close() // nolint: errcheck
if err := json.NewDecoder(req.Body).Decode(iface); err != nil {
// TODO: We may want to suppress the Error() return in production? It's useful when
// debugging because an error will be produced for both invalid/malformed JSON AND

View File

@ -52,7 +52,7 @@ func SaveAccountData(
return httputil.LogThenError(req, err)
}
defer req.Body.Close()
defer req.Body.Close() // nolint: errcheck
body, err := ioutil.ReadAll(req.Body)
if err != nil {

View File

@ -185,7 +185,10 @@ func createRoom(req *http.Request, device *authtypes.Device,
StateKey: &e.StateKey,
Depth: int64(depth),
}
builder.SetContent(e.Content)
err = builder.SetContent(e.Content)
if err != nil {
return httputil.LogThenError(req, err)
}
if i > 0 {
builder.PrevEvents = []gomatrixserverlib.EventReference{builtEvents[i-1].EventReference()}
}
@ -194,13 +197,16 @@ func createRoom(req *http.Request, device *authtypes.Device,
return httputil.LogThenError(req, err)
}
if err := gomatrixserverlib.Allowed(*ev, &authEvents); err != nil {
if err = gomatrixserverlib.Allowed(*ev, &authEvents); err != nil {
return httputil.LogThenError(req, err)
}
// Add the event to the list of auth events
builtEvents = append(builtEvents, *ev)
authEvents.AddEvent(ev)
err = authEvents.AddEvent(ev)
if err != nil {
return httputil.LogThenError(req, err)
}
}
// send events to the room server

View File

@ -153,21 +153,35 @@ func (r joinRoomReq) joinRoomByRemoteAlias(
return r.joinRoomUsingServers(resp.RoomID, resp.Servers)
}
func (r joinRoomReq) writeToBuilder(eb *gomatrixserverlib.EventBuilder, roomID string) {
func (r joinRoomReq) writeToBuilder(eb *gomatrixserverlib.EventBuilder, roomID string) error {
eb.Type = "m.room.member"
eb.SetContent(r.content)
eb.SetUnsigned(struct{}{})
err := eb.SetContent(r.content)
if err != nil {
return err
}
err = eb.SetUnsigned(struct{}{})
if err != nil {
return err
}
eb.Sender = r.userID
eb.StateKey = &r.userID
eb.RoomID = roomID
eb.Redacts = ""
return nil
}
func (r joinRoomReq) joinRoomUsingServers(
roomID string, servers []gomatrixserverlib.ServerName,
) util.JSONResponse {
var eb gomatrixserverlib.EventBuilder
r.writeToBuilder(&eb, roomID)
err := r.writeToBuilder(&eb, roomID)
if err != nil {
return httputil.LogThenError(r.req, err)
}
var queryRes api.QueryLatestEventsAndStateResponse
event, err := events.BuildEvent(r.req.Context(), &eb, r.cfg, r.queryAPI, &queryRes)
@ -235,7 +249,10 @@ func (r joinRoomReq) joinRoomUsingServer(roomID string, server gomatrixserverlib
// Set all the fields to be what they should be, this should be a no-op
// but it's possible that the remote server returned us something "odd"
r.writeToBuilder(&respMakeJoin.JoinEvent, roomID)
err = r.writeToBuilder(&respMakeJoin.JoinEvent, roomID)
if err != nil {
return nil, err
}
now := time.Now()
eventID := fmt.Sprintf("$%s:%s", util.RandomString(16), r.cfg.Matrix.ServerName)

View File

@ -60,7 +60,10 @@ func SendEvent(
Type: eventType,
StateKey: stateKey,
}
builder.SetContent(r)
err := builder.SetContent(r)
if err != nil {
return httputil.LogThenError(req, err)
}
var queryRes api.QueryLatestEventsAndStateResponse
e, err := events.BuildEvent(req.Context(), &builder, cfg, queryAPI, &queryRes)

View File

@ -80,20 +80,20 @@ func main() {
b.RoomID = *roomID
b.Type = "m.room.create"
b.StateKey = &emptyString
b.SetContent(map[string]string{"creator": *userID})
b.SetContent(map[string]string{"creator": *userID}) // nolint: errcheck
create := buildAndOutput()
// Build a m.room.member event.
b.Type = "m.room.member"
b.StateKey = userID
b.SetContent(map[string]string{"membership": "join"})
b.SetContent(map[string]string{"membership": "join"}) // nolint: errcheck
b.AuthEvents = []gomatrixserverlib.EventReference{create}
member := buildAndOutput()
// Build a number of m.room.message events.
b.Type = "m.room.message"
b.StateKey = nil
b.SetContent(map[string]string{"body": "Test Message"})
b.SetContent(map[string]string{"body": "Test Message"}) // nolint: errcheck
b.AuthEvents = []gomatrixserverlib.EventReference{create, member}
for i := 0; i < *messageCount; i++ {
buildAndOutput()

View File

@ -125,7 +125,8 @@ func startMediaAPI(suffix string, dynamicThumbnails bool) (*exec.Cmd, chan error
}
func cleanUpServer(cmd *exec.Cmd, dir string) {
cmd.Process.Kill() // ensure server is dead, only cleaning up so don't care about errors this returns.
// ensure server is dead, only cleaning up so don't care about errors this returns
cmd.Process.Kill() // nolint: errcheck
if err := os.RemoveAll(dir); err != nil {
fmt.Printf("WARNING: Failed to remove temporary directory %v: %q\n", dir, err)
}
@ -146,7 +147,7 @@ func main() {
// create server1 with only pre-generated thumbnails allowed
server1Cmd, server1CmdChan, _, server1ProxyCmd, _, server1ProxyAddr, server1Dir := startMediaAPI("1", false)
defer cleanUpServer(server1Cmd, server1Dir)
defer server1ProxyCmd.Process.Kill()
defer server1ProxyCmd.Process.Kill() // nolint: errcheck
testDownload(server1ProxyAddr, server1ProxyAddr, "doesnotexist", 404, server1CmdChan)
// upload a JPEG file
@ -163,7 +164,7 @@ func main() {
// create server2 with dynamic thumbnail generation
server2Cmd, server2CmdChan, _, server2ProxyCmd, _, server2ProxyAddr, server2Dir := startMediaAPI("2", true)
defer cleanUpServer(server2Cmd, server2Dir)
defer server2ProxyCmd.Process.Kill()
defer server2ProxyCmd.Process.Kill() // nolint: errcheck
testDownload(server2ProxyAddr, server2ProxyAddr, "doesnotexist", 404, server2CmdChan)
// pre-generated thumbnail that JPEG file via server2
@ -189,7 +190,7 @@ func getMediaURI(host, endpoint, query string, components []string) string {
func testUpload(host, filePath string) {
fmt.Printf("==TESTING== upload %v to %v\n", filePath, host)
file, err := os.Open(filePath)
defer file.Close()
defer file.Close() // nolint: errcheck
if err != nil {
panic(err)
}

View File

@ -114,8 +114,8 @@ func runAndReadFromTopic(runCmd *exec.Cmd, readyURL string, doInput func(), topi
readCmd.Stderr = os.Stderr
// Kill both processes before we exit.
defer func() { runCmd.Process.Kill() }()
defer func() { readCmd.Process.Kill() }()
defer func() { runCmd.Process.Kill() }() // nolint: errcheck
defer func() { readCmd.Process.Kill() }() // nolint: errcheck
// Run the command, read the messages and wait for a timeout in parallel.
go func() {
@ -228,7 +228,11 @@ func testRoomserver(input []string, wantOutput []string, checkQueries func(api.R
outputTopic := string(cfg.Kafka.Topics.OutputRoomEvent)
exe.DeleteTopic(outputTopic)
err = exe.DeleteTopic(outputTopic)
if err != nil {
panic(err)
}
if err = exe.CreateTopic(outputTopic); err != nil {
panic(err)
}

View File

@ -175,12 +175,21 @@ func startSyncServer() (*exec.Cmd, chan error) {
// prepareKafka creates the topics which will be written to by the tests.
func prepareKafka() {
exe.DeleteTopic(inputTopic)
if err := exe.CreateTopic(inputTopic); err != nil {
err := exe.DeleteTopic(inputTopic)
if err != nil {
panic(err)
}
exe.DeleteTopic(clientTopic)
if err := exe.CreateTopic(clientTopic); err != nil {
if err = exe.CreateTopic(inputTopic); err != nil {
panic(err)
}
err = exe.DeleteTopic(clientTopic)
if err != nil {
panic(err)
}
if err = exe.CreateTopic(clientTopic); err != nil {
panic(err)
}
}
@ -225,7 +234,8 @@ func main() {
fmt.Println("==TESTING==", os.Args[0])
prepareKafka()
cmd, syncServerCmdChan := startSyncServer()
defer cmd.Process.Kill() // ensure server is dead, only cleaning up so don't care about errors this returns.
// ensure server is dead, only cleaning up so don't care about errors this returns.
defer cmd.Process.Kill() // nolint: errcheck
// $ curl -XPOST -d '{}' "http://localhost:8009/_matrix/client/r0/createRoom?access_token=@alice:localhost"
// $ curl -XPUT -d '{"msgtype":"m.text","body":"hello world"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/send/m.room.message/1?access_token=@alice:localhost"

View File

@ -91,7 +91,7 @@ func (c *ContinualConsumer) Start() error {
pc, err := c.Consumer.ConsumePartition(c.Topic, partition, offset)
if err != nil {
for _, p := range partitionConsumers {
p.Close()
p.Close() // nolint: errcheck
}
return err
}
@ -106,7 +106,7 @@ func (c *ContinualConsumer) Start() error {
// consumePartition consumes the room events for a single partition of the kafkaesque stream.
func (c *ContinualConsumer) consumePartition(pc sarama.PartitionConsumer) {
defer pc.Close()
defer pc.Close() // nolint: errcheck
for message := range pc.Messages() {
msgErr := c.ProcessMessage(message)
// Advance our position in the stream so that we will start at the right position after a restart.

View File

@ -37,7 +37,10 @@ func NewDatabase(dataSourceName string) (*Database, error) {
return nil, err
}
d := &Database{}
d.statements.prepare(db)
err = d.statements.prepare(db)
if err != nil {
return nil, err
}
return d, nil
}

View File

@ -83,7 +83,7 @@ func (s *serverKeyStatements) bulkSelectServerKeys(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
results := map[gomatrixserverlib.PublicKeyRequest]gomatrixserverlib.ServerKeys{}
for rows.Next() {
var serverName string

View File

@ -71,7 +71,7 @@ func (s *PartitionOffsetStatements) SelectPartitionOffsets(topic string) ([]Part
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
var results []PartitionOffset
for rows.Next() {
var offset PartitionOffset

View File

@ -30,9 +30,9 @@ type Transaction interface {
// If the transaction succeeded then it is committed, otherwise it is rolledback.
func EndTransaction(txn Transaction, succeeded *bool) {
if *succeeded {
txn.Commit()
txn.Commit() // nolint: errcheck
} else {
txn.Rollback()
txn.Rollback() // nolint: errcheck
}
}

View File

@ -69,7 +69,7 @@ func CanonicalJSONInput(jsonData []string) []string {
}
// Do issues a request and checks the status code and body of the response
func (r *Request) Do() error {
func (r *Request) Do() (err error) {
client := &http.Client{
Timeout: 5 * time.Second,
Transport: &http.Transport{
@ -82,7 +82,7 @@ func (r *Request) Do() error {
if err != nil {
return err
}
defer res.Body.Close()
defer (func() { err = res.Body.Close() })()
if res.StatusCode != r.WantedStatusCode {
return fmt.Errorf("incorrect status code. Expected: %d Got: %d", r.WantedStatusCode, res.StatusCode)

View File

@ -120,16 +120,21 @@ func WriteConfig(cfg *config.Dendrite, configDir string) error {
}
// NewMatrixKey generates a new ed25519 matrix server key and writes it to a file.
func NewMatrixKey(matrixKeyPath string) error {
func NewMatrixKey(matrixKeyPath string) (err error) {
var data [35]byte
if _, err := rand.Read(data[:]); err != nil {
_, err = rand.Read(data[:])
if err != nil {
return err
}
keyOut, err := os.OpenFile(matrixKeyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer keyOut.Close()
defer (func() {
err = keyOut.Close()
})()
if err = pem.Encode(keyOut, &pem.Block{
Type: "MATRIX PRIVATE KEY",
Headers: map[string]string{
@ -176,7 +181,7 @@ func NewTLSKey(tlsKeyPath, tlsCertPath string) error {
if err != nil {
return err
}
defer certOut.Close()
defer certOut.Close() // nolint: errcheck
if err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
return err
}
@ -185,7 +190,7 @@ func NewTLSKey(tlsKeyPath, tlsCertPath string) error {
if err != nil {
return err
}
defer keyOut.Close()
defer keyOut.Close() // nolint: errcheck
if err = pem.Encode(keyOut, &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(priv),

View File

@ -180,7 +180,10 @@ func (t *txnReq) processEvent(e gomatrixserverlib.Event) error {
func checkAllowedByState(e gomatrixserverlib.Event, stateEvents []gomatrixserverlib.Event) error {
authUsingState := gomatrixserverlib.NewAuthEvents(nil)
for i := range stateEvents {
authUsingState.AddEvent(&stateEvents[i])
err := authUsingState.AddEvent(&stateEvents[i])
if err != nil {
return err
}
}
return gomatrixserverlib.Allowed(e, &authUsingState)
}

View File

@ -257,7 +257,10 @@ func buildMembershipEvent(
authEvents := gomatrixserverlib.NewAuthEvents(nil)
for i := range queryRes.StateEvents {
authEvents.AddEvent(&queryRes.StateEvents[i])
err = authEvents.AddEvent(&queryRes.StateEvents[i])
if err != nil {
return nil, err
}
}
if err = fillDisplayName(builder, authEvents); err != nil {

View File

@ -105,7 +105,7 @@ func (s *joinedHostsStatements) selectJoinedHosts(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
var result []types.JoinedHost
for rows.Next() {

View File

@ -105,12 +105,14 @@ func RemoveDir(dir types.Path, logger *log.Entry) {
}
// WriteTempFile writes to a new temporary file
func WriteTempFile(reqReader io.Reader, maxFileSizeBytes config.FileSizeBytes, absBasePath config.Path) (types.Base64Hash, types.FileSizeBytes, types.Path, error) {
func WriteTempFile(reqReader io.Reader, maxFileSizeBytes config.FileSizeBytes, absBasePath config.Path) (hash types.Base64Hash, size types.FileSizeBytes, path types.Path, err error) {
size = -1
tmpFileWriter, tmpFile, tmpDir, err := createTempFileWriter(absBasePath)
if err != nil {
return "", -1, "", err
return
}
defer tmpFile.Close()
defer (func() { err = tmpFile.Close() })()
// The amount of data read is limited to maxFileSizeBytes. At this point, if there is more data it will be truncated.
limitedReader := io.LimitReader(reqReader, int64(maxFileSizeBytes))
@ -121,13 +123,18 @@ func WriteTempFile(reqReader io.Reader, maxFileSizeBytes config.FileSizeBytes, a
teeReader := io.TeeReader(limitedReader, hasher)
bytesWritten, err := io.Copy(tmpFileWriter, teeReader)
if err != nil && err != io.EOF {
return "", -1, "", err
return
}
tmpFileWriter.Flush()
err = tmpFileWriter.Flush()
if err != nil {
return
}
hash := hasher.Sum(nil)
return types.Base64Hash(base64.RawURLEncoding.EncodeToString(hash[:])), types.FileSizeBytes(bytesWritten), tmpDir, nil
hash = types.Base64Hash(base64.RawURLEncoding.EncodeToString(hasher.Sum(nil)[:]))
size = types.FileSizeBytes(bytesWritten)
path = tmpDir
return
}
// moveFile attempts to move the file src to dst

View File

@ -83,7 +83,7 @@ func readFile(src string) (image.Image, error) {
if err != nil {
return nil, err
}
defer file.Close()
defer file.Close() // nolint: errcheck
img, _, err := image.Decode(file)
if err != nil {
@ -93,12 +93,12 @@ func readFile(src string) (image.Image, error) {
return img, nil
}
func writeFile(img image.Image, dst string) error {
func writeFile(img image.Image, dst string) (err error) {
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
defer (func() { err = out.Close() })()
return jpeg.Encode(out, img, &jpeg.Options{
Quality: 85,

View File

@ -148,7 +148,9 @@ func (r *downloadRequest) jsonErrorResponse(w http.ResponseWriter, res util.JSON
// Set status code and write the body
w.WriteHeader(res.Code)
r.Logger.WithField("code", res.Code).Infof("Responding (%d bytes)", len(resBytes))
w.Write(resBytes)
// we don't really care that much if we fail to write the error response
w.Write(resBytes) // nolint: errcheck
}
// Validate validates the downloadRequest fields
@ -234,7 +236,7 @@ func (r *downloadRequest) respondFromLocalFile(
return nil, errors.Wrap(err, "failed to get file path from metadata")
}
file, err := os.Open(filePath)
defer file.Close()
defer file.Close() // nolint: errcheck
if err != nil {
return nil, errors.Wrap(err, "failed to open file")
}
@ -256,7 +258,7 @@ func (r *downloadRequest) respondFromLocalFile(
if r.IsThumbnailRequest {
thumbFile, thumbMetadata, resErr := r.getThumbnailFile(types.Path(filePath), activeThumbnailGeneration, maxThumbnailGenerators, db, dynamicThumbnails, thumbnailSizes)
if thumbFile != nil {
defer thumbFile.Close()
defer thumbFile.Close() // nolint: errcheck
}
if resErr != nil {
return nil, resErr
@ -360,16 +362,16 @@ func (r *downloadRequest) getThumbnailFile(
thumbPath := string(thumbnailer.GetThumbnailPath(types.Path(filePath), thumbnail.ThumbnailSize))
thumbFile, err := os.Open(string(thumbPath))
if err != nil {
thumbFile.Close()
thumbFile.Close() // nolint: errcheck
return nil, nil, errors.Wrap(err, "failed to open file")
}
thumbStat, err := thumbFile.Stat()
if err != nil {
thumbFile.Close()
thumbFile.Close() // nolint: errcheck
return nil, nil, errors.Wrap(err, "failed to stat file")
}
if types.FileSizeBytes(thumbStat.Size()) != thumbnail.MediaMetadata.FileSizeBytes {
thumbFile.Close()
thumbFile.Close() // nolint: errcheck
return nil, nil, errors.New("thumbnail file sizes on disk and in database differ")
}
return thumbFile, thumbnail, nil
@ -564,7 +566,7 @@ func (r *downloadRequest) fetchRemoteFile(absBasePath config.Path, maxFileSizeBy
// Remote file not found
return "", false, nil
}
defer resp.Body.Close()
defer resp.Body.Close() // nolint: errcheck
// get metadata from request and set metadata on response
contentLength, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)

View File

@ -183,7 +183,10 @@ func (r *RoomserverAliasAPI) sendUpdatedAliasesEvent(
// Add auth events
authEvents := gomatrixserverlib.NewAuthEvents(nil)
for i := range res.StateEvents {
authEvents.AddEvent(&res.StateEvents[i])
err = authEvents.AddEvent(&res.StateEvents[i])
if err != nil {
return err
}
}
refs, err := eventsNeeded.AuthEventReferences(&authEvents)
if err != nil {

View File

@ -283,7 +283,7 @@ func (h *httpRoomserverQueryAPI) QueryServerAllowedToSeeEvent(
ctx context.Context,
request *QueryServerAllowedToSeeEventRequest,
response *QueryServerAllowedToSeeEventResponse,
) error {
) (err error) {
apiURL := h.roomserverURL + RoomserverQueryServerAllowedToSeeEventPath
return postJSON(ctx, h.httpClient, apiURL, request, response)
}
@ -306,7 +306,7 @@ func postJSON(
res, err := httpClient.Do(req.WithContext(ctx))
if res != nil {
defer res.Body.Close()
defer (func() { err = res.Body.Close() })()
}
if err != nil {
return err

View File

@ -117,7 +117,10 @@ func processRoomEvent(
return err
}
}
db.SetState(ctx, stateAtEvent.EventNID, stateAtEvent.BeforeStateSnapshotNID)
err = db.SetState(ctx, stateAtEvent.EventNID, stateAtEvent.BeforeStateSnapshotNID)
if err != nil {
return err
}
}
if input.Kind == api.KindBackfill {

View File

@ -85,7 +85,7 @@ func (s *eventJSONStatements) bulkSelectEventJSON(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
// We know that we will only get as many results as event NIDs
// because of the unique constraint on event NIDs.

View File

@ -119,7 +119,7 @@ func (s *eventStateKeyStatements) bulkSelectEventStateKeyNID(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
result := make(map[string]types.EventStateKeyNID, len(eventStateKeys))
for rows.Next() {
@ -153,7 +153,7 @@ func (s *eventStateKeyStatements) bulkSelectEventStateKey(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
result := make(map[types.EventStateKeyNID]string, len(eventStateKeyNIDs))
for rows.Next() {

View File

@ -131,7 +131,7 @@ func (s *eventTypeStatements) bulkSelectEventTypeNID(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
result := make(map[string]types.EventTypeNID, len(eventTypes))
for rows.Next() {

View File

@ -191,7 +191,7 @@ func (s *eventStatements) bulkSelectStateEventByID(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
// We know that we will only get as many results as event IDs
// because of the unique constraint on event IDs.
// So we can allocate an array of the correct size now.
@ -231,7 +231,7 @@ func (s *eventStatements) bulkSelectStateAtEventByID(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
results := make([]types.StateAtEvent, len(eventIDs))
i := 0
for ; rows.Next(); i++ {
@ -269,7 +269,7 @@ func (s *eventStatements) selectEventSentToOutput(
ctx context.Context, txn *sql.Tx, eventNID types.EventNID,
) (sentToOutput bool, err error) {
stmt := common.TxStmt(txn, s.selectEventSentToOutputStmt)
stmt.QueryRowContext(ctx, int64(eventNID)).Scan(&sentToOutput)
err = stmt.QueryRowContext(ctx, int64(eventNID)).Scan(&sentToOutput)
return
}
@ -295,7 +295,7 @@ func (s *eventStatements) bulkSelectStateAtEventAndReference(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
results := make([]types.StateAtEventAndReference, len(eventNIDs))
i := 0
for ; rows.Next(); i++ {
@ -333,7 +333,7 @@ func (s *eventStatements) bulkSelectEventReference(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
results := make([]gomatrixserverlib.EventReference, len(eventNIDs))
i := 0
for ; rows.Next(); i++ {
@ -354,7 +354,7 @@ func (s *eventStatements) bulkSelectEventID(ctx context.Context, eventNIDs []typ
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
results := make(map[types.EventNID]string, len(eventNIDs))
i := 0
for ; rows.Next(); i++ {
@ -378,7 +378,7 @@ func (s *eventStatements) bulkSelectEventNID(ctx context.Context, eventIDs []str
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
results := make(map[string]types.EventNID, len(eventIDs))
for rows.Next() {
var eventID string

View File

@ -113,22 +113,21 @@ func (s *inviteStatements) insertInviteEvent(
func (s *inviteStatements) updateInviteRetired(
ctx context.Context,
txn *sql.Tx, roomNID types.RoomNID, targetUserNID types.EventStateKeyNID,
) ([]string, error) {
) (eventIDs []string, err error) {
stmt := common.TxStmt(txn, s.updateInviteRetiredStmt)
rows, err := stmt.QueryContext(ctx, roomNID, targetUserNID)
if err != nil {
return nil, err
}
defer rows.Close()
var result []string
defer (func() { err = rows.Close() })()
for rows.Next() {
var inviteEventID string
if err := rows.Scan(&inviteEventID); err != nil {
return nil, err
}
result = append(result, inviteEventID)
eventIDs = append(eventIDs, inviteEventID)
}
return result, nil
return
}
// selectInviteActiveForUserInRoom returns a list of sender state key NIDs
@ -142,7 +141,7 @@ func (s *inviteStatements) selectInviteActiveForUserInRoom(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
var result []types.EventStateKeyNID
for rows.Next() {
var senderUserNID int64

View File

@ -137,7 +137,7 @@ func (s *stateBlockStatements) bulkSelectStateBlockEntries(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
results := make([]types.StateEntryList, len(stateBlockNIDs))
// current is a pointer to the StateEntryList to append the state entries to.
@ -193,7 +193,7 @@ func (s *stateBlockStatements) bulkSelectFilteredStateBlockEntries(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
var results []types.StateEntryList
var current types.StateEntryList

View File

@ -97,7 +97,7 @@ func (s *stateSnapshotStatements) bulkSelectStateBlockNIDs(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
results := make([]types.StateBlockNIDList, len(stateNIDs))
i := 0
for ; rows.Next(); i++ {

View File

@ -287,19 +287,19 @@ func (d *Database) GetLatestEventsForUpdate(
eventNIDs, lastEventNIDSent, currentStateSnapshotNID, err :=
d.statements.selectLatestEventsNIDsForUpdate(ctx, txn, roomNID)
if err != nil {
txn.Rollback()
txn.Rollback() // nolint: errcheck
return nil, err
}
stateAndRefs, err := d.statements.bulkSelectStateAtEventAndReference(ctx, txn, eventNIDs)
if err != nil {
txn.Rollback()
txn.Rollback() // nolint: errcheck
return nil, err
}
var lastEventIDSent string
if lastEventNIDSent != 0 {
lastEventIDSent, err = d.statements.selectEventID(ctx, txn, lastEventNIDSent)
if err != nil {
txn.Rollback()
txn.Rollback() // nolint: errcheck
return nil, err
}
}
@ -459,7 +459,7 @@ func (d *Database) MembershipUpdater(
succeeded := false
defer func() {
if !succeeded {
txn.Rollback()
txn.Rollback() // nolint: errcheck
}
}()

View File

@ -87,7 +87,7 @@ func (s *accountDataStatements) insertAccountData(
ctx context.Context,
userID, roomID, dataType string,
) (pos int64, err error) {
s.insertAccountDataStmt.QueryRowContext(ctx, userID, roomID, dataType).Scan(&pos)
err = s.insertAccountDataStmt.QueryRowContext(ctx, userID, roomID, dataType).Scan(&pos)
return
}

View File

@ -122,7 +122,7 @@ func (s *currentRoomStateStatements) selectJoinedUsers(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
result := make(map[string][]string)
for rows.Next() {
@ -147,7 +147,7 @@ func (s *currentRoomStateStatements) selectRoomIDsWithMembership(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
var result []string
for rows.Next() {
@ -169,7 +169,7 @@ func (s *currentRoomStateStatements) selectCurrentState(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
return rowsToEvents(rows)
}
@ -208,7 +208,7 @@ func (s *currentRoomStateStatements) selectEventsWithEventIDs(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
return rowsToStreamEvents(rows)
}

View File

@ -213,7 +213,7 @@ func (s *outputRoomEventsStatements) selectRecentEvents(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
events, err := rowsToStreamEvents(rows)
if err != nil {
return nil, err
@ -233,7 +233,7 @@ func (s *outputRoomEventsStatements) selectEvents(
if err != nil {
return nil, err
}
defer rows.Close()
defer rows.Close() // nolint: errcheck
return rowsToStreamEvents(rows)
}