Skip to content

Add Functionality to Generate Typesense Schema from Go Structs #152

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions typesense/collections.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
// CollectionsInterface is a type for Collections API operations
type CollectionsInterface interface {
Create(schema *api.CollectionSchema) (*api.CollectionResponse, error)
CreateCollectionFromStruct(structData interface{}) (*api.CollectionResponse, error)
Retrieve() ([]*api.CollectionResponse, error)
}

Expand Down Expand Up @@ -39,3 +40,23 @@ func (c *collections) Retrieve() ([]*api.CollectionResponse, error) {
}
return *response.JSON200, nil
}

// CreateCollectionFromStruct creates a Typesense collection from a Go struct.
func (c *collections) CreateCollectionFromStruct(structData interface{}) (*api.CollectionResponse, error) {
// Generate Typesense schema from the Go struct
schema, err := CreateSchemaFromGoStruct(structData)
if err != nil {
return nil, err
}

// Use the generated schema to create a collection in Typesense
response, err := c.apiClient.CreateCollectionWithResponse(context.Background(),
api.CreateCollectionJSONRequestBody(*schema))
if err != nil {
return nil, err
}
if response.JSON201 == nil {
return nil, &HTTPError{Status: response.StatusCode(), Body: response.Body}
}
return response.JSON201, nil
}
39 changes: 39 additions & 0 deletions typesense/collections_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,45 @@ func createNewCollection(name string) *api.CollectionResponse {
}
}

type MockStruct struct {
Field1 string `typesense:"string"`
}

func (m MockStruct) CollectionName() string {
return "custom_collection_name"
}

func TestCreateSchemaFromGoStruct(t *testing.T) {
mockStruct := MockStruct{Field1: "Test"}

schema, err := CreateSchemaFromGoStruct(mockStruct)
assert.NoError(t, err)
assert.NotNil(t, schema)
assert.Equal(t, "custom_collection_name", schema.Name)
}

func TestCreateCollectionFromStruct(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()

mockAPIClient := mocks.NewMockAPIClientInterface(ctrl)
client := NewClient(WithAPIClient(mockAPIClient))
mockStruct := MockStruct{Field1: "Test"}

schema, _ := CreateSchemaFromGoStruct(mockStruct)
expectedResult := &api.CollectionResponse{Name: "custom_collection_name", NumDocuments: pointer.Int64(0)}

mockAPIClient.EXPECT().
CreateCollectionWithResponse(gomock.Not(gomock.Nil()), api.CreateCollectionJSONRequestBody(*schema)).
Return(&api.CreateCollectionResponse{JSON201: expectedResult}, nil).
Times(1)

result, err := client.Collections().CreateCollectionFromStruct(mockStruct)

assert.NoError(t, err)
assert.Equal(t, expectedResult, result)
}

func TestCollectionCreate(t *testing.T) {
newSchema := createNewSchema("companies")
expectedResult := createNewCollection("companies")
Expand Down
75 changes: 75 additions & 0 deletions typesense/struct_parser.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package typesense

import (
"errors"
"reflect"
"strings"

"github.com/typesense/typesense-go/typesense/api"
)

// CollectionNamer is an interface that provides a method to get the collection name.
type CollectionNamer interface {
CollectionName() string
}

// CreateSchemaFromGoStruct takes a Go struct and generates a Typesense CollectionSchema.
// If the struct implements the CollectionNamer interface, its CollectionName method is used to get the collection name.
func CreateSchemaFromGoStruct(structData interface{}) (*api.CollectionSchema, error) {
t := reflect.TypeOf(structData)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}

var collectionName string
if namer, ok := structData.(CollectionNamer); ok {
collectionName = namer.CollectionName()
} else {
collectionName = t.Name()
}

fields := make([]api.Field, 0)
var defaultSortingField *string

for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
tagValue, ok := field.Tag.Lookup("typesense")
if !ok || tagValue == "-" {
continue
}

fieldType := field.Type.String()
if fieldType == "uuid.UUID" {
fieldType = "string"
}

tagParts := strings.Split(tagValue, ",")
facetValue := false // Default facet value
typesenseField := api.Field{
Name: tagParts[0],
Type: fieldType,
Facet: &facetValue, // Initially false
}

for _, tagPart := range tagParts {
tagPartTrimmed := strings.TrimSpace(tagPart)
if tagPartTrimmed == "defaultSort" {
if defaultSortingField != nil {
return nil, errors.New("multiple fields marked with 'defaultSort' tag")
}
defaultSortingField = &field.Name
} else if tagPartTrimmed == "facet" {
facetValue = true
typesenseField.Facet = &facetValue
}
}

fields = append(fields, typesenseField)
}

return &api.CollectionSchema{
Name: collectionName,
Fields: fields,
DefaultSortingField: defaultSortingField,
}, nil
}