Giter Club home page Giter Club logo

ksql-go's Introduction

Kafka ksqlDB driver and KSQL client

CircleCI codecov

Go Reference

An idiomatic KSQL go client with database/sql integrations.

This project is currently an unofficial ksqlDB client for Go until it reaches maturity.

Once maturity it reached, the plan is to integrate it into the ksqlDB codebase and give it official support.

The original design doc is in the ksqlDB repository.

This client has been developed with the goals outlined in the ksqlDB developer guide here.

Getting started

The best place to start is in the examples folder. It contains fully fledged examples for working with database/sql, sqlx, and the client directly.

Querying a stream with sqlx (recommended)

package main

import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/jmoiron/sqlx"
        
	_ "github.com/vancelongwill/ksql-go/stdlib" // import the database/sql driver
)

type Item struct {
        K  string `db:"K"`
        V1 int    `db:"V1"`
        V2 string `db:"V2"`
        V3 bool   `db:"V3"`
}

func run(ctx context.Context) error {
	db, err := sqlx.Open("ksqldb", "http://0.0.0.0:8088/")
	if err != nil {
		return err
	}
	rows, err := db.QueryxContext(ctx, "SELECT * FROM t1 WHERE v1 > -1 EMIT CHANGES;")
	if err != nil {
		return err
	}
	defer rows.Close()
	// this will continue forever unless the context is cancelled, or rows.Close is called
	for rows.Next() {
                var r Item
		err := rows.StructScan(&r)
		if err != nil {
			return err
		}
		log.Println(r)
	}
	return rows.Err()
}

Using a custom HTTP client (for authentication etc)

	// create a ksqldb client with a custom HTTP client (for auth etc)
	httpClient := &http.Client{}
	client := ksql.New("http://0.0.0.0:8088", ksql.WithHTTPClient(httpClient))

        // convert to databse/sql connection
	sqlDB := sql.OpenDB(stdlib.NewConnector(client))
	// again, using jmoiron/sqlx to interact with the DB
	db := sqlx.NewDb(sqlDB, "ksqldb")

HTTP Basic Auth:

type basicAuth struct {
	Username string
	Password string
}

func (bat basicAuth) RoundTrip(req *http.Request) (*http.Response, error) {
	req.Header.Set("Authorization", fmt.Sprintf("Basic %s",
		base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s",
			bat.Username, bat.Password)))))
	return http.DefaultTransport.RoundTrip(req)
}

func run(ctx context.Context) error {
	// create a ksqldb client with a custom HTTP client (for auth etc)
	httpClient := &http.Client{
		Transport: basicAuth{
			Username: "[email protected]",
			Password: "somepassword",
		},
	}
	client := ksql.New("http://0.0.0.0:8088", ksql.WithHTTPClient(httpClient))

	sqlDB := sql.OpenDB(stdlib.NewConnector(client))
	db := sqlx.NewDb(sqlDB, "ksqldb")
        ...
}

Oauth2 (with x/oauth2)

	creds := &clientcredentials.Config{
		ClientID:     "yourID",
		ClientSecret: "yoursecret",
		TokenURL:     "https://yourauthservice.com/oauth2/token",
	}
	client := ksql.New("http://0.0.0.0:8088", ksql.WithHTTPClient(creds.Client(ctx)))

Documentation

Features

  • Compatible with the database/sql driver
  • Supports all the features of the ksqlDB REST API
  • Provides high level API for working with pull & pull queries

Developing

  1. Pull the repo
  2. Get the dependencies
go mod download
  1. Run all unit tests and generate a coverage report
make coverage

Testing

At the moment the primary focus is on unit testing although there are plans to add some integration tests based on the examples.

TODO:

  • Support all ksqlDB REST API methods
  • TLS support (use custom http client)
  • More examples
  • GoDoc
  • Passes golint & go vet
  • More tests (see coverage reports)
  • User documentation
  • More semantic error handling
  • Handle HTTP error codes

ksql-go's People

Contributors

swist avatar vancelongwill avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

swist

ksql-go's Issues

json unmarshal error when calling client.ListQueries

Calling client.ListQueries(ctx) (using ksqldb server v0.17.0) returns the following error:

unable to decode JSON response '<JSON_RESP>': json: cannot unmarshal array into Go value of type client.ExecResult

An example of a json response that causes this error is below:

[
    {
        "@type": "queries",
        "statementText": "LIST QUERIES;",
        "queries": [
            {
                "queryString": "CREATE OR REPLACE TABLE SOME_TABLE WITH (KAFKA_TOPIC='SOME_TABLE', PARTITIONS=3, REPLICAS=1) AS SELECT * FROM SOME_OTHER_TABLE EMIT CHANGES;",
                "sinks": [
                    "SOME_TABLE"
                ],
                "sinkKafkaTopics": [
                    "SOME_TABLE"
                ],
                "id": "CTAS_SOME_TABLE_69",
                "statusCount": {
                    "RUNNING": 1
                },
                "queryType": "PERSISTENT",
                "state": "RUNNING"
            }
        ],
        "warnings": []
    }
]

Looking at the source code for client.ListQueries I've pinpointed the error to be in exec.go#L92. The json decode fails due to the following error:

json: cannot unmarshal array into Go struct field Query.queries.sinks of type string

This error is then ignored, and the code then proceeds to try to decode in to a single ExecResult instead, which also fails and returns the original error message above.

I believe that the problem is that although descriptions.go#L23 sets the type of Query.Sinks to be string (as per ksqldb docs), the actual response is returning an array of strings, so the Query.Sinks type should be []string instead. Making this change resolves the error.

Interestingly, the above example respose also has some extra fields not included in the ksqldb docs which only mention queryString, sinks and id.

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.