tmpl

package
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 24, 2023 License: MIT Imports: 0 Imported by: 0

Documentation

Index

Constants

View Source
const ConnectionTemplate = `` /* 3765-byte string literal not displayed */

ConnectionTemplate is the template for the connection functions. This is included in the init template.

View Source
const ErrorsTemplate = `` /* 460-byte string literal not displayed */

ErrorsTemplate is the template for the errors. This is included in the init template.

View Source
const InitStatementTemplate = `` /* 496-byte string literal not displayed */

InitStatementTemplate is the template for the init functions.

View Source
const OptionsTemplate = `` /* 2976-byte string literal not displayed */
View Source
const SingleRepeatedTypesTemplate = `` /* 1121-byte string literal not displayed */
View Source
const StorageTemplate = `` /* 3273-byte string literal not displayed */

StorageTemplate is the template for the storage functions. This is included in the init template.

View Source
const StructureTemplate = `
// {{ structureName }} is a struct for the "{{ tableName }}" table.
type {{ structureName }} struct {
{{ range $field := fields }}
	{{ $field | fieldName }} {{ $field | fieldType }}{{if not ($field | isRelation) }}` + " `db:\"{{ $field | sourceName }}\"`" + `{{end}}{{end}}
}

// TableName returns the table name.
func (t *{{ structureName }}) TableName() string {
	return "{{ tableName }}"
}

// ScanRow scans a row into a {{ structureName }}.
func (t *{{ structureName }}) ScanRow(r *sql.Row) error {
	return r.Scan({{ range $field := fields }} {{if not ($field | isRelation) }} &t.{{ $field | fieldName }}, {{ end }}{{ end }})
}

// ScanRow scans a single row into the {{ structureName }}.
func (t *{{ structureName }}) ScanRows(r *sql.Rows) error {
	return r.Scan(
		{{- range $index, $field := fields }}
		{{- if not ($field | isRelation) }}
		&t.{{ $field | fieldName }},
		{{- end}}
		{{- end }}
	)
}
`
View Source
const TableConditionsTemplate = `` /* 18190-byte string literal not displayed */
View Source
const TableCountMethodTemplate = `` /* 832-byte string literal not displayed */
View Source
const TableCreateMethodTemplate = `` /* 3931-byte string literal not displayed */
View Source
const TableDeleteMethodTemplate = `` /* 672-byte string literal not displayed */
View Source
const TableFindManyMethodTemplate = `` /* 1483-byte string literal not displayed */
View Source
const TableFindOneMethodTemplate = `` /* 467-byte string literal not displayed */
View Source
const TableFindWithPaginationMethodTemplate = `` /* 1024-byte string literal not displayed */
View Source
const TableGetByIDMethodTemplate = `` /* 632-byte string literal not displayed */
View Source
const TableStorageTemplate = `
// {{ storageName | lowerCamelCase }} is a struct for the "{{ tableName }}" table.
type {{ storageName | lowerCamelCase }} struct {
	db *sql.DB // The database connection.
	queryBuilder sq.StatementBuilderType // queryBuilder is used to build queries.
}

type {{ storageName }} interface {
	// CreateTable creates the table.
	CreateTable(ctx context.Context) error
	// DropTable drops the table.
	DropTable(ctx context.Context) error
	// TruncateTable truncates the table.
	TruncateTable(ctx context.Context) error
	// UpgradeTable upgrades the table.
	UpgradeTable(ctx context.Context) error
	// Create creates a new {{ structureName }}.
	{{- if (hasID) }}
	Create(ctx context.Context, model *{{structureName}}, opts ...Option) (*{{IDType}}, error)
	{{- else }} 
	Create(ctx context.Context, model *{{structureName}}, opts ...Option) error
	{{- end }}
	// Update updates an existing {{ structureName }}.
	Update(ctx context.Context, id {{IDType}}, updateData *{{structureName}}Update) error
	{{- if (hasPrimaryKey) }}
	// Delete removes an existing {{ structureName }} by its ID.
	DeleteBy{{ getPrimaryKey.GetName | camelCase }}(ctx context.Context, {{getPrimaryKey.GetName}} {{IDType}}, opts ...Option) error
	{{- end }}
	{{- if (hasPrimaryKey) }}
	// FindBy{{ getPrimaryKey.GetName | camelCase }} retrieves a {{ structureName }} by its {{ getPrimaryKey.GetName }}.
	FindBy{{ getPrimaryKey.GetName | camelCase }}(ctx context.Context, id {{IDType}}, opts ...Option) (*{{ structureName }}, error)
	{{- end }}
	// FindMany finds multiple {{ structureName }} based on the provided options.
	FindMany(ctx context.Context, builder ...*QueryBuilder) ([]*{{structureName}}, error)
	// FindOne finds a single {{ structureName }} based on the provided options.
	FindOne(ctx context.Context, builders ...*QueryBuilder) (*{{structureName}}, error)	
    // Count counts {{ structureName }} based on the provided options.
	Count(ctx context.Context, builders ...*QueryBuilder) (int64, error)
	// FindManyWithPagination finds multiple {{ structureName }} with pagination support.
	FindManyWithPagination(ctx context.Context, limit int, page int, builders ...*QueryBuilder) ([]*{{structureName}}, *Paginator, error)
	
	//
	// Lazy load relations methods 
	//

	{{- range $index, $field := fields }}
	{{- if and ($field | isRelation) }}
	// Load{{ $field | pluralFieldName }} loads the {{ $field | pluralFieldName }} relation.
	Load{{ $field | pluralFieldName }} (ctx context.Context, model *{{structureName}}, builders ...*QueryBuilder) error
	{{- end }}
	{{- end }}
	{{- range $index, $field := fields }}
	{{- if and ($field | isRelation) }}
	// LoadBatch{{ $field | pluralFieldName }} loads the {{ $field | pluralFieldName }} relation.
	LoadBatch{{ $field | pluralFieldName }} (ctx context.Context, items []*{{structureName}}, builders ...*QueryBuilder) error
	{{- end }}
	{{- end }}
}

// New{{ storageName }} returns a new {{ storageName | lowerCamelCase }}.
func New{{ storageName }}(db *sql.DB) {{ storageName }} {
	return &{{ storageName | lowerCamelCase }}{
		db: db,
		queryBuilder: sq.StatementBuilder.PlaceholderFormat(sq.Dollar),
	}
}

// TableName returns the table name.
func (t *{{ storageName | lowerCamelCase }}) TableName() string {
	return "{{ tableName }}"
}

// Columns returns the columns for the table.
func (t *{{ storageName | lowerCamelCase }}) Columns() []string {
	return []string{
		{{ range $field := fields }}{{if not ($field | isRelation) }}"{{ $field | sourceName }}",{{ end }}{{ end }}
	}
}

// DB returns the underlying sql.DB. This is useful for doing transactions.
func (t *{{ storageName | lowerCamelCase }}) DB(ctx context.Context) QueryExecer {
	var db QueryExecer = t.db
	if tx, ok := TxFromContext(ctx); ok {
		db = tx
	}

	return db
}

// createTable creates the table.
func (t *{{ storageName | lowerCamelCase }}) CreateTable(ctx context.Context) error {
	sqlQuery := ` + "`" + `
		{{- range $index, $field := fields }}
		{{- if ($field | isDefaultUUID ) }}
		CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
		{{- end}}
		{{- end}}
		-- Table: {{ tableName }}
		CREATE TABLE IF NOT EXISTS {{ tableName }} (
		{{- range $index, $field := fields }}
		{{- if not ($field | isRelation) }}
		{{ $field | sourceName }} {{if ($field | isAutoIncrement) }} SERIAL{{else}}{{ $field | postgresType }}{{end}}{{if $field | isPrimaryKey }} PRIMARY KEY{{end}}{{if ($field | isUnique) }} UNIQUE{{end}}{{ if and (isNotNull $field) (not (isAutoIncrement $field)) }} NOT NULL{{ end }}{{if ($field | getDefaultValue) }} DEFAULT {{$field | getDefaultValue}}{{end}}{{if not ( $field | isLastField )}},{{end}}
		{{- end}}
		{{- end}});
		{{if (comment) }}COMMENT ON TABLE {{ tableName }} IS '{{ comment }}';{{end}}
	` + "`" + `

	_, err := t.db.ExecContext(ctx,sqlQuery)
	return err
}

// DropTable drops the table.
func (t *{{ storageName | lowerCamelCase }}) DropTable(ctx context.Context) error {
	sqlQuery := ` + "`" + `
		DROP TABLE IF EXISTS {{ tableName }};
	` + "`" + `

	_, err := t.db.ExecContext(ctx,sqlQuery)
	return err
}

// TruncateTable truncates the table.
func (t *{{ storageName | lowerCamelCase }}) TruncateTable(ctx context.Context) error {
	sqlQuery := ` + "`" + `
		TRUNCATE TABLE {{ tableName }};
	` + "`" + `

	_, err := t.db.ExecContext(ctx,sqlQuery)
	return err
}

// UpgradeTable upgrades the table.
// todo: delete this method 
func (t *{{ storageName | lowerCamelCase }}) UpgradeTable(ctx context.Context) error {
	return nil
}

{{- range $index, $field := fields }}
{{- if and ($field | isRelation) }}
// Load{{ $field | pluralFieldName }} loads the {{ $field | pluralFieldName }} relation.
func (t *{{ storageName | lowerCamelCase }}) Load{{ $field | pluralFieldName }} (ctx context.Context, model *{{structureName}}, builders ...*QueryBuilder) error {
	if model == nil {
		return errors.Wrap(ErrModelIsNil, "{{structureName}} is nil")
	}

	// New{{ $field | relationStorageName }} creates a new {{ $field | relationStorageName }}.
	s := New{{ $field | relationStorageName }}(t.db)

	// Add the filter for the relation
	builders = append(builders, FilterBuilder({{ $field | relationStructureName  }}{{ $field | getRefID }}Eq(model.{{ $field | getFieldID }})))
	{{- if ($field | isRepeated) }}
		relationModels, err := s.FindMany(ctx, builders...)
		if err != nil {
			return fmt.Errorf("failed to find many {{ $field | relationStorageName }}: %w", err)
		}

		model.{{ $field | fieldName }} = relationModels
	{{- else }}
		relationModel, err := s.FindOne(ctx, builders...)
		if err != nil {
			return fmt.Errorf("failed to find {{ $field | relationStorageName }}: %w", err)
		}

		model.{{ $field | fieldName }} = relationModel
	{{- end }}
	return nil
}
{{- end }}
{{- end }}

{{- range $index, $field := fields }}
{{- if and ($field | isRelation) }}
// LoadBatch{{ $field | pluralFieldName }} loads the {{ $field | pluralFieldName }} relation.
func (t *{{ storageName | lowerCamelCase }}) LoadBatch{{ $field | pluralFieldName }} (ctx context.Context, items []*{{structureName}}, builders ...*QueryBuilder) error {
	requestItems := make([]interface{}, len(items))
	for i, item := range items {
		requestItems[i] = item.{{ $field | getFieldID }}
	}

	// New{{ $field | relationStorageName }} creates a new {{ $field | relationStorageName }}.
	s := New{{ $field | relationStorageName }}(t.db)

	// Add the filter for the relation
	builders = append(builders, FilterBuilder({{ $field | relationStructureName  }}{{ $field | getRefID }}In(requestItems...)))

	results, err := s.FindMany(ctx, builders...)
	if err != nil {
		return fmt.Errorf("failed to find many {{ $field | relationStorageName }}: %w", err)
	}

	{{- if ($field | isRepeated) }}
	resultMap := make(map[interface{}][]*{{ $field | relationStructureName }})
	{{- else }}
	resultMap := make(map[interface{}]*{{ $field | relationStructureName }})
	{{- end }}
	for _, result := range results {
		{{- if ($field | isRepeated) }}
		resultMap[result.{{ $field | getRefID }}] = append(resultMap[result.{{ $field | getRefID }}], result)
		{{- else }}
		resultMap[result.{{ $field | getRefID }}] = result
		{{- end }}
	}

	// Assign {{ $field | relationStructureName }} to items
	for _, item := range items {
        if v, ok := resultMap[item.{{ $field | getFieldID }}]; ok {
			item.{{ $field | fieldName }} = v
		}
	}

	return nil
}
{{- end }}
{{- end }}
`
View Source
const TableTemplate = `` /* 409-byte string literal not displayed */
View Source
const TableUpdateMethodTemplate = `` /* 1689-byte string literal not displayed */
View Source
const TransactionManagerTemplate = `` /* 3472-byte string literal not displayed */
View Source
const TypesTemplate = `
{{ range $key, $field := nestedMessages }}
// {{ $key }} is a JSON type nested in another message.
type {{ $field.StructureName }} struct {
	{{- range $nestedField := $field.Descriptor.GetField }}
	{{ $nestedField | fieldName }} {{ $nestedField | fieldType }}` + " `json:\"{{ $nestedField | sourceName }}\"`" + `
	{{- end }}
}

// Scan implements the sql.Scanner interface for JSON.
func (m *{{ $field.StructureName }}) Scan(src interface{}) error  {
	if bytes, ok := src.([]byte); ok {
		return json.Unmarshal(bytes, m)
	}

	return fmt.Errorf("can't convert %T", src)
}

// Value implements the driver.Valuer interface for JSON.
func (m *{{ $field.StructureName }}) Value() (driver.Value, error) {
	if m == nil {
		m = &{{ $field.StructureName }}{}
	}
	return json.Marshal(m)
}
{{ end }}
`

Variables

This section is empty.

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL