github.com/icyphox/x@v0.0.355-0.20220311094250-029bd783e8b8/sqlcon/connector.go (about)

     1  /*
     2   * Copyright © 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   *
    16   * @author		Aeneas Rekkas <aeneas+oss@aeneas.io>
    17   * @copyright 	2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
    18   * @license 	Apache-2.0
    19   */
    20  
    21  // Package sqlcon provides helpers for dealing with SQL connectivity.
    22  package sqlcon
    23  
    24  import (
    25  	"fmt"
    26  	"net/url"
    27  	"runtime"
    28  	"strings"
    29  
    30  	"github.com/pkg/errors"
    31  )
    32  
    33  func cleanURLQuery(in url.Values) (out url.Values) {
    34  	out, _ = url.ParseQuery(in.Encode())
    35  	out.Del("max_conns")
    36  	out.Del("max_idle_conns")
    37  	out.Del("max_conn_lifetime")
    38  	out.Del("max_idle_conn_time")
    39  	out.Del("parseTime")
    40  	return out
    41  }
    42  
    43  // GetDriverName returns the driver name of a given DSN.
    44  func GetDriverName(dsn string) string {
    45  	return strings.Split(dsn, "://")[0]
    46  }
    47  
    48  func classifyDSN(dsn string) string {
    49  	scheme := strings.Split(dsn, "://")[0]
    50  	parts := strings.Split(dsn, "@")
    51  	host := parts[len(parts)-1]
    52  	return fmt.Sprintf("%s://*:*@%s", scheme, host)
    53  }
    54  
    55  func maxParallelism() int {
    56  	maxProcs := runtime.GOMAXPROCS(0)
    57  	numCPU := runtime.NumCPU()
    58  	if maxProcs < numCPU {
    59  		return maxProcs
    60  	}
    61  	return numCPU
    62  }
    63  
    64  func parseQuery(dsn string) (clean string, query url.Values, err error) {
    65  	query = url.Values{}
    66  	parts := strings.Split(dsn, "?")
    67  	clean = parts[0]
    68  	if len(parts) == 2 {
    69  		if query, err = url.ParseQuery(parts[1]); err != nil {
    70  			return "", query, errors.WithStack(err)
    71  		}
    72  	}
    73  	return
    74  }