> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kinetica.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Go API

The *Kinetica* Go API is a native Go client for the database: connection
setup, sessions, HA failover & fail-back, multi-head routing, retries, records,
bulk insertion, SQL clients, and KiFS.  Every *Kinetica* endpoint is a method
on the connection, taking a typed request and returning a typed response.

The API's reference documentation is published on pkg.go.dev, where Go module
documentation lives, and its source is on *GitHub*:

* [Go API Reference](https://pkg.go.dev/github.com/kineticadb/kinetica-api-go/v7)
* [Go GitHub Repo](https://github.com/kineticadb/kinetica-api-go)
* [Go API Changelog](https://github.com/kineticadb/kinetica-api-go/blob/master/CHANGELOG.md)

## Installation

The module requires Go 1.26 or later.  Add it to a project with `go get`:

```
go get github.com/kineticadb/kinetica-api-go/v7
```

Then import the client package:

```go title="Import" theme={null}
import "github.com/kineticadb/kinetica-api-go/v7/kinetica"
```

Two further packages hold the KiFS client and the string constants of every
request's & response's fields:

```go title="Supporting Packages" theme={null}
import "github.com/kineticadb/kinetica-api-go/v7/kinetica/kifs"
import "github.com/kineticadb/kinetica-api-go/v7/kinetica/constants"
```

## Connecting

A connection is made with `Connect`, given the URL of a *Kinetica* database
server and the connection options, which carry the credentials.  `Connect`
discovers the clusters of the HA ring and the worker ranks of each, and reads
the server version; it fails if no server answers.

```go theme={null}
// Connect to the database, discovering the HA ring and worker ranks
options := kinetica.NewKineticaOptions().
	SetUsername(username).
	SetPassword(password)

db, err := kinetica.Connect(ctx, []string{url}, options)
if err != nil {
	return err
}
defer db.Close()

fmt.Println("Connected to Kinetica", db.GetServerVersion())
```

Each connection is its own server session, and the
[session temp tables](https://docs.kinetica.com/content/sql/ddl/session-temp-tables.md#sql-session-temp-tables) it creates belong
to that session; `Close` drops them.  A connection is safe for concurrent
use.

For connecting over HTTPS, with or without certificate validation, and with an
OAuth token, see [Connecting via API](https://docs.kinetica.com/content/api/concepts.md#api-conn).  For failover
across an HA ring, give `Connect` the head node of each cluster, or let it
discover the ring from one.

## Using the API

The following walks through the operations of the
[quick start example](https://docs.kinetica.com/content/api/go.md#go-example), which creates a table, loads
it, queries it, and drops it.

### Tables & Types

A table's record type can be defined from a Go struct.  Each exported field is
a column, named and given [column properties](https://docs.kinetica.com/content/sql/ddl/column-types.md#sql-column-types)
by its `kinetica` tag; a pointer field is nullable.

```go theme={null}
type Employee struct {
	ID        int32    `kinetica:"id,primary_key"`
	FirstName string   `kinetica:"first_name,char32"`
	LastName  string   `kinetica:"last_name,char32"`
	Salary    *float64 `kinetica:"salary"`
	HireDate  string   `kinetica:"hire_date,date"`
}
```

The type is registered with the database, and a table created from it:

```go theme={null}
// Define the record type from the struct, register it, and create the table
employeeType, err := kinetica.NewTypeFromStruct[Employee]("employee")
if err != nil {
	return err
}
typeID, err := employeeType.Create(ctx, db)
if err != nil {
	return err
}
if _, err := db.CreateTable(ctx, &kinetica.CreateTableRequest{
	TableName: tableName,
	TypeId:    typeID,
}); err != nil {
	return err
}
fmt.Println("Created table", tableName)
```

A type can also be built column by column with a `TypeBuilder`, or read from
an existing table with `NewTypeFromTable`.

### Inserting Records

Records of the struct type are inserted in one request with
`InsertRecordsTyped`:

```go theme={null}
// Insert records in one request
salary := 65000.0
inserted, err := kinetica.InsertRecordsTyped(ctx, db, tableName, []Employee{
	{ID: 1, FirstName: "Ada", LastName: "Lovelace", Salary: &salary, HireDate: "2020-03-16"},
	{ID: 2, FirstName: "Alan", LastName: "Turing", HireDate: "2021-06-23"},
}, nil)
if err != nil {
	return err
}
fmt.Println("Inserted", inserted.CountInserted, "records")
```

### Bulk Loading

For loading many records, a `BulkInserter` batches them and sends each batch
directly to the worker rank that holds it, using
[distributed ingest](https://docs.kinetica.com/content/tuning/multihead/multihead_ingest.md).
`Insert` queues a record; `Close` flushes what is buffered, waits for every
batch, and returns the batches that failed, if any.

```go theme={null}
// Insert records in bulk, each batch sent to the worker rank holding it
inserter, err := kinetica.NewBulkInserterContext(ctx, db, tableName, 1000, 0, nil)
if err != nil {
	return err
}
for id := int32(3); id <= 1002; id++ {
	if err := inserter.Insert(Employee{
		ID:        id,
		FirstName: fmt.Sprintf("First%d", id),
		LastName:  fmt.Sprintf("Last%d", id),
		HireDate:  "2024-01-01",
	}); err != nil {
		return err
	}
}
// Close flushes what is buffered, and reports the batches that failed
var failed *kinetica.InsertErrors
if err := inserter.Close(); errors.As(err, &failed) {
	return fmt.Errorf("%d records failed: %s", len(failed.Records), failed.Message)
} else if err != nil {
	return err
}
fmt.Println("Bulk inserted", inserter.GetCountInserted(), "records")
```

### Querying with SQL

`Query` runs a SQL query and returns an iterator over its records, which are
read from the server a batch at a time.  The iterator must be closed, which
drops the paging table the query made.

```go theme={null}
// Query with SQL; the iterator pages through the result and must be closed
records, err := db.Query(ctx, "SELECT id, first_name, last_name FROM "+tableName+" WHERE id <= 2 ORDER BY id")
if err != nil {
	return err
}
defer records.Close(ctx)
for record, err := range records.All(ctx) {
	if err != nil {
		return err
	}
	id, _ := record.IntByName("id")
	first, _ := record.StrByName("first_name")
	last, _ := record.StrByName("last_name")
	fmt.Println("Found", id, first, last)
}
```

`Execute` runs any other SQL statement and returns the number of records it
affected.  The `WithParameters` form of each takes the values for the `?`
placeholders in the statement, sent as the
[query parameters](https://docs.kinetica.com/content/api/rest/execute_sql_rest.md) of the request:

```go theme={null}
// Update with a parameterized statement; the parameters are sent as text
updated, err := db.ExecuteWithParameters(ctx,
	"UPDATE "+tableName+" SET salary = ? WHERE id = ?",
	kinetica.SQLParametersValues("72000", "2"), nil)
if err != nil {
	return err
}
fmt.Println("Updated", updated, "record")
```

`SQLParametersValues` sends the values as text, which the server converts to
the column types; `SQLParametersJSON` sends typed values, nulls, and slices
for several rows.

The full SQL feature set is available through these calls; see the
[SQL](https://docs.kinetica.com/content/sql.md) section for the language.

### Retrieving Records

`GetRecordsTyped` reads records back into the struct, matching each column to
the field of its name.  The options take a filter expression and a sort order,
among others.

```go theme={null}
// Read records back into the struct, by column name
employees, err := kinetica.GetRecordsTyped[Employee](ctx, db, tableName, 0, 2,
	&kinetica.GetRecordsOptions{Expression: "id <= 2", SortBy: "id"})
if err != nil {
	return err
}
for _, e := range employees.Data {
	salary := "no salary"
	if e.Salary != nil {
		salary = fmt.Sprintf("%.2f", *e.Salary)
	}
	fmt.Println("Employee", e.ID, e.FirstName, e.LastName, salary, e.HireDate)
}
fmt.Println("Matched", employees.TotalNumberOfRecords, "records")
```

### Dropping a Table

```go theme={null}
// Drop the table
if _, err := db.ClearTable(ctx, &kinetica.ClearTableRequest{TableName: tableName}); err != nil {
	return err
}
fmt.Println("Dropped table", tableName)
```

## Errors

Every call returns a `*kinetica.Error`, which carries a kind and a message:
an `API` error for a request the server refused, `Unauthorized` for a
rejected login, `Connection` for a request that got no response, and so on.
`errors.Is` finds a kind anywhere in an error's chain, and `errors.As`
reaches the error itself:

```go title="Error Handling" theme={null}
_, err := db.ShowTable(ctx, &kinetica.ShowTableRequest{TableName: "no_such_table"})

var kerr *kinetica.Error
switch {
case err == nil:
case errors.Is(err, kinetica.KindUnauthorized):
    log.Print("check the credentials")
case errors.As(err, &kerr) && kerr.Kind == kinetica.KindAPI:
    log.Print("the server refused it: ", kerr.Message())
default:
    log.Print(err)
}
```

The kinds, and which of them the client fails over for, are listed in the
[Go API Reference](https://pkg.go.dev/github.com/kineticadb/kinetica-api-go/v7).

## Quick Start Example

The complete program the sections above are drawn from.  It takes the database
URL and login on the command line:

```
go run ./quickstart --url http://localhost:9191 --username <username> --password <password>
```

```go theme={null}
// Kinetica Go API quick start: connect, create a table from a struct, insert
// records one request at a time and in bulk, query with SQL, read records back
// by type, and clean up.
//
// Run with the URL and login of a Kinetica instance:
//
//	go run ./quickstart --url http://localhost:9191 --username admin --password <password>
package main

import (
	"context"
	"errors"
	"flag"
	"fmt"
	"log"

	"github.com/kineticadb/kinetica-api-go/v7/kinetica"
)

// Employee is a record of the example table.  Each exported field is a column,
// named and given properties by its kinetica tag; a pointer field is nullable.
type Employee struct {
	ID        int32    `kinetica:"id,primary_key"`
	FirstName string   `kinetica:"first_name,char32"`
	LastName  string   `kinetica:"last_name,char32"`
	Salary    *float64 `kinetica:"salary"`
	HireDate  string   `kinetica:"hire_date,date"`
}

const (
	schemaName = "example"
	tableName  = schemaName + ".employee"
)

func main() {
	url := flag.String("url", "http://localhost:9191", "Kinetica URL to run example against")
	username := flag.String("username", "", "Username of user to run example with")
	password := flag.String("password", "", "Password of user")
	flag.Parse()

	ctx := context.Background()

	if err := run(ctx, *url, *username, *password); err != nil {
		log.Fatal(err)
	}
}

func run(ctx context.Context, url, username, password string) error {
	// Connect to the database, discovering the HA ring and worker ranks
	options := kinetica.NewKineticaOptions().
		SetUsername(username).
		SetPassword(password)

	db, err := kinetica.Connect(ctx, []string{url}, options)
	if err != nil {
		return err
	}
	defer db.Close()

	fmt.Println("Connected to Kinetica", db.GetServerVersion())
	// end connect

	// Create the schema, if it does not exist
	schemaOptions := kinetica.NewDefaultCreateSchemaOptions()
	schemaOptions.NoErrorIfExists = true
	if _, err := db.CreateSchema(ctx, &kinetica.CreateSchemaRequest{
		SchemaName: schemaName,
		Options:    schemaOptions.ToMap(),
	}); err != nil {
		return err
	}

	// Drop the table, if it exists, so the example starts from an empty one
	clearOptions := kinetica.NewDefaultClearTableOptions()
	clearOptions.NoErrorIfNotExists = true
	if _, err := db.ClearTable(ctx, &kinetica.ClearTableRequest{
		TableName: tableName,
		Options:   clearOptions.ToMap(),
	}); err != nil {
		return err
	}

	// Define the record type from the struct, register it, and create the table
	employeeType, err := kinetica.NewTypeFromStruct[Employee]("employee")
	if err != nil {
		return err
	}
	typeID, err := employeeType.Create(ctx, db)
	if err != nil {
		return err
	}
	if _, err := db.CreateTable(ctx, &kinetica.CreateTableRequest{
		TableName: tableName,
		TypeId:    typeID,
	}); err != nil {
		return err
	}
	fmt.Println("Created table", tableName)
	// end create table

	// Insert records in one request
	salary := 65000.0
	inserted, err := kinetica.InsertRecordsTyped(ctx, db, tableName, []Employee{
		{ID: 1, FirstName: "Ada", LastName: "Lovelace", Salary: &salary, HireDate: "2020-03-16"},
		{ID: 2, FirstName: "Alan", LastName: "Turing", HireDate: "2021-06-23"},
	}, nil)
	if err != nil {
		return err
	}
	fmt.Println("Inserted", inserted.CountInserted, "records")
	// end insert records

	// Insert records in bulk, each batch sent to the worker rank holding it
	inserter, err := kinetica.NewBulkInserterContext(ctx, db, tableName, 1000, 0, nil)
	if err != nil {
		return err
	}
	for id := int32(3); id <= 1002; id++ {
		if err := inserter.Insert(Employee{
			ID:        id,
			FirstName: fmt.Sprintf("First%d", id),
			LastName:  fmt.Sprintf("Last%d", id),
			HireDate:  "2024-01-01",
		}); err != nil {
			return err
		}
	}
	// Close flushes what is buffered, and reports the batches that failed
	var failed *kinetica.InsertErrors
	if err := inserter.Close(); errors.As(err, &failed) {
		return fmt.Errorf("%d records failed: %s", len(failed.Records), failed.Message)
	} else if err != nil {
		return err
	}
	fmt.Println("Bulk inserted", inserter.GetCountInserted(), "records")
	// end bulk insert

	// Query with SQL; the iterator pages through the result and must be closed
	records, err := db.Query(ctx, "SELECT id, first_name, last_name FROM "+tableName+" WHERE id <= 2 ORDER BY id")
	if err != nil {
		return err
	}
	defer records.Close(ctx)
	for record, err := range records.All(ctx) {
		if err != nil {
			return err
		}
		id, _ := record.IntByName("id")
		first, _ := record.StrByName("first_name")
		last, _ := record.StrByName("last_name")
		fmt.Println("Found", id, first, last)
	}
	// end query

	// Update with a parameterized statement; the parameters are sent as text
	updated, err := db.ExecuteWithParameters(ctx,
		"UPDATE "+tableName+" SET salary = ? WHERE id = ?",
		kinetica.SQLParametersValues("72000", "2"), nil)
	if err != nil {
		return err
	}
	fmt.Println("Updated", updated, "record")
	// end execute

	// Read records back into the struct, by column name
	employees, err := kinetica.GetRecordsTyped[Employee](ctx, db, tableName, 0, 2,
		&kinetica.GetRecordsOptions{Expression: "id <= 2", SortBy: "id"})
	if err != nil {
		return err
	}
	for _, e := range employees.Data {
		salary := "no salary"
		if e.Salary != nil {
			salary = fmt.Sprintf("%.2f", *e.Salary)
		}
		fmt.Println("Employee", e.ID, e.FirstName, e.LastName, salary, e.HireDate)
	}
	fmt.Println("Matched", employees.TotalNumberOfRecords, "records")
	// end get records

	// Drop the table
	if _, err := db.ClearTable(ctx, &kinetica.ClearTableRequest{TableName: tableName}); err != nil {
		return err
	}
	fmt.Println("Dropped table", tableName)
	// end clean up

	return nil
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.