# Go

Github.com/quill-sql/quill-go.

```sh
go get github.com/quill-sql/quill-go
```

```go
import (
	"encoding/json"
	"log"
	"net/http"
	"os"

	"github.com/quill-sql/quill-go/pkg/core"
	"github.com/quill-sql/quill-go/pkg/models"
)

dbURL := os.Getenv("POSTGRES_READ")
quill, err := core.NewQuill(models.QuillClientParams{
	PrivateKey:               os.Getenv("QUILL_PRIVATE_KEY"),
	DatabaseConnectionString: &dbURL,
	DatabaseType:             "postgresql",
})
if err != nil {
	log.Fatal(err)
}

// authenticate is your own auth middleware
http.Handle("/quill", authenticate(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	orgID := r.Context().Value(orgIDKey).(string)
	var body models.QuillRequest
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	result, err := quill.Query(models.QuillQueryParams{
		Tenants:  []interface{}{map[string]interface{}{"tenantField": "organization_id", "tenantIds": []interface{}{orgID}}},
		Metadata: body.Metadata,
	})
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(result)
})))
```

## NewQuill

```go
func NewQuill(params models.QuillClientParams) (*core.Quill, error)
```

| Field                      | Default                |                                                                                                                                                         |
| -------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PrivateKey`               | required               | `string`: the private key of your Quill environment                                                                                                     |
| `DatabaseType`             | required               | `"postgresql"`, `"redshift"`, `"snowflake"`, `"bigquery"`, `"mysql"`, `"clickhouse"`, `"mssql"` or `"databricks"`                                       |
| `DatabaseConnectionString` |                        | `*string`; used over `DatabaseConfig`                                                                                                                   |
| `DatabaseConfig`           |                        | the connection as a struct of package `pkg/db`, by `DatabaseType`, below                                                                                |
| `Cache`                    |                        | `*models.CacheCredentials{CacheType: "redis" \| "rediss", Host, Port, Username, Password, TTL}`: caches results in Redis for `TTL`, 24 hours by default |
| `MetadataServerURL`        | `https://api.quill.co` | `*string`                                                                                                                                               |

| `DatabaseType`               | `DatabaseConfig`                                                                                    |
| ---------------------------- | --------------------------------------------------------------------------------------------------- |
| `"postgresql"`, `"redshift"` | `db.PostgresConnectionConfig{ConnectionString, SSL}`                                                |
| `"snowflake"`                | `db.SnowflakeConnectionConfig{Account, Username, Password, Database, Warehouse}`                    |
| `"bigquery"`                 | `db.BigQueryConfig{ProjectID, DatasetName, Credentials}`                                            |
| `"mysql"`                    | `db.MysqlConnectionConfig{Host, Port, User, Password, Database, TLS}`                               |
| `"clickhouse"`               | `db.ClickHouseConnectionConfig{URL, Username, Password}`                                            |
| `"mssql"`                    | `db.MssqlConnectionConfig{Server, Port, User, Password, Database, Encrypt, TrustServerCertificate}` |
| `"databricks"`               | `db.DatabricksConnectionConfig{Host, Path, Token, Catalog}`                                         |

## Query

```go
func (q *Quill) Query(params models.QuillQueryParams) (models.QuillQueryResult, error)
```

| Field          | Default      |                                                                                                                  |
| -------------- | ------------ | ---------------------------------------------------------------------------------------------------------------- |
| `Tenants`      | required     | `[]interface{}` of `map[string]interface{}{"tenantField": string, "tenantIds": []interface{}}`, or of tenant ids |
| `Metadata`     | required     | `models.QuillRequestMetadata`: `body.Metadata`                                                                   |
| `Flags`        |              | `[]interface{}` of strings, or of `map[string]interface{}{"tenantField": string, "flags": []string}`             |
| `Filters`      |              | `*[]models.Filter`                                                                                               |
| `AdminEnabled` | `nil`, false | `*bool`: allows admin tasks, such as editing dashboards; set it from your own authorization                      |

| `QuillQueryResult` |                                                               |
| ------------------ | ------------------------------------------------------------- |
| `Status`           | `string`: `"success"` or `"error"`                            |
| `Data`             | `interface{}`                                                 |
| `Queries`          | `*models.QueryResults{QueryResults []map[string]interface{}}` |
| `Error`            | `*string`, with `Status: "error"`                             |

## GenerateClientToken

```go
func (q *Quill) GenerateClientToken(params core.ClientTokenParams) (string, error)
```

| Field        |                                                                                     |
| ------------ | ----------------------------------------------------------------------------------- |
| `PublicKey`  | `string`                                                                            |
| `Tenants`    | `[]core.ClientTokenTenant{TenantField string, TenantIds []interface{}}`             |
| `Flags`      | `[]string`, or `[]map[string]interface{}{"tenantField": string, "flags": []string}` |
| `Expiration` | `int64`: milliseconds since the epoch, in the future                                |

## Close

```go
func (q *Quill) Close() error
```
