Isomorphic Go client for PostgREST.

Postgrest GO

golangci-lint CodeFactor

Golang client for PostgREST. The goal of this library is to make an "ORM-like" restful interface.

Documentation

Full documentation can be found on our website.

Quick start

Install

go get github.com/supabase/postgrest-go

Usage

package main
​
import (
"fmt""github.com/supabase/postgrest-go"
)
​
func main() {
	client := postgrest.NewClient("http://localhost:3000", "", nil)
	if client.ClientError != nil {
		panic(client.ClientError)
	}
	​
	result := client.Rpc("add_them", "", map[string]int{"a": 12, "b": 3})
	if client.ClientError != nil {
		panic(client.ClientError)
	}
	​
	fmt.Println(result)
}

License

This repo is liscenced under Apache License.

Sponsors

We are building the features of Firebase using enterprise-grade, open source products. We support existing communities wherever possible, and if the products don’t exist we build them and open source them ourselves. Thanks to these sponsors who are making the OSS ecosystem better for everyone.

New Sponsor

Watch this repo

Comments
  • `Execute()` is not sending request to the correct URL

    `Execute()` is not sending request to the correct URL

    Bug report

    Describe the bug

    So when I try to insert data with the following code snippet, I expect it to send a request to https://<supabase_url>/rest/v1/products but it seems like the Execute() function is not sending the request to the correct URL. image

    The result of trying to run this is that I get the response as below, after a google search it seems like this is what Kong would respond if it can't find a route

    image

    So I try to directly change the client.clientTransport.baseURL.Path to https://<supabase_url>/rest/v1/products, the request is sent to the correct place where I can see a postgrest response but the query is still not successfully created yet. I'm suspecting is that the way the querybuilder marshal json is making some errors here.

    image

    To Reproduce

    Steps to reproduce the behavior, please provide code snippets or a repository:

    1. Get the library
    2. Use a supabase url, anon key and proper auth token to create the client
    3. Try to insert data into a table
    4. See error

    Expected behavior

    The request should be sent to the correct url and querybuilder should properly marshal value into json

    Screenshots

    Shown above

    System information

    • OS: macOS Big Sur 11.4
    • Version of Go: 1.16

    Additional context

    I will try fixing it and if I do, I will create a PR.

  • Provide examples for authentication etc.

    Provide examples for authentication etc.

    Hey! I love the idea behind this package, but have some troubles with getting started, as I am new to Supabase and PostgREST.

    I would love to see some more examples on the usage of this package (with supabase), namely authentication.

    • (How) should I use the client.TokenAuth method?
    • Can I encode the credentials into the HTTP URI somehow?

    For anything I tried, I get some not-so-descriptive error (like just EOF from net/url) which is very likely because I did something wrong.

    All the examples I can find are just for a local setup without auth. Maybe adding a few more tests would be ideal for this? I would love to contribute once I used this a bit more.

    I would greatly appreciate any help :)

  • Select from table fails

    Select from table fails

    Bug report

    Describe the bug

    Following the test example and the supabase-js example in the documentation I am not able to fetch data using the From().Select() chain and an error is returned in the response body instead of the err value itself.

    The json response looks like:

    {"message":"no Route matched with those values"}
    

    To Reproduce

            type User struct {
    		id string
    	}
            
            var (
    	        headers = map[string]string{"Authorization": fmt.Sprintf("Bearer %s", serverconf.Supabase.Key)}
    	        schema  = "public"
            )
    
            var serverconf := utils.NewServerConfig()
    
            supabaseClient := postgrest.NewClient(serverconf.Supabase.URL, schema, headers)
    		
            res, err := r.client.From("users").Select("*", "", false).Eq("email", email).Execute()
    
    	if err := json.Unmarshal(res, &result); err != nil {
    		panic(err)
    	}
    
    

    Expected behavior

    Expected to have a valid user response and no error. Also expected error to be returned in err variable but instead it's nil.

  • New execute method for json objects

    New execute method for json objects

    What kind of change does this PR introduce?

    This PR implements a new executeTo method which automatically parses the response into a json object as described in #7

    What is the current behavior?

    #7

    What is the new behavior?

    An ExecuteTo method was added to the structs as described which directly parses the response body into an interface{}

    Additional context

    I tried to implement the changes described in the issue but was not sure regarding the requriements. I currently implemented the functions as requested with the return value of an (interface{}, error) for the ExecuteTo functions.

    I also thought about changing the function to ExecuteTo(target interface{}) error which enables the user to give a custom struct or map from outside. Then instead of creating a new object inside the executeTo function, this target value is used to parse the response body into. I would be open to implement this function as well - maybe under a different name like ExecuteInto

    As this is my first contribution, i hope i didn't miss something or did something wrong, if so please let me know so i can fix it!

  • ❓ Can't get it to work.

    ❓ Can't get it to work.

    Synopsis

    I can't get this package to function against supabase.co

    Details

    Whether I use the Anon key or the Service key, I can't select anything.

    • With head set to false, I get []
    • With head set to true, I get ""

    Reproduction

    func TestSelect(t *testing.T) {
    	db := postgrest.NewClient(
    		"https://<project-ref>.supabase.co/rest/v1/",
    		"public",
    		map[string]string{},
    	)
    	db.TokenAuth("...")
    
    	res, count, err := db.
    		From("profiles").
    		Select("*", "", false). // also tried specifying columns
    		ExecuteString()
    
    	spew.Dump(res, count, err)
    
    	if err != nil {
    		t.Fatalf("error returned: %v", err)
    	}
    
    	if res == "[]" || res == "" {
    		t.Fatalf("no result")
    	}
    }
    
    === RUN   TestSelect
    (string) (len=2) "[]"
    (int64) 0
    (interface {}) <nil>
        select_test.go:30: no result
    --- FAIL: TestSelect (0.29s)
    
  • Reassign transformer methods to FilterBuilder

    Reassign transformer methods to FilterBuilder

    In lieu of a more ergonomic option within Go's type system (that feels reasonable) to resolve #8, I'm proposing removing TransformBuilder and simply reassigning its associated methods to FilterBuilder. As you'd expect, this lets you do:

    c.From("users").Select("*", "", false).Limit(10)
    

    Of course, it also somewhat unfortunately lets you do:

    c.From("users").Select("*", "", false).Limit(10).Eq("name", "sean")
    

    Which obviously looks weird.

    Since the transformer methods aren't usable in the current release, this is probably also a good time to discuss some of ergonomics around the transformer methods. Having four params with type similarities in Order, for example, feels a bit unnatural, so I'd propose having it instead accept a struct of options (or nil to get the defaults).

    type OrderOpts struct {
    	Ascending    bool
    	NullsFirst   bool
    	ForeignTable string
    }
    
    func (f *FilterBuilder) Order(column string, opts *OrderOpts) *FilterBuilder
    

    This also roughly mirrors the interface in postgres-js. I'm unsure whether it'd be useful to also update Limit and Range similarly, given they both also currently accept foreignTable.

    A full PR would need tests/docs -- this is just aimed at opening up discussion.

  • Update ExecuteTo funcs to return count

    Update ExecuteTo funcs to return count

    Updates the ExecuteTo funcs to return (countType, error), mirroring the recent changes to Execute and ExecuteString, and adds a couple test cases.

    This also fixes a couple broken links in the README, peppers in a handful of doc comments, details how some of the tests are set up/how to run, and adds a script in the test directory that can be used to seed the current test DB. So there've been a number of files touched. If desired, I can split these into multiple PRs.

    I assumed this PR would be rolled into a v0.0.6 release and updated the version variable accordingly.

  • Change authorization header

    Change authorization header

    After looking a bit at the supabase documentation, I saw that the authentication is not Basic but Bearer (which means in return that one should have to change this in the client.go file of postgrest.) I propose two solution:

    • whether to amend it on the static string of the TokenAuth (I just did it myself line 59 of client.go). then is will go to
    func (c *Client) TokenAuth(token string) *Client {
    	c.clientTransport.header.Set("Authorization", "Bearer "+token)
            ...
    }
    \\ instead of 
    func (c *Client) TokenAuth(token string) *Client {
    	c.clientTransport.header.Set("Authorization", "Basic "+token)
            ...
    }
    
    • or to amend it dynamically (I do not really now how PostgreSQL works, so if there are different type of authorization I could envisage the following)
    func (c *Client) TokenAuth(token string, auth_type string) *Client {
    	c.clientTransport.header.Set("Authorization", auth_type+" "+token)
            ...
    } 
    \\ instead of 
    func (c *Client) TokenAuth(token string) *Client {
    	c.clientTransport.header.Set("Authorization", "Basic "+token)
            ...
    }```
  • Minor changes to headers in client.go

    Minor changes to headers in client.go

    As mentioned in https://github.com/supabase-community/postgrest-go/issues/20, I think that the two changes in this PR will solve bugs. I have no idea if others also experienced this, but for me both the missing header and the "wrong" header name made the package unusable for me.

    I am using go 1.17 btw.

  • X-Client-Info header

    X-Client-Info header

    we're rolling out a header similar to Stripe's App-Data in all of the client libs so issues can be debugged more easily between the client and the backend

    the javascript libs are done already: https://github.com/supabase/supabase-js/pull/238

    the format is: X-Client-Info: supabase-js/1.11.0

    for client libs that wrap others (like how supabase-js wraps gotrue-js) we allow the wrapper lib to overwrite the wrapped lib's header (given that we can infer the gotrue-js version based on which supabase-js was used to make the call)

    any help with rolling this out here would be incredible

  • From() will always append the table name to the baseUrl Path

    From() will always append the table name to the baseUrl Path

    Bug report

    Describe the bug

    When using From(), the code will currently forcibly (+=) add the table name to the client transport baseUrl path. This makes it impossible to reuse a client instance (postgrest.NewClient(<url>L, <schema>, <headers>)) as the second time From() is used the schema becomes <schema>.<table><table>

    To Reproduce

    Steps to reproduce the behavior, please provide code snippets or a repository:

    var (
    	url = "https://<some-supabase-url>/rest/v1/"
    	headers  = map[string]string{"apikey": "<my-supabase-apikey>"}
    )
    
    client := postgrest.NewClient(url, "public", headers)
    
    // .. build some list
    for _, doc := range listofdocs {
        // Second time this is called, there will be an error because the schema is now wrong
    	resp, err := client.From("<mytable>").Insert(doc, "", "", "").Execute()
    	if err != nil {
    		// handle error
    	}
    }
    

    Expected behavior

    Expected behavior is that if calling multiple times (vs batch insert) that From() wont cause the insert to fail. The JS client (for example) does not exhibit this issue

    Screenshots

    N/A

    Additional context

    I am working on a solution to this that I will submit a PR for

  • Supabase URL needs `/rest/v1` appended

    Supabase URL needs `/rest/v1` appended

    In the README, the docs say to put in localhost:3000, but if calling supabase itself, if you put in the API URL as it is in Supabase, you get a () no Route matched with those values error.

    I had to update my URL to https://<database id>.supabase.co/rest/v1 and it worked.

    Could we update the docs? Or is there a fix under the hood we'd want to make? I'm up to make either, but wanted to run it by you all first!

  • Define and Creating test cases with explanatory comments

    Define and Creating test cases with explanatory comments

    We must define test cases first. I think we can look other supabase postgREST libraries for this.

    Bellow I will add cases and addition status with tasklist style so this issue will more useful in tasklist.

    TEST DEFINITIONS

    • [x] Basic from/select without auth based here
    • [ ] Basic insert/upsert/update/delete based here
RPC Framework abstraction layer. Provides foundation of the RonyDesc to generate RPC server/client codes.

RonyKit RonyKit provides the abstraction layer for creating a cluster aware API server. By defining separate components for each task, you are almost

Dec 15, 2022
Isomorphic Go client for PostgREST.

Postgrest GO Golang client for PostgREST. The goal of this library is to make an "ORM-like" restful interface. Documentation Full documentation can be

Dec 5, 2022
A Go client implementing a client-side distributed consumer group client for Amazon Kinesis.
A Go client implementing a client-side distributed consumer group client for Amazon Kinesis.

Kinesumer is a Go client implementing a client-side distributed consumer group client for Amazon Kinesis.

Jan 5, 2023
Clusterpedia-client - clusterpedia-client supports the use of native client-go mode to call the clusterpedia API

clusterpedia-client supports the use of native client-go mode to call the cluste

Jan 7, 2022
Client-go - Clusterpedia-client supports the use of native client-go mode to call the clusterpedia API

clusterpedia-client supports the use of native client-go mode to call the cluste

Dec 5, 2022
Prisma Client Go is an auto-generated and fully type-safe database client

Prisma Client Go Typesafe database access for Go Quickstart • Website • Docs • API reference • Blog • Slack • Twitter Prisma Client Go is an auto-gene

Jan 9, 2023
The Dual-Stack Dynamic DNS client, the world's first dynamic DNS client built for IPv6.

dsddns DsDDNS is the Dual-Stack Dynamic DNS client. A dynamic DNS client keeps your DNS records in sync with the IP addresses associated with your hom

Sep 27, 2022
The Fabric Smart Client is a new Fabric Client that lets you focus on the business processes and simplifies the development of Fabric-based distributed application.

Fabric Smart Client The Fabric Smart Client (FSC, for short) is a new Fabric client-side component whose objective is twofold. FSC aims to simplify th

Dec 14, 2022
this is a funny client for jsonrpc-client. it can support timeout,breaker ...

this is a funny client for jsonrpc-client. it can support timeout,breaker ...

Sep 17, 2022
Awesome WebSocket CLient - an interactive command line client for testing websocket servers
Awesome WebSocket CLient - an interactive command line client for testing websocket servers

Awesome WebSocket CLient - an interactive command line client for testing websocket servers

Dec 30, 2022
Chief Client Go is a cross platform Krunker client written in Go Lang

Chief Client Go Chief Client Go is a client for Mac and Linux written in GoLang Features Ad Blocker Option to use proxy Installation To install this c

Nov 6, 2021
Go Substrate RPC Client (GSRPC)Go Substrate RPC Client (GSRPC)

Go Substrate RPC Client (GSRPC) Substrate RPC client in Go. It provides APIs and types around Polkadot and any Substrate-based chain RPC calls. This c

Nov 11, 2021
Server and client implementation of the grpc go libraries to perform unary, client streaming, server streaming and full duplex RPCs from gRPC go introduction

Description This is an implementation of a gRPC client and server that provides route guidance from gRPC Basics: Go tutorial. It demonstrates how to u

Nov 24, 2021
Devcloud-go provides a sql-driver for mysql which named devspore driver and a redis client which named devspore client,

Devcloud-go Devcloud-go provides a sql-driver for mysql which named devspore driver and a redis client which named devspore client, you can use them w

Jun 9, 2022
Client for the cloud-iso-client

cloud-iso-client Client for the cloud-iso-client. Register an API token Before using this client library, you need to register an API token under your

Dec 6, 2021
Go-http-client: An enhanced http client for Golang
Go-http-client: An enhanced http client for Golang

go-http-client An enhanced http client for Golang Documentation on go.dev ?? This package provides you a http client package for your http requests. Y

Jan 7, 2023
Demonstration of sharing secret data between an OAuth/OIDC client and an Identity Providers web client.

OAuth / OIDC Cubbyhole Share secret data between client applications. This is mostly a demonstration of some of the work I've been evaluating at Storj

Mar 21, 2022
Godaddy-domains-client-go - Godaddy domains api Client golang - Write automaticly from swagger codegen

Go API client for swagger Overview This API client was generated by the swagger-codegen project. By using the swagger-spec from a remote server, you c

Jan 9, 2022
Nutanix-client-go - Go client for the Nutanix Prism V3 API

nutanix-client-go This repository contains portions of the Nutanix API client code in nutanix/terraform-provider-nutanix. It has been extracted to red

Jan 6, 2022
Kube - A simple Kubernetes client, based on client-go

kube A simple Kubernetes client, based on client-go.

Aug 9, 2022