Code Monkey home page Code Monkey logo

Comments (2)

aidanmelen avatar aidanmelen commented on August 14, 2024

According to the gosnowflakedb docs for Executing Multiple Statements in One Call, we should be using QueryContext like similar to ExecContext.

from terraform-provider-snowsql.

aidanmelen avatar aidanmelen commented on August 14, 2024

Example code for a multistatement query context and process all of the resulting query rows:

package main

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/snowflakedb/gosnowflake"
)

func main() {
	// Initialize the `statements` variable with multiple Snowflake query statement strings
	statements := `
          SHOW ROLES LIKE 'SYSADMIN';
          SHOW ROLES LIKE 'ACCOUNTADMIN';
        `

	// Set up a Snowflake connection
	cfg := &gosnowflake.Config{
		Account:   os.Getenv("SNOWFLAKE_ACCOUNT"),
		User:      os.Getenv("SNOWFLAKE_USER"),
		Password:  os.Getenv("SNOWFLAKE_PASSWORD"),
		Database:  os.Getenv("SNOWFLAKE_DATABASE"),
		Schema:    os.Getenv("SNOWFLAKE_SCHEMA"),
		Warehouse: os.Getenv("SNOWFLAKE_WAREHOUSE"),
	}
	dsn, err := gosnowflake.DSN(cfg)
	if err != nil {
		log.Fatal(err)
	}
	db, err := sql.Open("snowflake", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Set up a context with a timeout
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
	defer cancel()

	// Query Snowflake using the WithMultiStatement method
	multiStmtCtx, err := gosnowflake.WithMultiStatement(ctx, 0)
	if err != nil {
		log.Fatal(err)
	}
	rows, err := db.QueryContext(multiStmtCtx, statements)

	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	// Process all the rows from all the queries and store the results in a list
	results := make([]map[string]interface{}, 0)
	processRows := func(rows *sql.Rows) error {
		for rows.Next() {
			columns, err := rows.Columns()
			if err != nil {
				return err
			}
			values := make([]interface{}, len(columns))
			for i := range columns {
				values[i] = new(interface{})
			}
			err = rows.Scan(values...)
			if err != nil {
				return err
			}
			rowMap := make(map[string]interface{})
			for i, col := range columns {
				rowMap[col] = *values[i].(*interface{})
			}
			results = append(results, rowMap)
		}
		if err := rows.Err(); err != nil {
			return err
		}
		return nil
	}

	if err := processRows(rows); err != nil {
		log.Fatal(err)
	}

	for rows.NextResultSet() {
		if err := processRows(rows); err != nil {
			log.Fatal(err)
		}
	}

	marshalledResults, _ := json.Marshal(results)
	fmt.Printf("%v", string(marshalledResults))
}

and run with:

$ go run main.go | jq
[
  {
    "assigned_to_users": "0",
    "comment": "System administrator can create and manage databases and warehouses.",
    "created_on": "2021-11-02T19:45:29.136-07:00",
    "granted_roles": "0",
    "granted_to_roles": "1",
    "is_current": "N",
    "is_default": "N",
    "is_inherited": "Y",
    "name": "SYSADMIN",
    "owner": ""
  },
  {
    "assigned_to_users": "2",
    "comment": "Account administrator can manage all aspects of the account.",
    "created_on": "2021-11-02T19:45:29.108-07:00",
    "granted_roles": "2",
    "granted_to_roles": "0",
    "is_current": "Y",
    "is_default": "Y",
    "is_inherited": "N",
    "name": "ACCOUNTADMIN",
    "owner": ""
  }
]

from terraform-provider-snowsql.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.