// Copyright 2024 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 main import ( "context" "fmt" "time" "github.com/dolthub/dolt/go/libraries/utils/svcs" "github.com/dolthub/go-mysql-server/sql" "github.com/jackc/pgx/v5" dserver "github.com/dolthub/doltgresql/server" "github.com/dolthub/doltgresql/servercfg" "github.com/dolthub/doltgresql/servercfg/cfgdetails" ) // CreateDoltgresServer creates and returns a Doltgres server. func CreateDoltgresServer() (controller *svcs.Controller, port int, err error) { port, err = sql.GetEmptyPort() if err != nil { return nil, 0, err } address := "127.0.0.1" logLevel := cfgdetails.LogLevel_Panic controller, err = dserver.RunInMemory(&servercfg.DoltgresConfig{ DoltgresConfig: cfgdetails.DoltgresConfig{ LogLevelStr: &logLevel, ListenerConfig: &cfgdetails.DoltgresListenerConfig{ PortNumber: &port, HostStr: &address, }, }, }, dserver.NewListener) if err != nil { return nil, 0, err } defer func() { if err != nil { controller.Stop() } }() return controller, port, func() error { // The connection attempt may be made before the server has grabbed the port, so we'll retry the first // connection a few times. var conn *pgx.Conn var err error ctx := context.Background() for i := 0; i < 3; i++ { conn, err = pgx.Connect(ctx, fmt.Sprintf("postgres://postgres:password@127.0.0.1:%d/", port)) if err == nil { break } else { time.Sleep(time.Second) } } if err != nil { return err } return conn.Close(ctx) }() }