go-hep.org/x/hep@v0.38.1/groot/rsql/rsqldrv/connector.go (about)

     1  // Copyright ©2019 The go-hep Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package rsqldrv // import "go-hep.org/x/hep/groot/rsql/rsqldrv"
     6  
     7  import (
     8  	"context"
     9  	"database/sql"
    10  	"database/sql/driver"
    11  
    12  	"go-hep.org/x/hep/groot/riofs"
    13  )
    14  
    15  // Connector returns a database/sql/driver.Connector from a ROOT file.
    16  //
    17  // Connector can be used to open a database/sql.DB from an already
    18  // open ROOT file.
    19  func Connector(file *riofs.File) driver.Connector {
    20  	c := &rootConnector{file: file}
    21  	return c
    22  }
    23  
    24  type rootConnector struct {
    25  	drv  rootDriver
    26  	file *riofs.File
    27  }
    28  
    29  // Connect returns a connection to the database.
    30  // Connect may return a cached connection (one previously
    31  // closed), but doing so is unnecessary; the sql package
    32  // maintains a pool of idle connections for efficient re-use.
    33  //
    34  // The provided context.Context is for dialing purposes only
    35  // (see net.DialContext) and should not be stored or used for
    36  // other purposes.
    37  //
    38  // The returned connection is only used by one goroutine at a
    39  // time.
    40  func (c *rootConnector) Connect(ctx context.Context) (driver.Conn, error) {
    41  	return c.drv.connect(c.file), nil
    42  }
    43  
    44  // Driver returns the underlying Driver of the Connector,
    45  // mainly to maintain compatibility with the Driver method
    46  // on sql.DB.
    47  func (c *rootConnector) Driver() driver.Driver {
    48  	return &c.drv
    49  }
    50  
    51  // OpenDB opens a database/sql.DB from an already open ROOT file.
    52  func OpenDB(file *riofs.File) *sql.DB {
    53  	return sql.OpenDB(Connector(file))
    54  }
    55  
    56  var (
    57  	_ driver.Connector = (*rootConnector)(nil)
    58  )