Skip to content

Commit

Permalink
Create connector in mssql
Browse files Browse the repository at this point in the history
  • Loading branch information
RudraNirvan committed May 22, 2022
1 parent 1598eaf commit 1818e42
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package main

import (
"context"
"database/sql"
"flag"
"fmt"
"log"

mssql "github.com/denisenkom/go-mssqldb"
)

var (
debug = flag.Bool("debug", true, "enable debugging")
password = flag.String("password", "", "the client secret for the app/client ID")
port *int = flag.Int("port", 1433, "the database port")
server = flag.String("server", "", "the database server")
database = flag.String("database", "", "the database name")
)

func main() {
flag.Parse()

if *debug {
fmt.Printf(" password:%s\n", *password)
fmt.Printf(" port:%d\n", *port)
fmt.Printf(" server:%s\n", *server)
fmt.Printf(" database:%s\n", *database)
}

connString := fmt.Sprintf("server=%s;password=%s;port=%d;database=%s;fedauth=ActiveDirectoryServicePrincipalAccessToken;", *server, *password, *port, *database)
if *debug {
fmt.Printf(" connString:%s\n", connString)
}

tokenProviderWithCtx := func(ctx context.Context) (string, error) {
return "access_token", nil
}

connector, err := mssql.NewConnectorWithAccessTokenProvider(connString, tokenProviderWithCtx)
conn := sql.OpenDB(connector)

//conn, err := sql.Open(azuread.DriverName, connString)
if err != nil {
log.Fatal("Open connection failed:", err.Error())
}
defer conn.Close()

stmt, err := conn.Prepare("select 1, 'abc'")
if err != nil {
log.Fatal("Prepare failed:", err.Error())
}
defer stmt.Close()

row := stmt.QueryRow()
var somenumber int64
var somechars string
err = row.Scan(&somenumber, &somechars)
if err != nil {
log.Fatal("Scan failed:", err.Error())
}
fmt.Printf("somenumber:%d\n", somenumber)
fmt.Printf("somechars:%s\n", somechars)

fmt.Printf("bye\n")
}
14 changes: 14 additions & 0 deletions mssql.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,20 @@ func NewConnector(dsn string) (*Connector, error) {
return c, nil
}

// NewConnectorWithAccessTokenProvider creates a new connector from a DSN using the given
// access token provider. The returned connector may be used with sql.OpenDB.
func NewConnectorWithAccessTokenProvider(dsn string, tokenProvider func(ctx context.Context) (string, error)) (*Connector, error) {
params, _, err := msdsn.Parse(dsn)
if err != nil {
return nil, err
}

return NewSecurityTokenConnector(
params,
tokenProvider,
)
}

// NewConnectorConfig creates a new Connector for a DSN Config struct.
// The returned connector may be used with sql.OpenDB.
func NewConnectorConfig(config msdsn.Config) *Connector {
Expand Down

0 comments on commit 1818e42

Please sign in to comment.