Merge pull request #15 from sunboyy/method-spec-doc

Add method specification document
This commit is contained in:
sunboyy 2021-02-08 21:59:53 +07:00 committed by GitHub
commit 94a7ca6b62
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 237 additions and 138 deletions

View file

@ -55,8 +55,8 @@ type UserRepository interface {
// the database. This is a MANY mode because the first return type is an integer.
DeleteByCity(ctx context.Context, city string) (int, error)
// CountByCity returns the number of rows that match the given city parameter. If an error occurs while
// accessing the database, error value will be returned.
// CountByCity returns the number of rows that match the given city parameter. If an
// error occurs while accessing the database, error value will be returned.
CountByCity(ctx context.Context, city string) (int, error)
}
```
@ -82,6 +82,97 @@ $ repogen -src=examples/getting-started/user.go -dest=examples/getting-started/u
You can also write the above command in the `go:generate` format inside Go files in order to generate the implementation when `go generate` command is executed.
## Usage
### Method Definition
To begin, your method name must be in pascal-case (camel-case with beginning uppercase letter). Repogen determines an operation for a method by getting the **first word** of the method name. There are 5 supported words which refer to 5 supported operations.
1. `Insert` - Stores new data to the database
2. `Find` - Retrives data from the database
3. `Update` - Changes some fields of the data in the database
4. `Delete` - Removes data from the database
5. `Count` - Retrieves number of matched documents in the database
Each of the operations has their own requirements for the method name, parameters and return values. Please consult the documentation for each operation for its requirements.
#### Insert operation
An `Insert` operation has a very limited use case, i.e. inserting a single document or multiple documents. So, it is quite limited in method parameters and method returns. An insert method can only have one of these signatures.
```go
// InsertOne inserts a single document
InsertOne(ctx context.Context, model *Model) (interface{}, error)
// InsertMany inserts multiple documents
InsertMany(ctx context.Context, models []*Model) ([]interface{}, error)
```
Repogen determines a single-entity operation or a multiple-entity by checking the second parameter and the first return value. However, the operation requires the first parameter to be of type `context.Context` and the second return value to be of type `error`.
As the `Insert` operation has a limited use case, we do not want to limit you on how you name your method. Any method that has the name starting with the word `Insert` is always valid. For example, you can name your method `InsertAWholeBunchOfDocuments` and it will work as long as you specify method parameters and returns correctly.
#### Find operation
A `Find` operation also has two modes like `Insert` operation: single-entity and multiple-entity. However `Find` operation can be very simple or complex depending on how complex the query is. In this section, we will show you how to write single-modes and multiple-entity modes of find method with a simple query. For more information about more complex queries, please consult the query specification section in this document.
```go
// FindByID gets a single document by ID
FindByID(ctx context.Context, id primitive.ObjectID) (*Model, error)
// FindByCity gets all documents that match city parameter
FindByCity(ctx context.Context, city string) ([]*Model, error)
// FindAll gets all documents
FindAll(ctx context.Context) ([]*Model, error)
```
Repogen determines a single-entity operation or a multiple-entity by checking the first return value. If it is a pointer of a model, the method will be single-entity operation. If it is a slice of pointers of a model, the method will be multiple-entity operation.
The requirement of the `Find` operation method is that there must be only two return values, the second return value must be of type `error` and the first method parameter must be of type `context.Context`. The requirement of number of method parameters depends on the query which will be described in the query specification section.
#### Update operation
An `Update` operation also has two modes like `Insert` and `Find` operations: single-entity and multiple-entity. An `Update` operation also supports querying like `Find` operation. However, an `Update` operation requires more parameters than `Find` method, i.e. new values of updating fields. Specifying the query is the same as in `Find` method but specifying the updating fields are a little different.
```go
// UpdateDisplayNameAndCityByID updates a single document with a new display name and
// city by ID
UpdateDisplayNameAndCityByID(ctx context.Context, displayName string, city string,
id primitive.ObjectID) (bool, error)
// UpdateGenderByCity updates Gender field of documents with matching city parameter
UpdateGenderByCity(ctx context.Context, gender Gender, city string) (int, error)
```
Repogen determines a single-entity operation or a multiple-entity by checking the first return value. If it is of type `bool`, the method will be single-entity operation. If it is of type `int`, the method will be multiple-entity operation. For single-entity operation, the method returns true if there is a matching document. For multiple-entity operation, the integer return shows the number of matched documents.
The requirement of the `Update` operation method is that there must be only two return values, the second return value must be of type `error` and the first method parameter must be of type `context.Context`. The requirement of number of method parameters depends on the number of updating fields and the query. Updating fields must be directly after context parameter and query fields must be directly after updating fields.
#### Delete operation
A `Delete` operation is the very similar to `Find` operation. It has two modes. The method name pattern is the same. The method parameters and returns are also almost the same except that `Delete` operation has different first return value of the method. For single-entity operation, the method returns true if there is a matching document. For multiple-entity operation, the integer return shows the number of matched documents.
```go
// DeleteByID deletes a single document by ID
DeleteByID(ctx context.Context, id primitive.ObjectID) (bool, error)
// DeleteByCity deletes all documents that match city parameter
DeleteByCity(ctx context.Context, city string) (int, error)
// DeleteAll deletes all documents
DeleteAll(ctx context.Context) (int, error)
```
#### Count operation
A `Count` operation is also similar to `Find` operation except it has only multiple-entity mode. This means that the method returns are always the same for any count operations. The method name pattern and the parameters are the same as `Find` operation.
```go
// CountByGender returns number of documents that match gender parameter
CountByGender(ctx context.Context, gender Gender) (int, error)
```
## License
Licensed under [MIT](https://github.com/sunboyy/repogen/blob/main/LICENSE)

View file

@ -18,25 +18,25 @@ type UserModel struct {
// UserRepository is an interface that describes the specification of querying user data in the database
type UserRepository interface {
// InsertOne stores userModel into the database and returns inserted ID if insertion succeeds
// and returns error if insertion fails.
// InsertOne stores userModel into the database and returns inserted ID if insertion
// succeeds and returns error if insertion fails.
InsertOne(ctx context.Context, userModel *UserModel) (interface{}, error)
// FindByUsername queries user by username. If a user with specified username exists, the user will be
// returned. If no user exists or error occurs while querying, error will be returned.
// FindByUsername queries user by username. If a user with specified username exists,
// the user will be returned. Otherwise, error will be returned.
FindByUsername(ctx context.Context, username string) (*UserModel, error)
// UpdateDisplayNameByID updates a user with the specified ID with a new display name. If there is a user
// matches the query, it will return true. Error will be returned only when error occurs while accessing
// the database. This is a ONE mode because the first return type is a boolean.
// UpdateDisplayNameByID updates a user with the specified ID with a new display name.
// If there is a user matches the query, it will return true. Error will be returned
// only when error occurs while accessing the database.
UpdateDisplayNameByID(ctx context.Context, displayName string, id primitive.ObjectID) (bool, error)
// DeleteByCity deletes users that have `city` value match the parameter and returns the match count.
// The error will be returned only when error occurs while accessing the database. This is a MANY mode
// because the first return type is an integer.
// DeleteByCity deletes users that have `city` value match the parameter and returns
// the match count. The error will be returned only when error occurs while accessing
// the database. This is a MANY mode because the first return type is an integer.
DeleteByCity(ctx context.Context, city string) (int, error)
// CountByCity returns the number of rows that match the given city parameter. If an error occurs while
// accessing the database, error value will be returned.
// CountByCity returns the number of rows that match the given city parameter. If an
// error occurs while accessing the database, error value will be returned.
CountByCity(ctx context.Context, city string) (int, error)
}

View file

@ -21,45 +21,59 @@ type interfaceMethodParser struct {
}
func (p interfaceMethodParser) Parse() (MethodSpec, error) {
methodNameTokens := camelcase.Split(p.Method.Name)
switch methodNameTokens[0] {
case "Insert":
return p.parseInsertMethod(methodNameTokens[1:])
case "Find":
return p.parseFindMethod(methodNameTokens[1:])
case "Update":
return p.parseUpdateMethod(methodNameTokens[1:])
case "Delete":
return p.parseDeleteMethod(methodNameTokens[1:])
case "Count":
return p.parseCountMethod(methodNameTokens[1:])
}
return MethodSpec{}, UnknownOperationError
}
func (p interfaceMethodParser) parseInsertMethod(tokens []string) (MethodSpec, error) {
mode, err := p.extractInsertReturns(p.Method.Returns)
operation, err := p.parseMethod()
if err != nil {
return MethodSpec{}, err
}
return MethodSpec{
Name: p.Method.Name,
Params: p.Method.Params,
Returns: p.Method.Returns,
Operation: operation,
}, nil
}
func (p interfaceMethodParser) parseMethod() (Operation, error) {
methodNameTokens := camelcase.Split(p.Method.Name)
switch methodNameTokens[0] {
case "Insert":
return p.parseInsertOperation(methodNameTokens[1:])
case "Find":
return p.parseFindOperation(methodNameTokens[1:])
case "Update":
return p.parseUpdateOperation(methodNameTokens[1:])
case "Delete":
return p.parseDeleteOperation(methodNameTokens[1:])
case "Count":
return p.parseCountOperation(methodNameTokens[1:])
}
return nil, UnknownOperationError
}
func (p interfaceMethodParser) parseInsertOperation(tokens []string) (Operation, error) {
mode, err := p.extractInsertReturns(p.Method.Returns)
if err != nil {
return nil, err
}
if err := p.validateContextParam(); err != nil {
return MethodSpec{}, err
return nil, err
}
pointerType := code.PointerType{ContainedType: p.StructModel.ReferencedType()}
if mode == QueryModeOne && p.Method.Params[1].Type != pointerType {
return MethodSpec{}, InvalidParamError
return nil, InvalidParamError
}
arrayType := code.ArrayType{ContainedType: pointerType}
if mode == QueryModeMany && p.Method.Params[1].Type != arrayType {
return MethodSpec{}, InvalidParamError
return nil, InvalidParamError
}
return p.createMethodSpec(InsertOperation{
return InsertOperation{
Mode: mode,
}), nil
}, nil
}
func (p interfaceMethodParser) extractInsertReturns(returns []code.Type) (QueryMode, error) {
@ -91,33 +105,29 @@ func (p interfaceMethodParser) extractInsertReturns(returns []code.Type) (QueryM
return "", UnsupportedReturnError
}
func (p interfaceMethodParser) parseFindMethod(tokens []string) (MethodSpec, error) {
if len(tokens) == 0 {
return MethodSpec{}, UnsupportedNameError
}
func (p interfaceMethodParser) parseFindOperation(tokens []string) (Operation, error) {
mode, err := p.extractModelOrSliceReturns(p.Method.Returns)
if err != nil {
return MethodSpec{}, err
return nil, err
}
querySpec, err := parseQuery(tokens, 1)
if err != nil {
return MethodSpec{}, err
return nil, err
}
if err := p.validateContextParam(); err != nil {
return MethodSpec{}, err
return nil, err
}
if err := p.validateQueryFromParams(p.Method.Params[1:], querySpec); err != nil {
return MethodSpec{}, err
return nil, err
}
return p.createMethodSpec(FindOperation{
return FindOperation{
Mode: mode,
Query: querySpec,
}), nil
}, nil
}
func (p interfaceMethodParser) extractModelOrSliceReturns(returns []code.Type) (QueryMode, error) {
@ -153,27 +163,22 @@ func (p interfaceMethodParser) extractModelOrSliceReturns(returns []code.Type) (
return "", UnsupportedReturnError
}
func (p interfaceMethodParser) parseUpdateMethod(tokens []string) (MethodSpec, error) {
if len(tokens) == 0 {
return MethodSpec{}, UnsupportedNameError
}
func (p interfaceMethodParser) parseUpdateOperation(tokens []string) (Operation, error) {
mode, err := p.extractIntOrBoolReturns(p.Method.Returns)
if err != nil {
return MethodSpec{}, err
return nil, err
}
updateFieldTokens, queryTokens := p.splitUpdateFieldAndQueryTokens(tokens)
paramIndex := 1
var fields []UpdateField
var aggregatedToken string
for i, token := range tokens {
if token == "By" || token == "All" {
tokens = tokens[i:]
break
} else if token != "And" {
for _, token := range updateFieldTokens {
if token != "And" {
aggregatedToken += token
} else if len(aggregatedToken) == 0 {
return MethodSpec{}, InvalidUpdateFieldsError
return nil, InvalidUpdateFieldsError
} else {
fields = append(fields, UpdateField{Name: aggregatedToken, ParamIndex: paramIndex})
paramIndex++
@ -181,95 +186,103 @@ func (p interfaceMethodParser) parseUpdateMethod(tokens []string) (MethodSpec, e
}
}
if len(aggregatedToken) == 0 {
return MethodSpec{}, InvalidUpdateFieldsError
return nil, InvalidUpdateFieldsError
}
fields = append(fields, UpdateField{Name: aggregatedToken, ParamIndex: paramIndex})
querySpec, err := parseQuery(tokens, 1+len(fields))
querySpec, err := parseQuery(queryTokens, 1+len(fields))
if err != nil {
return MethodSpec{}, err
return nil, err
}
if err := p.validateContextParam(); err != nil {
return MethodSpec{}, err
return nil, err
}
for _, field := range fields {
structField, ok := p.StructModel.Fields.ByName(field.Name)
if !ok {
return MethodSpec{}, StructFieldNotFoundError
return nil, StructFieldNotFoundError
}
if structField.Type != p.Method.Params[field.ParamIndex].Type {
return MethodSpec{}, InvalidParamError
return nil, InvalidParamError
}
}
if err := p.validateQueryFromParams(p.Method.Params[len(fields)+1:], querySpec); err != nil {
return MethodSpec{}, err
return nil, err
}
return p.createMethodSpec(UpdateOperation{
return UpdateOperation{
Fields: fields,
Mode: mode,
Query: querySpec,
}), nil
}, nil
}
func (p interfaceMethodParser) parseDeleteMethod(tokens []string) (MethodSpec, error) {
if len(tokens) == 0 {
return MethodSpec{}, UnsupportedNameError
func (p interfaceMethodParser) splitUpdateFieldAndQueryTokens(tokens []string) ([]string, []string) {
var updateFieldTokens []string
var queryTokens []string
for i, token := range tokens {
if token == "By" || token == "All" {
queryTokens = tokens[i:]
break
} else {
updateFieldTokens = append(updateFieldTokens, token)
}
}
return updateFieldTokens, queryTokens
}
func (p interfaceMethodParser) parseDeleteOperation(tokens []string) (Operation, error) {
mode, err := p.extractIntOrBoolReturns(p.Method.Returns)
if err != nil {
return MethodSpec{}, err
return nil, err
}
querySpec, err := parseQuery(tokens, 1)
if err != nil {
return MethodSpec{}, err
return nil, err
}
if err := p.validateContextParam(); err != nil {
return MethodSpec{}, err
return nil, err
}
if err := p.validateQueryFromParams(p.Method.Params[1:], querySpec); err != nil {
return MethodSpec{}, err
return nil, err
}
return p.createMethodSpec(DeleteOperation{
return DeleteOperation{
Mode: mode,
Query: querySpec,
}), nil
}, nil
}
func (p interfaceMethodParser) parseCountMethod(tokens []string) (MethodSpec, error) {
if len(tokens) == 0 {
return MethodSpec{}, UnsupportedNameError
}
func (p interfaceMethodParser) parseCountOperation(tokens []string) (Operation, error) {
if err := p.validateCountReturns(p.Method.Returns); err != nil {
return MethodSpec{}, err
return nil, err
}
querySpec, err := parseQuery(tokens, 1)
if err != nil {
return MethodSpec{}, err
return nil, err
}
if err := p.validateContextParam(); err != nil {
return MethodSpec{}, err
return nil, err
}
if err := p.validateQueryFromParams(p.Method.Params[1:], querySpec); err != nil {
return MethodSpec{}, err
return nil, err
}
return p.createMethodSpec(CountOperation{
return CountOperation{
Query: querySpec,
}), nil
}, nil
}
func (p interfaceMethodParser) validateCountReturns(returns []code.Type) error {
@ -341,12 +354,3 @@ func (p interfaceMethodParser) validateQueryFromParams(params []code.Param, quer
return nil
}
func (p interfaceMethodParser) createMethodSpec(operation Operation) MethodSpec {
return MethodSpec{
Name: p.Method.Name,
Params: p.Method.Params,
Returns: p.Method.Returns,
Operation: operation,
}
}

View file

@ -965,13 +965,6 @@ func TestParseInterfaceMethod_Insert_Invalid(t *testing.T) {
func TestParseInterfaceMethod_Find_Invalid(t *testing.T) {
testTable := []ParseInterfaceMethodInvalidTestCase{
{
Name: "unsupported find method name",
Method: code.Method{
Name: "Find",
},
ExpectedError: spec.UnsupportedNameError,
},
{
Name: "invalid number of returns",
Method: code.Method{
@ -1006,6 +999,17 @@ func TestParseInterfaceMethod_Find_Invalid(t *testing.T) {
},
ExpectedError: spec.UnsupportedReturnError,
},
{
Name: "find method without query",
Method: code.Method{
Name: "Find",
Returns: []code.Type{
code.PointerType{ContainedType: code.SimpleType("UserModel")},
code.SimpleType("error"),
},
},
ExpectedError: spec.InvalidQueryError,
},
{
Name: "misplaced operator token (leftmost)",
Method: code.Method{
@ -1140,13 +1144,6 @@ func TestParseInterfaceMethod_Find_Invalid(t *testing.T) {
func TestParseInterfaceMethod_Update_Invalid(t *testing.T) {
testTable := []ParseInterfaceMethodInvalidTestCase{
{
Name: "unsupported update method name",
Method: code.Method{
Name: "Update",
},
ExpectedError: spec.UnsupportedNameError,
},
{
Name: "invalid number of returns",
Method: code.Method{
@ -1203,6 +1200,17 @@ func TestParseInterfaceMethod_Update_Invalid(t *testing.T) {
},
ExpectedError: spec.InvalidUpdateFieldsError,
},
{
Name: "update method without query",
Method: code.Method{
Name: "UpdateCity",
Returns: []code.Type{
code.SimpleType("bool"),
code.SimpleType("error"),
},
},
ExpectedError: spec.InvalidQueryError,
},
{
Name: "ambiguous query",
Method: code.Method{
@ -1292,13 +1300,6 @@ func TestParseInterfaceMethod_Update_Invalid(t *testing.T) {
func TestParseInterfaceMethod_Delete_Invalid(t *testing.T) {
testTable := []ParseInterfaceMethodInvalidTestCase{
{
Name: "unsupported delete method name",
Method: code.Method{
Name: "Delete",
},
ExpectedError: spec.UnsupportedNameError,
},
{
Name: "invalid number of returns",
Method: code.Method{
@ -1333,6 +1334,17 @@ func TestParseInterfaceMethod_Delete_Invalid(t *testing.T) {
},
ExpectedError: spec.UnsupportedReturnError,
},
{
Name: "delete method without query",
Method: code.Method{
Name: "Delete",
Returns: []code.Type{
code.SimpleType("int"),
code.SimpleType("error"),
},
},
ExpectedError: spec.InvalidQueryError,
},
{
Name: "misplaced operator token (leftmost)",
Method: code.Method{
@ -1467,25 +1479,6 @@ func TestParseInterfaceMethod_Delete_Invalid(t *testing.T) {
func TestParseInterfaceMethod_Count_Invalid(t *testing.T) {
testTable := []ParseInterfaceMethodInvalidTestCase{
{
Name: "unsupported count method name",
Method: code.Method{
Name: "Count",
},
ExpectedError: spec.UnsupportedNameError,
},
{
Name: "invalid number of returns",
Method: code.Method{
Name: "CountAll",
Returns: []code.Type{
code.SimpleType("int"),
code.SimpleType("error"),
code.SimpleType("bool"),
},
},
ExpectedError: spec.UnsupportedReturnError,
},
{
Name: "invalid number of returns",
Method: code.Method{
@ -1520,6 +1513,17 @@ func TestParseInterfaceMethod_Count_Invalid(t *testing.T) {
},
ExpectedError: spec.UnsupportedReturnError,
},
{
Name: "count method without query",
Method: code.Method{
Name: "Count",
Returns: []code.Type{
code.SimpleType("int"),
code.SimpleType("error"),
},
},
ExpectedError: spec.InvalidQueryError,
},
{
Name: "invalid query",
Method: code.Method{