ronantakizawa/codereview-bench huggingface dataset:
Repository: go-playground/validator
File: baked_in.go (Go)

Code before:
		if len(s) == 0 {
			return false
		}

		url, err := url.ParseRequestURI(s)

		if err != nil || url.Scheme == "" {
			return false
		}

		return true
	}

	panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}

// isUrnRFC2141 is the validation function for validating if the current field's value is a valid URN as per RFC 2141.
func isUrnRFC2141(fl FieldLevel) bool {
	field := fl.Field()

	switch field.Kind() {
	case reflect.String:

		str := field.String()

		_, match := urn.Parse([]byte(str))

		return match
	}

	panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}

// isFile is the validation function for validating if the current field's value is a valid file path.
func isFile(fl FieldLevel) bool {
	field := fl.Field()

	switch field.Kind() {
	case reflect.String:
		fileInfo, err := os.Stat(field.String())
		if err != nil {
			return false
		}

		return !fileInfo.IsDir()
	}

	panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}

// isE164 is the validation function for validating if the current field's value is a valid e.164 formatted phone number.

Review comment (suggestion):
It'd be nice to see support for `*string` as thats the most used cases in most of the generators.

Code after:

		if len(s) == 0 {
			return false
		}

		url, err := url.ParseRequestURI(s)

		if err != nil || url.Scheme == "" {
			return false
		}

		return true
	}

	panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}

// isHttpURL is the validation function for validating if the current field's value is a valid HTTP(s) URL.
func isHttpURL(fl FieldLevel) bool {
	if !isURL(fl) {
		return false
	}

	field := fl.Field()
	switch field.Kind() {
	case reflect.String:

		s := strings.ToLower(field.String())
		return strings.HasPrefix(s, "http://") || strings.HasPrefix(s, "https://")
	}

	panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}

// isUrnRFC2141 is the validation function for validating if the current field's value is a valid URN as per RFC 2141.
func isUrnRFC2141(fl FieldLevel) bool {
	field := fl.Field()

	switch field.Kind() {
	case reflect.String:

		str := field.String()

		_, match := urn.Parse([]byte(str))

		return match
	}

	panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
Repository: go-playground/validator
File: doc.go (Go)

Code before:
other types.

	Usage: excludesfield=InnerStructField.Field

# Unique

For arrays & slices, unique will ensure that there are no duplicates.
For maps, unique will ensure that there are no duplicate values.
For slices of struct, unique will ensure that there are no duplicate values
in a field of the struct specified via a parameter.

	// For arrays, slices, and maps:
	Usage: unique

	// For slices of struct:
	Usage: unique=field

# Alpha Only

This validates that a string value contains ASCII alpha characters only

	Usage: alpha

# Alpha Space

This validate that a string value contains ASCII alpha characters and spaces only

	Usage: alphaspace

# Alphanumeric

This validates that a string value contains ASCII alphanumeric characters only

	Usage: alphanum

# Alpha Unicode

This validates that a string value contains unicode alpha characters only

	Usage: alphaunicode

# Alphanumeric Unicode

This validates that a string value contains unicode alphanumeric characters only

	Usage: alphanumunicode

# Boolean

This validates that a string value can successfully be parsed into a boolean with strconv.ParseBool


Review comment (suggestion):
```suggestion
This validates that a string value contains ASCII alpha characters and spaces only
```


Code after:
other types.

	Usage: excludesfield=InnerStructField.Field

# Unique

For arrays & slices, unique will ensure that there are no duplicates.
For maps, unique will ensure that there are no duplicate values.
For slices of struct, unique will ensure that there are no duplicate values
in a field of the struct specified via a parameter.

	// For arrays, slices, and maps:
	Usage: unique

	// For slices of struct:
	Usage: unique=field

# Alpha Only

This validates that a string value contains ASCII alpha characters only

	Usage: alpha

# Alpha Space

This validates that a string value contains ASCII alpha characters and spaces only

	Usage: alphaspace

# Alphanumeric

This validates that a string value contains ASCII alphanumeric characters only

	Usage: alphanum

# Alpha Unicode

This validates that a string value contains unicode alpha characters only

	Usage: alphaunicode

# Alphanumeric Unicode

This validates that a string value contains unicode alphanumeric characters only

	Usage: alphanumunicode

# Boolean

This validates that a string value can successfully be parsed into a boolean with strconv.ParseBool
Repository: go-playground/validator
File: _examples/simple/main.go (Go)

Code before:
func validateStruct() {

	address := &Address{
		Street: "Eavesdown Docks",
		Planet: "Persphone",
		Phone:  "none",
	}

	user := &User{
		FirstName:      "Badger",
		LastName:       "Smith",
		Age:            135,
		Gender:         "male",
		Email:          "Badger.Smith@gmail.com",
		FavouriteColor: "#000-",
		Addresses:      []*Address{address},
	}

	// returns nil or ValidationErrors ( []FieldError )
	err := validate.Struct(user)
	if err != nil {

		// this check is only needed when your code could produce
		// an invalid value for validation such as interface with nil
		// value most including myself do not usually have code like this.
		if errors.Is(err, &validator.InvalidValidationError{}) {
			fmt.Println(err)
			return
		}

		var validateErrs validator.ValidationErrors
		if errors.As(err, &validateErrs) {
			for _, e := range validateErrs {
				fmt.Println(e.Namespace())
				fmt.Println(e.Field())
				fmt.Println(e.StructNamespace())
				fmt.Println(e.StructField())
				fmt.Println(e.Tag())
				fmt.Println(e.ActualTag())
				fmt.Println(e.Kind())
				fmt.Println(e.Type())
				fmt.Println(e.Value())
				fmt.Println(e.Param())
				fmt.Println()
			}
		}

		// from here you can create your own error messages in whatever language you wish
		return
	}


Review comment (suggestion):
I don't think it works

This would be better

```suggestion
		if errors.As(err, &validator.InvalidValidationError{}) {
```

errors.Is is used for sentinel errors.
errors.As is used to check an error is from a certain type, and converts it

Code after:
func validateStruct() {

	address := &Address{
		Street: "Eavesdown Docks",
		Planet: "Persphone",
		Phone:  "none",
	}

	user := &User{
		FirstName:      "Badger",
		LastName:       "Smith",
		Age:            135,
		Gender:         "male",
		Email:          "Badger.Smith@gmail.com",
		FavouriteColor: "#000-",
		Addresses:      []*Address{address},
	}

	// returns nil or ValidationErrors ( []FieldError )
	err := validate.Struct(user)
	if err != nil {

		// this check is only needed when your code could produce
		// an invalid value for validation such as interface with nil
		// value most including myself do not usually have code like this.
		if errors.As(err, &validator.InvalidValidationError{}) {
			fmt.Println(err)
			return
		}

		var validateErrs validator.ValidationErrors
		if errors.As(err, &validateErrs) {
			for _, e := range validateErrs {
				fmt.Println(e.Namespace())
				fmt.Println(e.Field())
				fmt.Println(e.StructNamespace())
				fmt.Println(e.StructField())
				fmt.Println(e.Tag())
				fmt.Println(e.ActualTag())
				fmt.Println(e.Kind())
				fmt.Println(e.Type())
				fmt.Println(e.Value())
				fmt.Println(e.Param())
				fmt.Println()
			}
		}

		// from here you can create your own error messages in whatever language you wish
		return
	}
Repository: go-playground/validator
File: validator_test.go (Go)

Code before:
	errs = validate.Var(s, "email")
	Equal(t, errs, nil)

	s = "उपयोगकर्ता@उदाहरण.कॉम"
	errs = validate.Var(s, "email")
	Equal(t, errs, nil)

	s = "用户@例子.广告"
	errs = validate.Var(s, "email")
	Equal(t, errs, nil)

	s = "mail@domain_with_underscores.org"
	errs = validate.Var(s, "email")
	NotEqual(t, errs, nil)
	AssertError(t, errs, "", "", "", "", "email")

	s = "mail@dotaftercom.com."
	errs = validate.Var(s, "email")
	NotEqual(t, errs, nil)
	AssertError(t, errs, "", "", "", "", "email")

	s = "mail@dotaftercom.co.uk."
	errs = validate.Var(s, "email")
	NotEqual(t, errs, nil)
	AssertError(t, errs, "", "", "", "", "email")

	s = ""
	errs = validate.Var(s, "email")
	NotEqual(t, errs, nil)
	AssertError(t, errs, "", "", "", "", "email")

	s = "test@email"
	errs = validate.Var(s, "email")
	NotEqual(t, errs, nil)
	AssertError(t, errs, "", "", "", "", "email")

	s = "test@email."
	errs = validate.Var(s, "email")
	NotEqual(t, errs, nil)
	AssertError(t, errs, "", "", "", "", "email")

	s = "@email.com"
	errs = validate.Var(s, "email")
	NotEqual(t, errs, nil)
	AssertError(t, errs, "", "", "", "", "email")

	s = `"test test"@email.com`
	errs = validate.Var(s, "email")
	Equal(t, errs, nil)

	s = `"@email.com`

Review comment (suggestion):
Let's include one more test case.

```
	s = "Foo Bar <foobar@example.com>"
	errs = validate.Var(s, "email")
	NotEqual(t, errs, nil)
```

Code after:
	errs = validate.Var(s, "email")
	Equal(t, errs, nil)

	s = "उपयोगकर्ता@उदाहरण.कॉम"
	errs = validate.Var(s, "email")
	Equal(t, errs, nil)

	s = "用户@例子.广告"
	errs = validate.Var(s, "email")
	Equal(t, errs, nil)

	s = "mail@domain_with_underscores.org"
	errs = validate.Var(s, "email")
	NotEqual(t, errs, nil)
	AssertError(t, errs, "", "", "", "", "email")

	s = "mail@dotaftercom.com."
	errs = validate.Var(s, "email")
	NotEqual(t, errs, nil)
	AssertError(t, errs, "", "", "", "", "email")

	s = "mail@dotaftercom.co.uk."
	errs = validate.Var(s, "email")
	NotEqual(t, errs, nil)
	AssertError(t, errs, "", "", "", "", "email")

	s = "Foo Bar <foobar@example.com>"
	errs = validate.Var(s, "email")
	NotEqual(t, errs, nil)

	s = ""
	errs = validate.Var(s, "email")
	NotEqual(t, errs, nil)
	AssertError(t, errs, "", "", "", "", "email")

	s = "test@email"
	errs = validate.Var(s, "email")
	NotEqual(t, errs, nil)
	AssertError(t, errs, "", "", "", "", "email")

	s = "test@email."
	errs = validate.Var(s, "email")
	NotEqual(t, errs, nil)
	AssertError(t, errs, "", "", "", "", "email")

	s = "@email.com"
	errs = validate.Var(s, "email")
	NotEqual(t, errs, nil)
	AssertError(t, errs, "", "", "", "", "email")

	s = `"test test"@email.com`
Repository: go-playground/validator
File: validator_test.go (Go)

Code before:
		Equal(t, fe.Namespace(), "Test2.Inner")
		Equal(t, fe.Tag(), "validateFn")

		fe = errs[2]
		Equal(t, fe.Field(), "Inner2")
		Equal(t, fe.Namespace(), "Test2.Inner2")
		Equal(t, fe.Tag(), "validateFn")
	})
}
func TestMapStructBasicValidation(t *testing.T) {
	type Inner struct {
		Value string `validate:"max=5"`
	}
	type Outer struct {
		Data map[string]Inner `validate:"dive"`
	}
	obj := Outer{
		Data: map[string]Inner{
			"key1": {Value: "exceeds"},
		},
	}
	validate := New()
	err := validate.Struct(obj)
	if err == nil {
		t.Fatal("Expected validation error due to Value > 5 chars")
	}
}
func TestMapStructPointerValidation(t *testing.T) {
	type Inner struct {
		Count int `validate:"gt=10"`
	}
	type Outer struct {
		Items map[string]*Inner `validate:"dive"`
	}
	obj := Outer{
		Items: map[string]*Inner{
			"a": {Count: 5},
		},
	}
	validate := New()
	err := validate.Struct(obj)
	if err == nil {
		t.Fatal("Expected error due to Count <= 10")
	}
}
func TestMapStructWithKeyValidationOnly(t *testing.T) {
	type Inner struct {
		Name string `validate:"required"`
	}
	type Outer struct {
		Things map[string]Inner `validate:"dive,keys,min=3,endkeys"`

Review comment (suggestion):
Let's replace all 'if err == nil => t.Fatal' in new tests and add comments to keep things consistent.
```suggestion
	NotEqual(t, err, nil)
```

Code after:
		Equal(t, fe.Namespace(), "Test2.Inner")
		Equal(t, fe.Tag(), "validateFn")

		fe = errs[2]
		Equal(t, fe.Field(), "Inner2")
		Equal(t, fe.Namespace(), "Test2.Inner2")
		Equal(t, fe.Tag(), "validateFn")
	})
}
func TestMapStructBasicValidation(t *testing.T) {
	// Tests basic validation of a map with struct values
	type Inner struct {
		Value string `validate:"max=5"`
	}
	type Outer struct {
		Data map[string]Inner `validate:"dive"`
	}
	obj := Outer{
		Data: map[string]Inner{
			"key1": {Value: "exceeds"}, // Should fail because Value is longer than 5 characters
		},
	}
	validate := New()
	errs := validate.Struct(obj)
	NotEqual(t, errs, nil)
}
func TestMapStructPointerValidation(t *testing.T) {
	// Tests validation of a map with pointer to struct values
	type Inner struct {
		Count int `validate:"gt=10"`
	}
	type Outer struct {
		Items map[string]*Inner `validate:"dive"`
	}
	obj := Outer{
		Items: map[string]*Inner{
			"a": {Count: 5},
		},
	}
	validate := New()
	errs := validate.Struct(obj)
	NotEqual(t, errs, nil)
}
func TestMapStructWithKeyValidationOnly(t *testing.T) {
	// Tests validation of a map with struct values, focusing on key validation
	type Inner struct {
		Name string `validate:"required"`
	}
	type Outer struct {
		Things map[string]Inner `validate:"dive,keys,min=3,endkeys"`
	}
Repository: gogs/gogs
File: modules/avatar/avatar.go (Go)

Code before:
package avatar

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
	"image"
	"image/jpeg"
	"image/png"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"

	"github.com/nfnt/resize"
)

var (
	gravatar         = "http://www.gravatar.com/avatar"
	defaultImagePath = "./default.jpg"
)

// hash email to md5 string
func HashEmail(email string) string {
	h := md5.New()
	h.Write([]byte(strings.ToLower(email)))
	return hex.EncodeToString(h.Sum(nil))
}

type Avatar struct {
	Hash           string
	cacheDir       string // image save dir
	reqParams      string
	imagePath      string
	expireDuration time.Duration
}

func New(hash string, cacheDir string) *Avatar {
	return &Avatar{
		Hash:           hash,
		cacheDir:       cacheDir,
		expireDuration: time.Minute * 10,
		reqParams: url.Values{
			"d":    {"retro"},
			"size": {"200"},

Review comment (suggestion):
Add URL parameter to Gravatar will give back size you want `https://avatars3.githubusercontent.com/u/2946214?s=200`


Code after:
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

// for www.gravatar.com image cache
package avatar

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
	"image"
	"image/jpeg"
	"image/png"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"

	"github.com/nfnt/resize"
)

var (
	gravatar = "http://www.gravatar.com/avatar"
)

func debug(a ...interface{}) {
	if true {
		log.Println(a...)
	}
}

// hash email to md5 string
// keep this func in order to make this package indenpent
func HashEmail(email string) string {
	h := md5.New()
	h.Write([]byte(strings.ToLower(email)))
	return hex.EncodeToString(h.Sum(nil))
}

type Avatar struct {
	Hash           string
	AlterImage     string // image path
	cacheDir       string // image save dir
	reqParams      string
Repository: gogs/gogs
File: modules/avatar/avatar.go (Go)

Code before:
package avatar

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
	"image"
	"image/jpeg"
	"image/png"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"

	"github.com/nfnt/resize"
)

var (
	gravatar         = "http://www.gravatar.com/avatar"
	defaultImagePath = "./default.jpg"
)

// hash email to md5 string
func HashEmail(email string) string {
	h := md5.New()

Review comment (security):
Add license notify before this line, same as another file

> // Copyright 2014 The Gogs Authors. All rights reserved.
> // Use of this source code is governed by a MIT-style
> // license that can be found in the LICENSE file.


Code after:
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

// for www.gravatar.com image cache
package avatar

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
	"image"
	"image/jpeg"
	"image/png"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"

	"github.com/nfnt/resize"
)

var (
	gravatar = "http://www.gravatar.com/avatar"
)
Repository: gogs/gogs
File: internal/route/api/v1/repo/commits.go (Go)

Code before:
func GetAllCommits(c *context.APIContext) {
	if strings.Contains(c.Req.Header.Get("Accept"), api.MediaApplicationSHA) {
		c.SetParams("*", c.Params(":sha"))
		GetReferenceSHA(c)
		return
	}

	// Get pagesize, set default if it is not specified.
	pageSizeStr := c.Query("pageSize")
	if pageSizeStr == "" {
		pageSizeStr = "30"
	}

	pageSize, err := strconv.Atoi(pageSizeStr)
	if err != nil {
		c.Error(err, "get page size error")
	}

	gitRepo, err := git.Open(c.Repo.Repository.RepoPath())
	if err != nil {
		c.Error(err, "open repository")
		return
	}

	// The response object returned as JSON
	result := []*api.Commit{}

	commits, err := gitRepo.Log("HEAD", git.LogOptions{MaxCount: pageSize})
	if err != nil {
		c.Error(err, "git log")
	}

	for _, commit := range commits {
		apiCommit, err := gitCommitToApiCommit(commit, c)
		if err != nil {
			c.Error(err, "convert git commit to api commit")
			return
		}
		result = append(result, apiCommit)
	}

	c.JSONSuccess(result)
}

// GetSingleCommit will return a single Commit object based on the specified SHA.
func GetSingleCommit(c *context.APIContext) {
	if strings.Contains(c.Req.Header.Get("Accept"), api.MediaApplicationSHA) {
		c.SetParams("*", c.Params(":sha"))
		GetReferenceSHA(c)
		return
	}

Review comment (performance):
```suggestion
	result := make([]*api.Commit, 0, pageSize)
```

We can preallocate to the `pageSize`.

Code after:
	// Get pagesize, set default if it is not specified.
	pageSize := c.QueryInt("pageSize")
	if pageSize == 0 {
		pageSize = 30
	}

	gitRepo, err := git.Open(c.Repo.Repository.RepoPath())
	if err != nil {
		c.Error(err, "open repository")
		return
	}

	// The response object returned as JSON
	result := make([]*api.Commit, 0, pageSize)
	commits, err := gitRepo.Log("HEAD", git.LogOptions{MaxCount: pageSize})
	if err != nil {
		c.Error(err, "git log")
	}

	for _, commit := range commits {
		apiCommit, err := gitCommitToAPICommit(commit, c)
		if err != nil {
			c.Error(err, "convert git commit to api commit")
			return
		}
		result = append(result, apiCommit)
	}

	c.JSONSuccess(result)
}

// GetSingleCommit will return a single Commit object based on the specified SHA.
func GetSingleCommit(c *context.APIContext) {
	if strings.Contains(c.Req.Header.Get("Accept"), api.MediaApplicationSHA) {
		c.SetParams("*", c.Params(":sha"))
		GetReferenceSHA(c)
		return
	}

	gitRepo, err := git.Open(c.Repo.Repository.RepoPath())
	if err != nil {
		c.Error(err, "open repository")
		return
	}
	commit, err := gitRepo.CatFileCommit(c.Params(":sha"))
	if err != nil {
		c.NotFoundOrError(gitutil.NewError(err), "get commit")
		return
	}

	apiCommit, err := gitCommitToAPICommit(commit, c)
Repository: gogs/gogs
File: internal/db/repo_tag.go (Go)

Code before:
package db

import (
	"fmt"

	"github.com/gogs/git-module"
)

type Tag struct {
	RepoPath string
	Name     string

	IsProtected bool
	Commit      *git.Commit
}

func (ta *Tag) GetCommit() (*git.Commit, error) {
	gitRepo, err := git.Open(ta.RepoPath)
	if err != nil {
		return nil, fmt.Errorf("open repository: %v", err)
	}
	return gitRepo.TagCommit(ta.Name)
}

func GetTagsByPath(path string) ([]*Tag, error) {
	gitRepo, err := git.Open(path)
	if err != nil {
		return nil, fmt.Errorf("open repository: %v", err)
	}


Review comment (security):
```suggestion
// Copyright 2021 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package db
```

Code after:
// Copyright 2021 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package db

import (
	"fmt"

	"github.com/gogs/git-module"
)

type Tag struct {
	RepoPath string
	Name     string

	IsProtected bool
	Commit      *git.Commit
}

func (ta *Tag) GetCommit() (*git.Commit, error) {
	gitRepo, err := git.Open(ta.RepoPath)
	if err != nil {
		return nil, fmt.Errorf("open repository: %v", err)
	}
	return gitRepo.TagCommit(ta.Name)
}

func GetTagsByPath(path string) ([]*Tag, error) {
	gitRepo, err := git.Open(path)
Repository: gogs/gogs
File: internal/route/api/v1/repo/tag.go (Go)

Code before:
package repo

import (
	"gogs.io/gogs/internal/context"
	"gogs.io/gogs/internal/route/api/v1/convert"
)

func ListTags(c *context.APIContext) {
	tags, err := c.Repo.Repository.GetTags()
	if err != nil {
		c.Error(err, "get tags")
		return
	}

	apiTags := make([]*convert.Tag, len(tags))
	for i := range tags {
		commit, err := tags[i].GetCommit()
		if err != nil {
			c.Error(err, "get commit")
			return
		}
		apiTags[i] = convert.ToTag(tags[i], commit)
	}

	c.JSONSuccess(&apiTags)
}


Review comment (security):
```suggestion
// Copyright 2021 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package repo
```

Code after:
// Copyright 2021 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package repo

import (
	"gogs.io/gogs/internal/context"
	"gogs.io/gogs/internal/route/api/v1/convert"
)

func ListTags(c *context.APIContext) {
	tags, err := c.Repo.Repository.GetTags()
	if err != nil {
		c.Error(err, "get tags")
		return
	}

	apiTags := make([]*convert.Tag, len(tags))
	for i := range tags {
		commit, err := tags[i].GetCommit()
		if err != nil {
			c.Error(err, "get commit")
			return
		}
		apiTags[i] = convert.ToTag(tags[i], commit)
	}

	c.JSONSuccess(&apiTags)
}
Repository: gogs/gogs
File: internal/db/migrations/v20.go (Go)

Code before:

import (
	"github.com/pkg/errors"
	"xorm.io/xorm"

	"gogs.io/gogs/internal/cryptoutil"
)

func migrateAccessTokenSHA1(x *xorm.Engine) (err error) {
	exist, err := x.IsTableExist("access_token")
	if err != nil {
		return errors.Wrap(err, "is table exists")
	} else if !exist {
		return nil
	}

	sess := x.NewSession()
	defer sess.Close()
	if err = sess.Begin(); err != nil {
		return err
	}

	type accessToken struct {
		ID     int64
		Sha1   string
		SHA256 string
	}
	var accessTokens []*accessToken
	err = sess.Table("access_token").Where("sha256 IS NULL").Find(&accessTokens)
	if err != nil {
		return errors.Wrap(err, "query access_token")
	}

	for _, t := range accessTokens {
		sha256 := cryptoutil.SHA256(t.Sha1)
		if _, err := sess.Table("access_token").ID(t.ID).Update(map[string]interface{}{"sha256": sha256}); err != nil {
			return errors.Wrap(err, "update sha256")
		}
	}

	return sess.Commit()
}


Review comment (suggestion):
```suggestion
		SHA256 string `xorm:"VARCHAR(64)"`
```

Code after:

import (
	"github.com/pkg/errors"
	"gorm.io/gorm"

	"gogs.io/gogs/internal/cryptoutil"
)

func migrateAccessTokenToSHA256(db *gorm.DB) error {
	return db.Transaction(func(tx *gorm.DB) error {
		// 1. Add column without constraints because all rows have NULL values for the
		// "sha256" column.
		type accessToken struct {
			ID     int64
			Sha1   string
			SHA256 string `gorm:"TYPE:VARCHAR(64)"`
		}
		err := tx.Migrator().AddColumn(&accessToken{}, "SHA256")
		if err != nil {
			return errors.Wrap(err, "add column")
		}

		// 2. Generate SHA256 for existing rows from their values in the "sha1" column.
		var accessTokens []*accessToken
		err = tx.Where("sha256 IS NULL").Find(&accessTokens).Error
		if err != nil {
			return errors.Wrap(err, "list")
		}

		for _, t := range accessTokens {
			sha256 := cryptoutil.SHA256(t.Sha1)
			err = tx.Model(&accessToken{}).Where("id = ?", t.ID).Update("sha256", sha256).Error
			if err != nil {
				return errors.Wrap(err, "update")
			}
		}

		// 3. We are now safe to apply constraints to the "sha256" column.
		type accessTokenWithConstraint struct {
			SHA256 string `gorm:"type:VARCHAR(64);unique;not null"`
		}
		err = tx.Table("access_token").AutoMigrate(&accessTokenWithConstraint{})
		if err != nil {
			return errors.Wrap(err, "auto migrate")
		}

		return nil
	})
}