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

     1  // Copyright 2021 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 sql
    16  
    17  import (
    18  	"sort"
    19  	"strings"
    20  	"sync"
    21  
    22  	"github.com/dolthub/go-mysql-server/internal/similartext"
    23  )
    24  
    25  // databaseProvider is a collection of Database.
    26  type databaseProvider struct {
    27  	dbs map[string]Database
    28  	mu  *sync.RWMutex
    29  }
    30  
    31  var _ DatabaseProvider = databaseProvider{}
    32  
    33  func NewDatabaseProvider(dbs ...Database) DatabaseProvider {
    34  	dbMap := make(map[string]Database, len(dbs))
    35  	for _, db := range dbs {
    36  		dbMap[strings.ToLower(db.Name())] = db
    37  	}
    38  	return databaseProvider{
    39  		dbs: dbMap,
    40  		mu:  &sync.RWMutex{},
    41  	}
    42  }
    43  
    44  // Database returns the Database with the given name if it exists.
    45  func (d databaseProvider) Database(ctx *Context, name string) (Database, error) {
    46  	d.mu.RLock()
    47  	defer d.mu.RUnlock()
    48  
    49  	db, ok := d.dbs[strings.ToLower(name)]
    50  	if ok {
    51  		return db, nil
    52  	}
    53  
    54  	names := make([]string, 0, len(d.dbs))
    55  	for n := range d.dbs {
    56  		names = append(names, n)
    57  	}
    58  
    59  	similar := similartext.Find(names, name)
    60  	return nil, ErrDatabaseNotFound.New(name + similar)
    61  }
    62  
    63  // HasDatabase returns the Database with the given name if it exists.
    64  func (d databaseProvider) HasDatabase(ctx *Context, name string) bool {
    65  	d.mu.RLock()
    66  	defer d.mu.RUnlock()
    67  
    68  	_, ok := d.dbs[strings.ToLower(name)]
    69  	return ok
    70  }
    71  
    72  // AllDatabases returns the Database with the given name if it exists.
    73  func (d databaseProvider) AllDatabases(*Context) []Database {
    74  	d.mu.RLock()
    75  	defer d.mu.RUnlock()
    76  
    77  	all := make([]Database, 0, len(d.dbs))
    78  	for _, db := range d.dbs {
    79  		all = append(all, db)
    80  	}
    81  
    82  	sort.Slice(all, func(i, j int) bool {
    83  		return all[i].Name() < all[j].Name()
    84  	})
    85  
    86  	return all
    87  }