embed

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2022 License: MIT Imports: 1 Imported by: 0

Documentation

Index

Constants

View Source
const FojiDotYaml = `` /* 3326-byte string literal not displayed */
View Source
const FojiSlashDbListDotConsoleDotTpl = `` /* 1605-byte string literal not displayed */
View Source
const FojiSlashEmbedDotGoDotTpl = `// Code generated by foji {{ version }}, template: {{ templateFile }}; DO NOT EDIT.

package {{ .Params.PackageName }}

import "os"

func List() []string {
	return []string{
{{- range .FileGroups }}
	{{- range .Files }}
		"{{ .Name }}",
	{{- end }}
{{- end}}
		}
}

func Get(filename string) ([]byte, error) {
	switch filename {
{{- range .FileGroups }}
{{- range .Files }}
	case "{{ .Name }}":
		return {{ case (goToken .Name) }}Bytes, nil
{{- end }}
{{- end}}
	}

	return nil, os.ErrNotExist
}

func GetString(filename string) (string, error) {
	switch filename {
{{- range .FileGroups }}
{{- range .Files }}
	case "{{ .Name }}":
		return {{ case (goToken .Name) }}, nil
{{- end }}
{{- end}}
	}

	return "", os.ErrNotExist
}
{{- range .FileGroups }}
{{- range .Files }}

var {{ case (goToken .Name) }}Bytes = []byte({{ case (goToken .Name) }})
const {{ case (goToken .Name) }} = ` + "`" + `{{ backQuote (toString .Content) }}` + "`" + `
{{- end -}}
{{end -}}`
View Source
const FojiSlashEnumDotGoDotTpl = `` /* 3759-byte string literal not displayed */
View Source
const FojiSlashFieldsDotGoDotTpl = `` /* 11105-byte string literal not displayed */
View Source
const FojiSlashOpenapiSlashAuthDotGoDotTpl = `` /* 5654-byte string literal not displayed */
View Source
const FojiSlashOpenapiSlashDocsDotGoDotTpl = `// Code generated by foji {{ version }}, template: {{ templateFile }}; DO NOT EDIT.

package {{ .Params.PackageName }}

import (
	"net/http"

	"github.com/fasthttp/router"
	"github.com/valyala/fasthttp"
)

var (
	strApplicationHTML = []byte("text/html")
	reDocHTML          = []byte(` + "`" + `<!DOCTYPE html>
<html>
  <head>
    <title>{{ .Params.Title }}</title>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
    <style>
      body {
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <redoc spec-url='swagger.yaml' {{ .Params.RedocOptions }} ></redoc>
    <script src="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"> </script>
  </body>
</html>` + "`" + `)
)

func Register(r *router.Router) {
	r.GET("/docs", GetHTML)
	r.GET("/swagger.yaml", GetYaml)
}

func GetHTML(ctx *fasthttp.RequestCtx) {
	ctx.Response.Header.SetContentTypeBytes(strApplicationHTML)
	_, err := ctx.Write(reDocHTML)
	if err != nil {
		ctx.Error(err.Error(), http.StatusInternalServerError)
	}
}

func GetYaml(ctx *fasthttp.RequestCtx) {

{{- range .FileGroups }}
	{{- range .Files }}
		_, err := ctx.Write({{ case (goToken .Name) }}Bytes)
	{{- end -}}
{{end }}
	if err != nil {
		ctx.Error(err.Error(), http.StatusInternalServerError)
		return
	}
}
`
View Source
const FojiSlashOpenapiSlashErrorDotGoDotTpl = `` /* 522-byte string literal not displayed */
View Source
const FojiSlashOpenapiSlashHandlerDotGoDotTpl = `` /* 7136-byte string literal not displayed */
View Source
const FojiSlashOpenapiSlashMainDotGoDotTpl = `` /* 1384-byte string literal not displayed */
View Source
const FojiSlashOpenapiSlashModelDotGoDotTpl = `{{- define "propertyDeclaration"}}
    {{- $key := .RuntimeParams.key }}
    {{- $schema := .RuntimeParams.schema }}
    {{- $typeName := .RuntimeParams.typeName }}
    {{- if not (empty $schema.Value.Description) }}
    // {{ $schema.Value.Description }}
    {{- end }}
    {{- if $.IsDefaultEnum  $key $schema }}
    {{ pascal $key }}  {{print $typeName (pascal $key) "Enum"}} ` + "`" + `json:"{{$key}},omitempty"` + "`" + `
    {{- else }}
    {{ pascal $key }} {{ $.GetType .PackageName $key $schema }} ` + "`" + `json:"{{$key}},omitempty"` + "`" + `
    {{- end }}
{{- end -}}

// Code generated by foji {{ version }}, template: {{ templateFile }}; DO NOT EDIT.

package {{ .PackageName }}

import (
{{- range .Imports }}
    "{{ . }}"
{{- end }}
    "github.com/bir/iken/validation"
)
{{ range $key, $schema := .File.API.Components.Schemas }}
{{- if isNil (index $schema.Value.Extensions "x-go-type" ) }}
{{- $typeName := pascal $key }}
//  {{ $typeName }}
{{- if not (empty .Value.Description) }}
//  {{ $schema.Value.Description }}
{{- end}}
//
// OpenAPI Component: {{ $key }}
type {{ pascal $key }} struct {
{{- range $key, $schema := .Value.Properties }}
    {{- template "propertyDeclaration" ($.WithParams "key" $key "schema" $schema "typeName" $typeName)}}
{{- end }}
{{- range .Value.AllOf }}
    {{- if notEmpty .Ref }}
        {{ $.GetTypeName $.PackageName  . }}
    {{- else }}
        {{- range $key, $schema := .Value.Properties }}
            {{- template "propertyDeclaration" ($.WithParams "key" $key "schema" $schema "typeName" $typeName)}}
        {{- end }}
    {{- end }}
{{- end }}

}
{{- range $key, $schema := .Value.Properties }}
    {{- if notEmpty $schema.Value.Pattern }}

var {{ camel $typeName }}{{ pascal $key }}Pattern = regexp.MustCompile(` + "`" + `{{ $schema.Value.Pattern }}` + "`" + `)
    {{- end}}
{{- end }}

{{- range $key, $schema := .Value.Properties }}
    {{- if not (empty $schema.Value.Enum) }}
    {{- $enumType := print $typeName (pascal $key) "Enum" }}

type {{ $enumType }} int32

const (
    Unknown{{ $enumType }} {{ $enumType }} = iota
    {{- range $i, $value := $schema.Value.Enum }}
    {{ $enumType }}{{ pascal (goToken $value) }}
    {{- end }}
)

func New{{ $enumType }}(name string) {{ $enumType }} {
    switch name {
    {{- range $schema.Value.Enum  }}
        case "{{ . }}":
        return {{ $enumType }}{{ pascal (goToken .) }}
    {{- end }}
    }

    return {{ $enumType }}(0)
}


var  {{ $enumType }}String = map[{{ $enumType }}]string{
    {{- range $schema.Value.Enum }}
        {{ $enumType }}{{ pascal (goToken .) }}: "{{ . }}",
    {{- end }}
}

func (e {{ $enumType }}) String() string {
    return {{ $enumType }}String[e]
}

func (e *{{ $enumType }}) UnmarshalJSON(input []byte) (err error) {
	var i int32

	err = json.Unmarshal(input, &i)
	if err == nil {
		*e = {{ $enumType }}(i)
		return nil
	}

	var s string

	err = json.Unmarshal(input, &s)
	if err != nil {
		return err
	}

	*e = New{{ $enumType }}(s)

	return nil
}

func (e *{{ $enumType }}) MarshalJSON() (result []byte, err error) {
    return json.Marshal(e.String())
}
    {{- end}}
{{- end }}

func (p {{ pascal $key }}) Validate() error {
    {{- if $.HasValidation . }}
    var err validation.Errors
{{- range $key, $schema := .Value.Properties }}
    {{- if in $schema.Value.Type "number" "integer" }}
        {{- $fieldType := $.GetType $.PackageName $key $schema }}
        {{- if isNotNil $schema.Value.Min }}

    if p.{{ pascal $key }} <{{ if $schema.Value.ExclusiveMin }}={{end}} {{ $schema.Value.Min }} {
        _ = err.Add("{{$key}}", "must be >{{ if not $schema.Value.ExclusiveMin }}={{end}} {{ $schema.Value.Min }}")
    }
        {{- end }}
        {{- if isNotNil $schema.Value.Max }}

    if p.{{ pascal $key }} >{{ if $schema.Value.ExclusiveMax }}={{end}} {{ $schema.Value.Max }} {
        _ = err.Add("{{$key}}", "must be <{{ if not $schema.Value.ExclusiveMax }}={{end}} {{ $schema.Value.Max }}")
    }
        {{- end }}
        {{- if isNotNil $schema.Value.MultipleOf }}
            {{- if eq $schema.Value.Type "integer" }}

    if p.{{ pascal $key }} % {{ $schema.Value.MultipleOf }} != 0 {
        _ = err.Add("{{$key}}", "must be multiple of {{ $schema.Value.MultipleOf }}")
    }
            {{- else }}
    if math.Mod({{ if not (eq $fieldType "float64") }}float64({{ end }}p.{{ pascal $key }}{{ if not (eq $fieldType "float64") }}){{end}}, {{ $schema.Value.MultipleOf }}) != 0 {
        _ = err.Add("{{$key}}", "must be multiple of {{ $schema.Value.MultipleOf }}")
    }
            {{- end }}
        {{- end }}
    {{- else if eq $schema.Value.Type "string" }}
        {{- $fieldType := $.GetType $.PackageName $key $schema }}
        {{- if gt $schema.Value.MinLength 0 }}

    if len(p.{{ pascal $key }}) < {{ $schema.Value.MinLength }} {
        _ = err.Add("{{$key}}", "length must be >= {{ $schema.Value.MinLength }}")
    }
        {{- end }}
        {{- if isNotNil $schema.Value.MaxLength }}

    if len(p.{{ pascal $key }}) > {{ $schema.Value.MaxLength }} {
        _ = err.Add("{{$key}}", "length must be <= {{ $schema.Value.MaxLength }}")
    }
        {{- end }}
        {{- if notEmpty $schema.Value.Pattern }}

    if !{{ camel $typeName }}{{ pascal $key }}Pattern.MatchString( p.{{ pascal $key }})  {
        _ = err.Add("{{$key}}", "must match {{ $schema.Value.Pattern }}")
    }
        {{- end }}
    {{- else if eq $schema.Value.Type "array" }}
        {{- if gt $schema.Value.MinItems 0 }}

    if len(p.{{ pascal $key }}) < {{ $schema.Value.MinItems }} {
        _ = err.Add("{{$key}}", "length must be >= {{ $schema.Value.MinItems }}")
    }
        {{- end }}
        {{- if isNotNil $schema.Value.MaxItems }}

    if len(p.{{ pascal $key }}) > {{ $schema.Value.MaxItems }} {
        _ = err.Add("{{$key}}", "length must be <= {{ $schema.Value.MaxItems }}")
    }
        {{- end }}
    {{- end }}
{{- end }}

    return err.GetErr()
{{- else }}
    return nil
{{- end }}
}
{{ end }}
{{- end}}

`
View Source
const FojiSlashOpenapiSlashServiceDotGoDotTpl = `` /* 1739-byte string literal not displayed */
View Source
const FojiSlashOpenapiSlashStubDotYamlDotTpl = `` /* 4893-byte string literal not displayed */
View Source
const FojiSlashPgxSlashDbDotGoDotTpl = `` /* 661-byte string literal not displayed */
View Source
const FojiSlashPgxSlashModelDotGoDotTpl = `// Code generated by foji {{ version }}, template: {{ templateFile }}; DO NOT EDIT.
{{- $table := .Table.Name}}
{{- $goName := case .Table.Name -}}
{{- $colNames := .Table.Columns.ByOrdinal.Names }}
{{- $pkNames := cases .Table.PrimaryKeys.ByOrdinal.Names }}

package {{ $.PackageName }}

import (
	"fmt"

{{- range .Imports }}
	"{{ . }}"
{{- end }}
)

// {{$goName}} represents a record from '{{.Schema.Name}}.{{$table}}'.
type {{$goName}} struct {
{{- range .Table.Columns.ByOrdinal }}
	{{ case .Name }} {{ $.GetType . $.PackageName }}  ` + "`" + `json:"{{ .Name }},omitempty"` + "`" + ` // {{ .Type }} {{ if .Nullable }}NULL{{end}}
{{- end }}
}

func (r {{$goName}}) String() string {
	return fmt.Sprintf( "{{$goName}}{
		{{- csv ($pkNames.Sprintf "%s:%%v" ) }}}",
		{{- csv ($pkNames.Sprintf "r.%s" ) }})
}

// Field values for every column in {{.Table.Name}}.  These are used for custom where clause queries
var (
{{- range .Table.Columns.ByOrdinal }}
	{{$goName}}{{case .Name}} {{ title (replaceEach ( $.GetType . $.PackageName) "" "." "*" "{" "}" ) }}Field = "{{ .Name }}"
{{- end}}
)

`
View Source
const FojiSlashPgxSlashTableDotGoDotTpl = `// Code generated by foji {{ version }}, template: {{ templateFile }}; DO NOT EDIT.
{{- $pkgName := "pg" }}
{{- $table := .Table.Name}}
{{- $schema := .Table.Schema.Name}}
{{- $goName := case $table }}
{{- $hasSoftDeletes := .Table.Columns.Names.Contains "deleted_at"}}
{{- $mutableCols := (.Table.Columns.Filter .Table.PrimaryKeys.Paths).ByOrdinal.Names }}
{{- $mutableFields := (cases $mutableCols).Sprintf "row.%s"}}
{{- $scanFields := (cases .Table.Columns.ByOrdinal.Names).Sprintf "&row.%s"}}
{{- $selectFields := csv .Table.Columns.ByOrdinal.Names}}
{{- $PKs := cases .Table.PrimaryKeys.ByOrdinal.Names }}
{{- $PKFields := csv ($PKs.Sprintf "row.%s")}}
{{- $PKScanFields := csv ($PKs.Sprintf "&row.%s")}}

package {{ $pkgName }}

import (
	"context"
	"fmt"

	"github.com/jackc/pgx/v4"

	"{{.Params.Package}}"
{{- range .Imports }}
	"{{ . }}"
{{- end }}
)

const querySelect{{$goName}} = ` + "`" + `SELECT
	{{ $selectFields }}
FROM {{$schema}}.{{$table}} ` + "`" + `

func scan{{$goName}}(rr pgx.Rows) ([]*{{$.PackageName}}.{{$goName}}, error) {
	var result []*{{$.PackageName}}.{{$goName}}
	for rr.Next() {
		row := {{$.PackageName}}.{{$goName}}{}
		err := rr.Scan({{ csv $scanFields }})
		if err != nil {
			return nil, fmt.Errorf("scan{{$goName}}:%w", err)
		}
		result = append(result, &row)
	}
	return result, nil
}

func scanOne{{$goName}}(rr pgx.Row) (*{{$.PackageName}}.{{$goName}}, error) {
	row := {{$.PackageName}}.{{$goName}}{}
	err := rr.Scan({{ csv $scanFields }})
	if err != nil {
		return nil, fmt.Errorf("{{$goName}}:%w", err)
	}
	return &row, nil
}

// All retrieves all rows from '{{$table}}' as a slice of {{$goName}}.
func (r Repo) All{{$goName}}(ctx context.Context) ([]*{{$.PackageName}}.{{$goName}}, error) {
	query :=  querySelect{{$goName }}
{{- if $hasSoftDeletes -}}
	+ ` + "`" + `WHERE deleted_at is NULL ` + "`" + `
{{- end}}
	q, err := r.db.Query(ctx,query)
	if err != nil {
		return nil, fmt.Errorf("{{$goName}}:%w", err)
	}
	return scan{{$goName}}(q)
}

// Count gets size of '{{$table}}'.
func (r Repo) Count{{$goName}}(ctx context.Context, where {{$.PackageName}}.WhereClause) (int, error) {
	idx := 1
	query := ` + "`" + `SELECT
		count(*) as count
		FROM {{$schema}}.{{$table}}
		WHERE ` + "`" + ` + where.String(&idx)
		
	count := 0
	return count, r.db.QueryRow(ctx, query, where.Values()...).Scan(&count)
}

// Select retrieves rows from '{{$table}}' as a slice of {{$goName}}.
func (r Repo) Select{{$goName}}(ctx context.Context, where {{$.PackageName}}.WhereClause) ([]*{{$.PackageName}}.{{$goName}}, error) {
	idx := 1
	query := querySelect{{$goName}} + " WHERE " + where.String(&idx)
{{- if $hasSoftDeletes -}}
	+ ` + "`" + ` AND deleted_at is NULL ` + "`" + `
{{- end}}

	q, err := r.db.Query(ctx, query, where.Values()...)
	if err != nil {
		return nil, fmt.Errorf("{{$goName}}:%w", err)
	}
	return scan{{$goName}}(q)
}

// SelectOrder retrieves rows from '{{$table}}' as a slice of {{$goName}} in a particular order.
func (r Repo) SelectOrder{{$goName}}(ctx context.Context, where {{$.PackageName}}.WhereClause, orderBy {{$.PackageName}}.OrderByClause) ([]*{{$.PackageName}}.{{$goName}}, error) {
	idx := 1
	query := querySelect{{$goName}} + " WHERE " + where.String(&idx)
{{- if $hasSoftDeletes -}}
	+ ` + "`" + ` AND deleted_at is NULL ` + "`" + `
{{- end}} + " " + orderBy.String()

	q, err := r.db.Query(ctx, query, where.Values()...)
	if err != nil {
		return nil, fmt.Errorf("{{$goName}}:%w", err)
	}
	return scan{{$goName}}(q)
}

// First retrieve one row from '{{$table}}' when sorted by orderBy.
func (r Repo) First{{$goName}}(ctx context.Context, where {{$.PackageName}}.WhereClause, orderBy {{$.PackageName}}.OrderByClause) (*{{$.PackageName}}.{{$goName}}, error) {
	idx := 1
	query := querySelect{{$goName}} + " WHERE " + where.String(&idx)
{{- if $hasSoftDeletes -}}
	+ ` + "`" + ` AND deleted_at is NULL ` + "`" + `
{{- end}} + " " + orderBy.String() + " LIMIT 1"

	q := r.db.QueryRow(ctx, query, where.Values()...)
	return scanOne{{$goName}}(q)
}

{{- /* Takes the number of values to produce and produces a list of postgres
placeholders of the form $1, $2, etc */}}
{{- define "values" -}}
	{{$nums := numbers 1 . -}}
	{{$indices := $nums.Sprintf "$%s" -}}
	{{csv $indices -}}
{{end}}

// Insert inserts the row into the database.
func (r Repo) Insert{{$goName}}(ctx context.Context, row *{{$.PackageName}}.{{$goName}}) error {
const query = ` + "`" + `INSERT INTO {{$schema}}.{{$table}}
{{- if gt (len $mutableCols) 0}}
	({{ csv $mutableCols }})
	VALUES
	({{template "values" (len $mutableCols) }})
{{- else}}
	DEFAULT VALUES
{{- end}}
	RETURNING
		{{csv .Table.PrimaryKeys.Names.Sort }}` + "`" + `
	q := r.db.QueryRow(ctx, query,{{- csv $mutableFields }})
	return q.Scan({{$PKScanFields}})
}
{{if gt (len $mutableCols) 0}}
// Update the Row in the database.
func (r Repo) Update{{$goName}}(ctx context.Context, row *{{$.PackageName}}.{{$goName}}) error {
	query := ` + "`" + `UPDATE {{$schema}}.{{$table}}
	SET
		({{csv $mutableCols }}) =
		({{ template "values" (len $mutableCols) }})
	WHERE
	{{$last := sum (len .Table.PrimaryKeys) (len $mutableCols)}}
	{{- $first := inc (len $mutableCols)}}
	{{- range $x, $name := .Table.PrimaryKeys.Names.Sort -}}
		{{$name}} = ${{sum $first $x}}{{if lt (sum $x $first) $last}} AND {{end}}
	{{- end}}` + "`" + `

	_, err := r.db.Exec(ctx, query, {{csv $mutableFields }}, {{$PKFields}})
	return fmt.Errorf("{{$goName}}:%w", err)
	}
{{end}}
// Set sets a single column on an existing row in the database.
func (r Repo) Set{{$goName}}(ctx context.Context, set {{$.PackageName}}.Where, where {{$.PackageName}}.WhereClause) (int64, error) {
	idx := 2
	query := ` + "`" + `UPDATE {{$schema}}.{{$table}} SET ` + "`" + ` +
		set.Field + " = $1 " +
		` + "`" + `WHERE ` + "`" + ` +
		where.String(&idx)

	res, err := r.db.Exec(ctx, query, append([]interface{}{ set.Value }, where.Values()...)...)
	if err != nil {
		return 0, fmt.Errorf("{{$goName}}:%w", err)
	}
	return res.RowsAffected(), nil
}
{{- if .Table.HasPrimaryKey }}
{{- if $hasSoftDeletes}}
// Delete{{$goName}} soft deletes the row from the database. Returns the number of items soft deleted.
{{else}}
// Delete{{$goName}} deletes the Row from the database. Returns the number of items deleted.
{{end}}
func (r Repo) Delete{{$goName}}( ctx context.Context, {{ $.Parameterize .Table.PrimaryKeys "%s %s" $pkgName }}) (int64, error) {
	{{- if $hasSoftDeletes}}
	const query = ` + "`" + `UPDATE {{$schema}}.{{$table}}
		SET deleted_at = now()
		WHERE
		{{ range $x, $name := .Table.PrimaryKeys.Names.Sort -}}
			{{$name}} = ${{inc $x}}{{if lt $x (sum (len $.Table.PrimaryKeys) -1)}} AND {{end}}
		{{- end}} AND deleted_at is NULL
		` + "`" + `
	{{- else }}
	const query = ` + "`" + `DELETE FROM {{$schema}}.{{$table}} WHERE
		{{ range $x, $name := .Table.PrimaryKeys.Names.Sort -}}
			{{$name}} = ${{inc $x}}{{if lt $x (sum (len $.Table.PrimaryKeys) -1)}} AND {{end}}
		{{- end}}` + "`" + `{{- end}}
	res, err := r.db.Exec(ctx, query,
	{{- csv .Table.PrimaryKeys.Names.Sort.Camel  -}}
	)
	if err != nil {
		return 0, fmt.Errorf("{{$goName}}:%w", err)
	}
	return res.RowsAffected(), nil
}
{{- if $hasSoftDeletes}}
// DeletePermanent{{$goName}} deletes the Row from the database. This bypasses the soft delete mechanism.
// Returns the number of items deleted.
func (r Repo) DeletePermanent{{$goName}}( ctx context.Context, {{ $.Parameterize .Table.PrimaryKeys "%s %s" $pkgName }}) (int64, error) {
	const query = ` + "`" + `DELETE FROM {{$schema}}.{{$table}} WHERE
		{{ range $x, $name := .Table.PrimaryKeys.Names.Sort -}}
			{{$name}} = ${{inc $x}}{{if lt $x (sum (len $.Table.PrimaryKeys) -1)}} AND {{end}}
		{{- end}}` + "`" + `
	res, err := r.db.Exec(ctx, query,
	{{- csv .Table.PrimaryKeys.Names.Sort.Camel  -}}
	)
	if err != nil {
		return 0, fmt.Errorf("{{$goName}}:%w", err)
	}
	return res.RowsAffected(), nil
}
{{end}}
{{end}}
// DeleteWhere{{$goName}} deletes Rows from the database and returns the number of rows deleted.
func (r Repo) DeleteWhere{{$goName}}(ctx context.Context, where {{$.PackageName}}.WhereClause) (int64, error) {
	idx := 1
{{ if $hasSoftDeletes}}
	query := ` + "`" + `UPDATE {{$schema}}.{{$table}}
		SET deleted_at = now()
		WHERE ` + "`" + ` + where.String(&idx) + ` + "`" + ` AND deleted_at is NULL` + "`" + `
{{ else }}
	query := ` + "`" + `DELETE FROM {{$schema}}.{{$table}}
		WHERE ` + "`" + ` + where.String(&idx)
{{ end }}
	res, err := r.db.Exec(ctx, query, where.Values()...)
	if err != nil {
		return 0, fmt.Errorf("{{$goName}}:%w", err)
	}
	return res.RowsAffected(), nil
}
{{ if $hasSoftDeletes}}
// UndeleteWhere{{$goName}} undeletes the Row from the database.
func (r Repo) Undelete{{$goName}}(ctx context.Context, {{ $.Parameterize .Table.PrimaryKeys "%s %s" $pkgName }}) (int64, error) {
	query := ` + "`" + `UPDATE {{$schema}}.{{$table}}
	SET deleted_at = NULL
	WHERE
{{- range $x, $name := .Table.PrimaryKeys.Names.Sort }}
	{{$name}} = ${{inc $x}}{{if lt $x (sum (len $.Table.PrimaryKeys) -1)}} AND {{end}}
{{- end}} AND deleted_at is not NULL` + "`" + `

	res, err := r.db.Exec(ctx, query, {{ csv .Table.PrimaryKeys.Names.Sort.Camel  -}})
	if err != nil {
		return 0, fmt.Errorf("{{$goName}}:%w", err)
	}
	return res.RowsAffected(), nil
}

// DeleteWherePermanent{{$goName}} deletes the Row from the database. This bypasses the soft delete mechanism.
// Returns the number of items deleted.
func (r Repo) DeleteWherePermanent{{$goName}}(ctx context.Context, where {{$.PackageName}}.WhereClause) (int64, error) {
	idx := 1
	query := ` + "`" + `DELETE FROM {{$schema}}.{{$table}}
		WHERE ` + "`" + ` + where.String(&idx)

	res, err := r.db.Exec(ctx, query,  where.Values()...)
	if err != nil {
		return 0, fmt.Errorf("{{$goName}}:%w", err)
	}
	return res.RowsAffected(), nil
}

// UndeleteWhere{{$goName}} undeletes the Row from the database.
func (r Repo) UndeleteWhere{{$goName}}(ctx context.Context, where {{$.PackageName}}.WhereClause) (int64, error) {
	idx := 1
	query := ` + "`" + `UPDATE {{$schema}}.{{$table}}
		SET deleted_at = null
		WHERE ` + "`" + ` + where.String(&idx) + ` + "`" + ` AND deleted_at is NOT NULL` + "`" + `

	res, err := r.db.Exec(ctx, query, where.Values()...)
	if err != nil {
		return 0, fmt.Errorf("{{$goName}}:%w", err)
	}
	return res.RowsAffected(), nil
}

{{ end -}}

{{ range .Table.Indexes -}}
	{{- $FuncName := print $goName "By" ((cases .Columns.Names).Join "") -}}
	{{- if $.Table.PrimaryKeys.Names.ContainsAll .Columns.Names -}}
		{{- $FuncName = print "Get" $goName -}}
	{{- end -}}
// {{$FuncName}} retrieves a row from '{{$.Table.Schema.Name}}.{{$.Table.Name}}'.
//
// Generated from index '{{.Name}}'.
func (r Repo) {{ $FuncName }}(ctx context.Context, {{ $.Parameterize .Columns "%s %s" $pkgName }}) ({{ if not .IsUnique }}[]{{ end }}*{{$.PackageName}}.{{$goName}}, error) {
	query := querySelect{{$goName}} + ` + "`" + ` WHERE {{csv .Columns.Names.Sort }} = {{template "values" (len .Columns)}}
{{- if $hasSoftDeletes }} AND deleted_at is NULL{{ end}}` + "`" + `

{{- if .IsUnique }}
	q := r.db.QueryRow(ctx, query, {{ csv (.Columns.Names.Sort.Camel) }})
{{- else }}
	q, err := r.db.Query(ctx, query, {{ csv (.Columns.Names.Sort.Camel) }})
	if err != nil {
		return nil, fmt.Errorf("{{$goName}}.{{ $FuncName }}:%w", err)
	}
{{- end }}

{{- if .IsUnique }}
	return scanOne{{$goName}}(q)
{{- else }}
	return scan{{$goName}}(q)
{{- end }}
}

{{ end }}`
View Source
const FojiSlashSqlRepoDotGoDotTpl = `// Code generated by foji {{ version }}, template: {{ templateFile }}; DO NOT EDIT.

package pg

import (
	"context"
	"fmt"

{{- range .Imports }}
	"{{ . }}"
{{- end }}
)

{{- range .Queries }}
{{ $resultType := $.GetType .Result.TypeParam $.PackageName }}

{{- if .Result.GenerateType }}
// {{.Result.Type}} represents a result from '{{.Name}}'.
type {{.Result.Type}} struct {
{{- range .Result.Params.ByOrdinal }}
	{{ pascal .Name }} {{ $.GetType . $.PackageName }}  ` + "`" + `json:"{{ .Name }},omitempty"` + "`" + ` // postgres type: {{ .Type }} {{- if .Nullable }} NULLABLE {{ end }}
{{- end }}
}
{{- end }}

// {{.Name}} returns {{ $resultType }}
{{- if notEmpty .Comment }}
// {{.Comment}}
{{- end }}
func (r Repo) {{ .Name }}(ctx context.Context{{if gt (len .Params) 0}}, {{end}}{{ $.Parameterize .Params.ByOrdinal "%s %s" $.PackageName }}) ({{ if .IsType "query" }}[]{{ end }}*{{$resultType}}, error) {
	const query = ` + "`" + `{{ backQuote .SQL }}` + "`" + `

{{- if .IsType "query" }}
	q, err := r.db.Query(ctx, query{{if gt (len .Params) 0}}, {{ csv (.Params.ByQuery.Names.Camel)}}{{end}})
	if err != nil {
		return nil, fmt.Errorf("{{.Name}}.Query:%w", err)
	}

	var out []*{{ $resultType }}

	for q.Next() {
		row := {{ $resultType }}{}
		err := q.Scan({{ csv (.Result.Params.ByQuery.Names.Pascal.Sprintf "&row.%s")}})
		if err != nil {
			return nil, fmt.Errorf("{{.Name}}.Scan:%w", err)
		}

		out = append(out, &row)
	}

	return out, nil
{{- else }}
	q := r.db.QueryRow(ctx, query{{if gt (len .Params) 0}},{{end}} {{ csv (.Params.ByQuery.Names.Camel) }})
	{{/*        return scanOne{{$goName}}(q)*/}}
{{- end }}
}
{{- end }}
`
View Source
const InitDotYaml = `` /* 283-byte string literal not displayed */

Variables

View Source
var FojiDotYamlBytes = []byte(FojiDotYaml)
View Source
var FojiSlashDbListDotConsoleDotTplBytes = []byte(FojiSlashDbListDotConsoleDotTpl)
View Source
var FojiSlashEmbedDotGoDotTplBytes = []byte(FojiSlashEmbedDotGoDotTpl)
View Source
var FojiSlashEnumDotGoDotTplBytes = []byte(FojiSlashEnumDotGoDotTpl)
View Source
var FojiSlashFieldsDotGoDotTplBytes = []byte(FojiSlashFieldsDotGoDotTpl)
View Source
var FojiSlashOpenapiSlashAuthDotGoDotTplBytes = []byte(FojiSlashOpenapiSlashAuthDotGoDotTpl)
View Source
var FojiSlashOpenapiSlashDocsDotGoDotTplBytes = []byte(FojiSlashOpenapiSlashDocsDotGoDotTpl)
View Source
var FojiSlashOpenapiSlashErrorDotGoDotTplBytes = []byte(FojiSlashOpenapiSlashErrorDotGoDotTpl)
View Source
var FojiSlashOpenapiSlashHandlerDotGoDotTplBytes = []byte(FojiSlashOpenapiSlashHandlerDotGoDotTpl)
View Source
var FojiSlashOpenapiSlashMainDotGoDotTplBytes = []byte(FojiSlashOpenapiSlashMainDotGoDotTpl)
View Source
var FojiSlashOpenapiSlashModelDotGoDotTplBytes = []byte(FojiSlashOpenapiSlashModelDotGoDotTpl)
View Source
var FojiSlashOpenapiSlashServiceDotGoDotTplBytes = []byte(FojiSlashOpenapiSlashServiceDotGoDotTpl)
View Source
var FojiSlashOpenapiSlashStubDotYamlDotTplBytes = []byte(FojiSlashOpenapiSlashStubDotYamlDotTpl)
View Source
var FojiSlashPgxSlashDbDotGoDotTplBytes = []byte(FojiSlashPgxSlashDbDotGoDotTpl)
View Source
var FojiSlashPgxSlashModelDotGoDotTplBytes = []byte(FojiSlashPgxSlashModelDotGoDotTpl)
View Source
var FojiSlashPgxSlashTableDotGoDotTplBytes = []byte(FojiSlashPgxSlashTableDotGoDotTpl)
View Source
var FojiSlashSqlRepoDotGoDotTplBytes = []byte(FojiSlashSqlRepoDotGoDotTpl)
View Source
var InitDotYamlBytes = []byte(InitDotYaml)

Functions

func Get

func Get(filename string) ([]byte, error)

func GetString

func GetString(filename string) (string, error)

func List

func List() []string

Types

This section is empty.

Jump to

Keyboard shortcuts

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