github.com/dolthub/go-mysql-server@v0.18.0/driver/_example/create.go (about)

     1  // Copyright 2020-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 main
    16  
    17  import (
    18  	"context"
    19  	"time"
    20  
    21  	"github.com/dolthub/go-mysql-server/driver"
    22  	"github.com/dolthub/go-mysql-server/memory"
    23  	"github.com/dolthub/go-mysql-server/sql"
    24  	"github.com/dolthub/go-mysql-server/sql/types"
    25  )
    26  
    27  type factory struct{}
    28  
    29  func (factory) Resolve(name string, options *driver.Options) (string, sql.DatabaseProvider, error) {
    30  	provider := memory.NewDBProvider(
    31  		createTestDatabase(),
    32  	)
    33  	return name, provider, nil
    34  }
    35  
    36  func createTestDatabase() *memory.Database {
    37  	const (
    38  		dbName    = "mydb"
    39  		tableName = "mytable"
    40  	)
    41  
    42  	db := memory.NewDatabase(dbName)
    43  	pro := memory.NewDBProvider(db)
    44  	ctx := sql.NewContext(context.Background(), sql.WithSession(memory.NewSession(sql.NewBaseSession(), pro)))
    45  
    46  	table := memory.NewTable(db, tableName, sql.NewPrimaryKeySchema(sql.Schema{
    47  		{Name: "name", Type: types.Text, Nullable: false, Source: tableName},
    48  		{Name: "email", Type: types.Text, Nullable: false, Source: tableName},
    49  		{Name: "phone_numbers", Type: types.JSON, Nullable: false, Source: tableName},
    50  		{Name: "created_at", Type: types.Timestamp, Nullable: false, Source: tableName},
    51  	}), nil)
    52  
    53  	db.AddTable(tableName, table)
    54  
    55  	table.Insert(ctx, sql.NewRow("John Doe", "john@doe.com", types.JSONDocument{Val: []string{"555-555-555"}}, time.Now()))
    56  	table.Insert(ctx, sql.NewRow("John Doe", "johnalt@doe.com", types.JSONDocument{Val: []string{}}, time.Now()))
    57  	table.Insert(ctx, sql.NewRow("Jane Doe", "jane@doe.com", types.JSONDocument{Val: []string{}}, time.Now()))
    58  	table.Insert(ctx, sql.NewRow("Evil Bob", "evilbob@gmail.com", types.JSONDocument{Val: []string{"555-666-555", "666-666-666"}}, time.Now()))
    59  	return db
    60  }