Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Basic CREATE USER implementation #704

Merged
merged 2 commits into from
Jan 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions enginetest/enginetests.go
Original file line number Diff line number Diff line change
Expand Up @@ -1003,6 +1003,12 @@ func TestScripts(t *testing.T, harness Harness) {
}
}

func TestUsersAndPrivileges(t *testing.T, harness Harness) {
for _, script := range UserPrivTests {
TestScript(t, harness, script)
}
}

func TestComplexIndexQueries(t *testing.T, harness Harness) {
for _, script := range ComplexIndexQueries {
TestScript(t, harness, script)
Expand Down
4 changes: 4 additions & 0 deletions enginetest/memory_engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,10 @@ func TestScripts(t *testing.T) {
enginetest.TestScripts(t, enginetest.NewMemoryHarness("default", 1, testNumPartitions, true, mergableIndexDriver))
}

func TestUsersAndPrivileges(t *testing.T) {
enginetest.TestUsersAndPrivileges(t, enginetest.NewMemoryHarness("default", 1, testNumPartitions, true, mergableIndexDriver))
}

func TestComplexIndexQueries(t *testing.T) {
harness := enginetest.NewMemoryHarness("default", 1, testNumPartitions, true, mergableIndexDriver)
enginetest.TestComplexIndexQueries(t, harness)
Expand Down
111 changes: 111 additions & 0 deletions enginetest/user_priv_queries.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// Copyright 2022 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package enginetest

import (
"time"

"github.com/dolthub/go-mysql-server/sql"
)

// UserPrivTests test the user, authentication, and privilege systems.
var UserPrivTests = []ScriptTest{
{
Name: "Basic user creation",
SetUpScript: []string{
"CREATE USER testuser@`127.0.0.1`;",
},
Assertions: []ScriptTestAssertion{
{
Query: "CREATE USER testuser@`127.0.0.1`;",
ExpectedErr: sql.ErrUserCreationFailure,
},
{
Query: "CREATE USER IF NOT EXISTS testuser@`127.0.0.1`;",
Expected: []sql.Row{{sql.NewOkResult(0)}},
},
{
Query: "INSERT INTO mysql.user (Host, User, ssl_cipher, x509_issuer, x509_subject) VALUES ('localhost', 'testuser2', '', '', '');",
Expected: []sql.Row{{sql.NewOkResult(1)}},
},
{
Query: "SELECT * FROM mysql.user WHERE User = 'root';",
Expected: []sql.Row{
{
"localhost", // Host
"root", // User
"Y", // Select_priv
"Y", // Insert_priv
"Y", // Update_priv
"Y", // Delete_priv
"Y", // Create_priv
"Y", // Drop_priv
"Y", // Reload_priv
"Y", // Shutdown_priv
"Y", // Process_priv
"Y", // File_priv
"Y", // Grant_priv
"Y", // References_priv
"Y", // Index_priv
"Y", // Alter_priv
"Y", // Show_db_priv
"Y", // Super_priv
"Y", // Create_tmp_table_priv
"Y", // Lock_tables_priv
"Y", // Execute_priv
"Y", // Repl_slave_priv
"Y", // Repl_client_priv
"Y", // Create_view_priv
"Y", // Show_view_priv
"Y", // Create_routine_priv
"Y", // Alter_routine_priv
"Y", // Create_user_priv
"Y", // Event_priv
"Y", // Trigger_priv
"Y", // Create_tablespace_priv
"", // ssl_type
"", // ssl_cipher
"", // x509_issuer
"", // x509_subject
0, // max_questions
0, // max_updates
0, // max_connections
0, // max_user_connections
"caching_sha2_password", // plugin
nil, // authentication_string
"N", // password_expired
time.Unix(0, 0).UTC(), // password_last_changed
nil, // password_lifetime
"N", // account_locked
"Y", // Create_role_priv
"Y", // Drop_role_priv
nil, // Password_reuse_history
nil, // Password_reuse_time
nil, // Password_require_current
nil, // User_attributes
},
},
},
{
Query: "SELECT Host, User FROM mysql.user;",
Expected: []sql.Row{
{"localhost", "root"},
{"localhost", "testuser2"},
{"127.0.0.1", "testuser"},
},
},
},
},
}
2 changes: 1 addition & 1 deletion sql/analyzer/analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ type Analyzer struct {
// Batches of Rules to apply.
Batches []*Batch
// Catalog of databases and registered functions.
Catalog sql.Catalog
Catalog *Catalog
// ProcedureCache is a cache of stored procedures.
ProcedureCache *ProcedureCache
}
Expand Down
14 changes: 11 additions & 3 deletions sql/analyzer/catalog.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,24 +22,31 @@ import (
"github.com/dolthub/go-mysql-server/internal/similartext"
"github.com/dolthub/go-mysql-server/sql"
"github.com/dolthub/go-mysql-server/sql/expression/function"
"github.com/dolthub/go-mysql-server/sql/grant_tables"
)

type Catalog struct {
GrantTables *grant_tables.GrantTables

provider sql.DatabaseProvider
builtInFunctions function.Registry
mu sync.RWMutex
locks sessionLocks
}

var _ sql.Catalog = (*Catalog)(nil)
var _ sql.FunctionProvider = (*Catalog)(nil)

type tableLocks map[string]struct{}

type dbLocks map[string]tableLocks

type sessionLocks map[uint32]dbLocks

// NewCatalog returns a new empty Catalog with the given provider
func NewCatalog(provider sql.DatabaseProvider) sql.Catalog {
func NewCatalog(provider sql.DatabaseProvider) *Catalog {
return &Catalog{
GrantTables: grant_tables.CreateEmptyGrantTables(),
provider: provider,
builtInFunctions: function.NewRegistry(),
locks: make(sessionLocks),
Expand All @@ -50,8 +57,6 @@ func NewDatabaseProvider(dbs ...sql.Database) sql.DatabaseProvider {
return sql.NewDatabaseProvider(dbs...)
}

var _ sql.FunctionProvider = (*Catalog)(nil)

func (c *Catalog) AllDatabases() []sql.Database {
c.mu.RLock()
defer c.mu.RUnlock()
Expand Down Expand Up @@ -95,6 +100,9 @@ func (c *Catalog) HasDB(db string) bool {
func (c *Catalog) Database(db string) (sql.Database, error) {
c.mu.RLock()
defer c.mu.RUnlock()
if strings.ToLower(db) == "mysql" {
return c.GrantTables, nil
}
return c.provider.Database(db)
}

Expand Down
2 changes: 1 addition & 1 deletion sql/analyzer/catalog_locks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,5 +55,5 @@ func TestCatalogLockTable(t *testing.T) {
},
}

require.Equal(expected, c.(*Catalog).locks)
require.Equal(expected, c.locks)
}
24 changes: 24 additions & 0 deletions sql/analyzer/privileges.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Copyright 2021 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package analyzer

import "github.com/dolthub/go-mysql-server/sql"

// checkPrivileges verifies the given statement (node n) by checking that the calling user has the necessary privileges
// to execute it.
func checkPrivileges(ctx *sql.Context, a *Analyzer, n sql.Node, scope *Scope) (sql.Node, error) {
//TODO: implement this
return n, nil
}
1 change: 1 addition & 0 deletions sql/analyzer/rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
// OnceBeforeDefault contains the rules to be applied just once before the
// DefaultRules.
var OnceBeforeDefault = []Rule{
{"check_privileges", checkPrivileges},
{"validate_offset_and_limit", validateLimitAndOffset},
{"validate_create_table", validateCreateTable},
{"load_stored_procedures", loadStoredProcedures},
Expand Down
11 changes: 0 additions & 11 deletions sql/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,17 +273,6 @@ type SchemaTarget interface {
WithTargetSchema(Schema) (Node, error)
}

// Partition represents a partition from a SQL table.
type Partition interface {
Key() []byte
}

// PartitionIter is an iterator that retrieves partitions.
type PartitionIter interface {
Closer
Next(*Context) (Partition, error)
}

// Table represents the backend of a SQL table.
type Table interface {
Nameable
Expand Down
5 changes: 4 additions & 1 deletion sql/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -380,8 +380,11 @@ var (
// ErrUnknownConstraintDefinition is returned when an unknown constraint type is used
ErrUnknownConstraintDefinition = errors.NewKind("unknown constraint definition: %s, %T")

// ErrInvalidCheckConstraint is returned when a check constraint is defined incorrectly
// ErrInvalidCheckConstraint is returned when a check constraint is defined incorrectly
ErrInvalidCheckConstraint = errors.NewKind("invalid constraint definition: %s")

// ErrUserCreationFailure is returned when attempting to create a user and it fails for any reason.
ErrUserCreationFailure = errors.NewKind("Operation CREATE USER failed for %s")
)

func CastSQLError(err error) (*mysql.SQLError, error, bool) {
Expand Down
3 changes: 2 additions & 1 deletion sql/expression/function/time_format.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ import (
"fmt"
"time"

"github.com/lestrrat-go/strftime"

"github.com/dolthub/go-mysql-server/sql"
"github.com/dolthub/go-mysql-server/sql/expression"
"github.com/lestrrat-go/strftime"
)

var mysqlTimeFormatSpec = strftime.NewSpecificationSet()
Expand Down
3 changes: 2 additions & 1 deletion sql/expression/function/time_format_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ import (
"testing"
"time"

"github.com/stretchr/testify/assert"

"github.com/dolthub/go-mysql-server/sql"
"github.com/dolthub/go-mysql-server/sql/expression"
"github.com/stretchr/testify/assert"
)

func TestTimeFormatting(t *testing.T) {
Expand Down
99 changes: 99 additions & 0 deletions sql/grant_tables/grant_table.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// Copyright 2022 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package grant_tables

import (
"github.com/dolthub/go-mysql-server/sql"
"github.com/dolthub/go-mysql-server/sql/in_mem_table"
)

type grantTable struct {
name string
sch sql.Schema
data *in_mem_table.InMemTableData
}

var _ sql.Table = (*grantTable)(nil)
var _ sql.InsertableTable = (*grantTable)(nil)
var _ sql.UpdatableTable = (*grantTable)(nil)
var _ sql.DeletableTable = (*grantTable)(nil)
var _ sql.ReplaceableTable = (*grantTable)(nil)
var _ sql.TruncateableTable = (*grantTable)(nil)

// newGrantTable returns a new Grant Table with the given schema and keys.
func newGrantTable(name string, sch sql.Schema, primaryKey in_mem_table.InMemTableDataKey, secondaryKeys ...in_mem_table.InMemTableDataKey) *grantTable {
return &grantTable{
name: name,
sch: sch,
data: in_mem_table.NewInMemTableData(sch, primaryKey, secondaryKeys),
}
}

// Name implements the interface sql.Table.
func (g *grantTable) Name() string {
return g.name
}

// String implements the interface sql.Table.
func (g *grantTable) String() string {
return g.name
}

// Schema implements the interface sql.Table.
func (g *grantTable) Schema() sql.Schema {
return g.sch.Copy()
}

// Partitions implements the interface sql.Table.
func (g *grantTable) Partitions(ctx *sql.Context) (sql.PartitionIter, error) {
return sql.PartitionsToPartitionIter(dummyPartition{}), nil
}

// PartitionRows implements the interface sql.Table.
func (g *grantTable) PartitionRows(ctx *sql.Context, partition sql.Partition) (sql.RowIter, error) {
return g.data.ToRowIter(), nil
}

// Inserter implements the interface sql.InsertableTable.
func (g *grantTable) Inserter(ctx *sql.Context) sql.RowInserter {
return in_mem_table.NewInMemTableDataEditor(g.data)
}

// Updater implements the interface sql.UpdatableTable.
func (g *grantTable) Updater(ctx *sql.Context) sql.RowUpdater {
return in_mem_table.NewInMemTableDataEditor(g.data)
}

// Deleter implements the interface sql.DeletableTable.
func (g *grantTable) Deleter(ctx *sql.Context) sql.RowDeleter {
return in_mem_table.NewInMemTableDataEditor(g.data)
}

// Replacer implements the interface sql.ReplaceableTable.
func (g *grantTable) Replacer(ctx *sql.Context) sql.RowReplacer {
return in_mem_table.NewInMemTableDataEditor(g.data)
}

// Truncate implements the interface sql.TruncateableTable.
func (g *grantTable) Truncate(ctx *sql.Context) (int, error) {
count := g.data.Count()
g.data.Clear()
return int(count), nil
}

// Data returns the in-memory table data for the grant table.
func (g *grantTable) Data() *in_mem_table.InMemTableData {
return g.data
}
Loading