github.com/dolthub/go-mysql-server@v0.18.0/sql/mysql_db/mysql_db_test.go (about)

     1  // Copyright 2023 Dolthub, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package mysql_db
    16  
    17  import (
    18  	"testing"
    19  
    20  	"github.com/stretchr/testify/require"
    21  
    22  	"github.com/dolthub/go-mysql-server/sql"
    23  )
    24  
    25  type capturingPersistence struct {
    26  	buf []byte
    27  }
    28  
    29  func (p *capturingPersistence) Persist(ctx *sql.Context, data []byte) error {
    30  	p.buf = data
    31  	return nil
    32  }
    33  
    34  func TestMySQLDbOverwriteUsersAndGrantsData(t *testing.T) {
    35  	ctx := sql.NewEmptyContext()
    36  	db := CreateEmptyMySQLDb()
    37  	p := &capturingPersistence{}
    38  	db.SetPersister(p)
    39  
    40  	db.AddRootAccount()
    41  	ed := db.Editor()
    42  	db.Persist(ctx, ed)
    43  	ed.Close()
    44  
    45  	require.NotNil(t, p.buf)
    46  
    47  	// A root@localhost user was created.
    48  	rd := db.Reader()
    49  	root := db.GetUser(rd, "root", "localhost", false)
    50  	rd.Close()
    51  	require.NotNil(t, root)
    52  
    53  	onlyRoot := p.buf
    54  
    55  	ed = db.Editor()
    56  	db.AddSuperUser(ed, "aaron", "localhost", "")
    57  	db.AddSuperUser(ed, "brian", "localhost", "")
    58  	db.AddSuperUser(ed, "tim", "localhost", "")
    59  	db.Persist(ctx, ed)
    60  	ed.Close()
    61  
    62  	var numUsers int
    63  	rd = db.Reader()
    64  	rd.VisitUsers(func(*User) {
    65  		numUsers += 1
    66  	})
    67  	rd.Close()
    68  	require.Equal(t, 4, numUsers)
    69  
    70  	ed = db.Editor()
    71  	require.NoError(t, db.OverwriteUsersAndGrantData(ctx, ed, onlyRoot))
    72  	ed.Close()
    73  
    74  	numUsers = 0
    75  	rd = db.Reader()
    76  	rd.VisitUsers(func(*User) {
    77  		numUsers += 1
    78  	})
    79  	require.Equal(t, 1, numUsers)
    80  
    81  	root = db.GetUser(rd, "root", "localhost", false)
    82  	require.NotNil(t, root)
    83  
    84  	tim := db.GetUser(rd, "tim", "localhost", false)
    85  	require.Nil(t, tim)
    86  
    87  	rd.Close()
    88  }