repo
stringlengths 5
67
| sha
stringlengths 40
40
| path
stringlengths 4
234
| url
stringlengths 85
339
| language
stringclasses 6
values | split
stringclasses 3
values | doc
stringlengths 3
51.2k
| sign
stringlengths 5
8.01k
| problem
stringlengths 13
51.2k
| output
stringlengths 0
3.87M
|
---|---|---|---|---|---|---|---|---|---|
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/sqlite3/authgrouppermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/sqlite3/authgrouppermission.xo.go#L101-L128 | go | train | // Delete deletes the AuthGroupPermission from the database. | func (agp *AuthGroupPermission) Delete(db XODB) error | // Delete deletes the AuthGroupPermission from the database.
func (agp *AuthGroupPermission) Delete(db XODB) error | {
var err error
// if doesn't exist, bail
if !agp._exists {
return nil
}
// if deleted, bail
if agp._deleted {
return nil
}
// sql query
const sqlstr = `DELETE FROM auth_group_permissions WHERE id = ?`
// run query
XOLog(sqlstr, agp.ID)
_, err = db.Exec(sqlstr, agp.ID)
if err != nil {
return err
}
// set deleted
agp._deleted = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authuser.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authuser.xo.go#L42-L68 | go | train | // Insert inserts the AuthUser to the database. | func (au *AuthUser) Insert(db XODB) error | // Insert inserts the AuthUser to the database.
func (au *AuthUser) Insert(db XODB) error | {
var err error
// if already exist, bail
if au._exists {
return errors.New("insert failed: already exists")
}
// sql insert query, primary key provided by sequence
const sqlstr = `INSERT INTO public.auth_user (` +
`password, last_login, is_superuser, username, first_name, last_name, email, is_staff, is_active, date_joined` +
`) VALUES (` +
`$1, $2, $3, $4, $5, $6, $7, $8, $9, $10` +
`) RETURNING id`
// run query
XOLog(sqlstr, au.Password, au.LastLogin, au.IsSuperuser, au.Username, au.FirstName, au.LastName, au.Email, au.IsStaff, au.IsActive, au.DateJoined)
err = db.QueryRow(sqlstr, au.Password, au.LastLogin, au.IsSuperuser, au.Username, au.FirstName, au.LastName, au.Email, au.IsStaff, au.IsActive, au.DateJoined).Scan(&au.ID)
if err != nil {
return err
}
// set existence
au._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authuser.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authuser.xo.go#L200-L234 | go | train | // AuthUsersByUsername retrieves a row from 'public.auth_user' as a AuthUser.
//
// Generated from index 'auth_user_username_6821ab7c_like'. | func AuthUsersByUsername(db XODB, username string) ([]*AuthUser, error) | // AuthUsersByUsername retrieves a row from 'public.auth_user' as a AuthUser.
//
// Generated from index 'auth_user_username_6821ab7c_like'.
func AuthUsersByUsername(db XODB, username string) ([]*AuthUser, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, password, last_login, is_superuser, username, first_name, last_name, email, is_staff, is_active, date_joined ` +
`FROM public.auth_user ` +
`WHERE username = $1`
// run query
XOLog(sqlstr, username)
q, err := db.Query(sqlstr, username)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*AuthUser{}
for q.Next() {
au := AuthUser{
_exists: true,
}
// scan
err = q.Scan(&au.ID, &au.Password, &au.LastLogin, &au.IsSuperuser, &au.Username, &au.FirstName, &au.LastName, &au.Email, &au.IsStaff, &au.IsActive, &au.DateJoined)
if err != nil {
return nil, err
}
res = append(res, &au)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/loader.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/loader.go#L67-L73 | go | train | // NthParam satisifies Loader's NthParam. | func (tl TypeLoader) NthParam(i int) string | // NthParam satisifies Loader's NthParam.
func (tl TypeLoader) NthParam(i int) string | {
if tl.ParamN != nil {
return tl.ParamN(i)
}
return fmt.Sprintf("$%d", i+1)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/loader.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/loader.go#L85-L91 | go | train | // Escape escapes the provided identifier based on the EscType. | func (tl TypeLoader) Escape(typ EscType, s string) string | // Escape escapes the provided identifier based on the EscType.
func (tl TypeLoader) Escape(typ EscType, s string) string | {
if e, ok := tl.Esc[typ]; ok && e != nil {
return e(s)
}
return `"` + s + `"`
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/loader.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/loader.go#L94-L100 | go | train | // Relkind satisfies Loader's Relkind. | func (tl TypeLoader) Relkind(rt RelType) string | // Relkind satisfies Loader's Relkind.
func (tl TypeLoader) Relkind(rt RelType) string | {
if tl.ProcessRelkind != nil {
return tl.ProcessRelkind(rt)
}
return rt.String()
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/loader.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/loader.go#L103-L109 | go | train | // SchemaName returns the active schema name. | func (tl TypeLoader) SchemaName(args *ArgType) (string, error) | // SchemaName returns the active schema name.
func (tl TypeLoader) SchemaName(args *ArgType) (string, error) | {
if tl.Schema != nil {
return tl.Schema(args)
}
return "", nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/loader.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/loader.go#L112-L244 | go | train | // ParseQuery satisfies Loader's ParseQuery. | func (tl TypeLoader) ParseQuery(args *ArgType) error | // ParseQuery satisfies Loader's ParseQuery.
func (tl TypeLoader) ParseQuery(args *ArgType) error | {
var err error
// parse supplied query
queryStr, params := args.ParseQuery(tl.Mask(), true)
inspectStr, _ := args.ParseQuery("NULL", false)
// split up query and inspect based on lines
query := strings.Split(queryStr, "\n")
inspect := strings.Split(inspectStr, "\n")
// query comment placeholder
queryComments := make([]string, len(query)+1)
// trim whitespace if applicable
if args.QueryTrim {
for n, l := range query {
query[n] = strings.TrimSpace(l)
if n < len(query)-1 {
query[n] = query[n] + " "
}
}
for n, l := range inspect {
inspect[n] = strings.TrimSpace(l)
if n < len(inspect)-1 {
inspect[n] = inspect[n] + " "
}
}
}
// query strip
if args.QueryStrip && tl.QueryStrip != nil {
tl.QueryStrip(query, queryComments)
}
// create template for query type
typeTpl := &Type{
Name: args.QueryType,
RelType: Table,
Fields: []*Field{},
Table: &models.Table{
TableName: "[custom " + strings.ToLower(snaker.CamelToSnake(args.QueryType)) + "]",
},
Comment: args.QueryTypeComment,
}
if args.QueryFields == "" {
// if no query fields specified, then pass to inspector
colList, err := tl.QueryColumnList(args, inspect)
if err != nil {
return err
}
// process columns
for _, c := range colList {
f := &Field{
Name: snaker.SnakeToCamelIdentifier(c.ColumnName),
Col: c,
}
f.Len, f.NilType, f.Type = tl.ParseType(args, c.DataType, args.QueryAllowNulls && !c.NotNull)
typeTpl.Fields = append(typeTpl.Fields, f)
}
} else {
// extract fields from query fields
for _, qf := range strings.Split(args.QueryFields, ",") {
qf = strings.TrimSpace(qf)
colName := qf
colType := "string"
i := strings.Index(qf, " ")
if i != -1 {
colName = qf[:i]
colType = qf[i+1:]
}
typeTpl.Fields = append(typeTpl.Fields, &Field{
Name: colName,
Type: colType,
Col: &models.Column{
ColumnName: snaker.CamelToSnake(colName),
},
})
}
}
// generate query type template
err = args.ExecuteTemplate(QueryTypeTemplate, args.QueryType, "", typeTpl)
if err != nil {
return err
}
// build func name
funcName := args.QueryFunc
if funcName == "" {
// no func name specified, so generate based on type
if args.QueryOnlyOne {
funcName = args.QueryType
} else {
funcName = inflector.Pluralize(args.QueryType)
}
// affix any params
if len(params) == 0 {
funcName = "Get" + funcName
} else {
funcName = funcName + "By"
for _, p := range params {
funcName = funcName + strings.ToUpper(p.Name[:1]) + p.Name[1:]
}
}
}
// create func template
queryTpl := &Query{
Name: funcName,
Query: query,
QueryComments: queryComments,
QueryParams: params,
OnlyOne: args.QueryOnlyOne,
Interpolate: args.QueryInterpolate,
Type: typeTpl,
Comment: args.QueryFuncComment,
}
// generate template
err = args.ExecuteTemplate(QueryTemplate, args.QueryType, "", queryTpl)
if err != nil {
return err
}
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/loader.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/loader.go#L247-L292 | go | train | // LoadSchema loads schema definitions. | func (tl TypeLoader) LoadSchema(args *ArgType) error | // LoadSchema loads schema definitions.
func (tl TypeLoader) LoadSchema(args *ArgType) error | {
var err error
// load enums
_, err = tl.LoadEnums(args)
if err != nil {
return err
}
// load procs
_, err = tl.LoadProcs(args)
if err != nil {
return err
}
// load tables
tableMap, err := tl.LoadRelkind(args, Table)
if err != nil {
return err
}
// load views
viewMap, err := tl.LoadRelkind(args, View)
if err != nil {
return err
}
// merge views with the tableMap
for k, v := range viewMap {
tableMap[k] = v
}
// load foreign keys
_, err = tl.LoadForeignKeys(args, tableMap)
if err != nil {
return err
}
// load indexes
_, err = tl.LoadIndexes(args, tableMap)
if err != nil {
return err
}
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/loader.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/loader.go#L295-L338 | go | train | // LoadEnums loads schema enums. | func (tl TypeLoader) LoadEnums(args *ArgType) (map[string]*Enum, error) | // LoadEnums loads schema enums.
func (tl TypeLoader) LoadEnums(args *ArgType) (map[string]*Enum, error) | {
var err error
// not supplied, so bail
if tl.EnumList == nil {
return nil, nil
}
// load enums
enumList, err := tl.EnumList(args.DB, args.Schema)
if err != nil {
return nil, err
}
// process enums
enumMap := map[string]*Enum{}
for _, e := range enumList {
enumTpl := &Enum{
Name: SingularizeIdentifier(e.EnumName),
Schema: args.Schema,
Values: []*EnumValue{},
Enum: e,
ReverseConstNames: args.UseReversedEnumConstNames,
}
err = tl.LoadEnumValues(args, enumTpl)
if err != nil {
return nil, err
}
enumMap[enumTpl.Name] = enumTpl
args.KnownTypeMap[enumTpl.Name] = true
}
// generate enum templates
for _, e := range enumMap {
err = args.ExecuteTemplate(EnumTemplate, e.Name, "", e)
if err != nil {
return nil, err
}
}
return enumMap, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/loader.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/loader.go#L341-L368 | go | train | // LoadEnumValues loads schema enum values. | func (tl TypeLoader) LoadEnumValues(args *ArgType, enumTpl *Enum) error | // LoadEnumValues loads schema enum values.
func (tl TypeLoader) LoadEnumValues(args *ArgType, enumTpl *Enum) error | {
var err error
// load enum values
enumValues, err := tl.EnumValueList(args.DB, args.Schema, enumTpl.Enum.EnumName)
if err != nil {
return err
}
// process enum values
for _, ev := range enumValues {
// chop off redundant enum name if applicable
name := snaker.SnakeToCamelIdentifier(ev.EnumValue)
if strings.HasSuffix(strings.ToLower(name), strings.ToLower(enumTpl.Name)) {
n := name[:len(name)-len(enumTpl.Name)]
if len(n) > 0 {
name = n
}
}
enumTpl.Values = append(enumTpl.Values, &EnumValue{
Name: name,
Val: ev,
})
}
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/loader.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/loader.go#L371-L425 | go | train | // LoadProcs loads schema stored procedures definitions. | func (tl TypeLoader) LoadProcs(args *ArgType) (map[string]*Proc, error) | // LoadProcs loads schema stored procedures definitions.
func (tl TypeLoader) LoadProcs(args *ArgType) (map[string]*Proc, error) | {
var err error
// not supplied, so bail
if tl.ProcList == nil {
return nil, nil
}
// load procs
procList, err := tl.ProcList(args.DB, args.Schema)
if err != nil {
return nil, err
}
// process procs
procMap := map[string]*Proc{}
for _, p := range procList {
// fix the name if it starts with one or more underscores
name := p.ProcName
for strings.HasPrefix(name, "_") {
name = name[1:]
}
// create template
procTpl := &Proc{
Name: snaker.SnakeToCamelIdentifier(name),
Schema: args.Schema,
Params: []*Field{},
Return: &Field{},
Proc: p,
}
// parse return type into template
// TODO: fix this so that nullable types can be returned
_, procTpl.Return.NilType, procTpl.Return.Type = tl.ParseType(args, p.ReturnType, false)
// load proc parameters
err = tl.LoadProcParams(args, procTpl)
if err != nil {
return nil, err
}
procMap[p.ProcName] = procTpl
}
// generate proc templates
for _, p := range procMap {
err = args.ExecuteTemplate(ProcTemplate, "sp_"+p.Name, "", p)
if err != nil {
return nil, err
}
}
return procMap, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/loader.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/loader.go#L428-L457 | go | train | // LoadProcParams loads schema stored procedure parameters. | func (tl TypeLoader) LoadProcParams(args *ArgType, procTpl *Proc) error | // LoadProcParams loads schema stored procedure parameters.
func (tl TypeLoader) LoadProcParams(args *ArgType, procTpl *Proc) error | {
var err error
// load proc params
paramList, err := tl.ProcParamList(args.DB, args.Schema, procTpl.Proc.ProcName)
if err != nil {
return err
}
// process params
for i, p := range paramList {
// TODO: some databases support named parameters in procs (MySQL)
paramTpl := &Field{
Name: fmt.Sprintf("v%d", i),
}
// TODO: fix this so that nullable types can be used as parameters
_, _, paramTpl.Type = tl.ParseType(args, strings.TrimSpace(p.ParamType), false)
// add to proc params
if procTpl.ProcParams != "" {
procTpl.ProcParams = procTpl.ProcParams + ", "
}
procTpl.ProcParams = procTpl.ProcParams + p.ParamType
procTpl.Params = append(procTpl.Params, paramTpl)
}
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/loader.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/loader.go#L460-L499 | go | train | // LoadRelkind loads a schema table/view definition. | func (tl TypeLoader) LoadRelkind(args *ArgType, relType RelType) (map[string]*Type, error) | // LoadRelkind loads a schema table/view definition.
func (tl TypeLoader) LoadRelkind(args *ArgType, relType RelType) (map[string]*Type, error) | {
var err error
// load tables
tableList, err := tl.TableList(args.DB, args.Schema, tl.Relkind(relType))
if err != nil {
return nil, err
}
// tables
tableMap := make(map[string]*Type)
for _, ti := range tableList {
// create template
typeTpl := &Type{
Name: SingularizeIdentifier(ti.TableName),
Schema: args.Schema,
RelType: relType,
Fields: []*Field{},
Table: ti,
}
// process columns
err = tl.LoadColumns(args, typeTpl)
if err != nil {
return nil, err
}
tableMap[ti.TableName] = typeTpl
}
// generate table templates
for _, t := range tableMap {
err = args.ExecuteTemplate(TypeTemplate, t.Name, "", t)
if err != nil {
return nil, err
}
}
return tableMap, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/loader.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/loader.go#L502-L550 | go | train | // LoadColumns loads schema table/view columns. | func (tl TypeLoader) LoadColumns(args *ArgType, typeTpl *Type) error | // LoadColumns loads schema table/view columns.
func (tl TypeLoader) LoadColumns(args *ArgType, typeTpl *Type) error | {
var err error
// load columns
columnList, err := tl.ColumnList(args.DB, args.Schema, typeTpl.Table.TableName)
if err != nil {
return err
}
// process columns
for _, c := range columnList {
ignore := false
for _, ignoreField := range args.IgnoreFields {
if ignoreField == c.ColumnName {
// Skip adding this field if user has specified they are not
// interested.
//
// This could be useful for fields which are managed by the
// database (e.g. automatically updated timestamps) instead of
// via Go code.
ignore = true
}
}
if ignore {
continue
}
// set col info
f := &Field{
Name: snaker.SnakeToCamelIdentifier(c.ColumnName),
Col: c,
}
f.Len, f.NilType, f.Type = tl.ParseType(args, c.DataType, !c.NotNull)
// set primary key
if c.IsPrimaryKey {
typeTpl.PrimaryKeyFields = append(typeTpl.PrimaryKeyFields, f)
// This is retained for backward compatibility in the templates.
typeTpl.PrimaryKey = f
}
// append col to template fields
typeTpl.Fields = append(typeTpl.Fields, f)
}
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/loader.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/loader.go#L553-L579 | go | train | // LoadForeignKeys loads foreign keys. | func (tl TypeLoader) LoadForeignKeys(args *ArgType, tableMap map[string]*Type) (map[string]*ForeignKey, error) | // LoadForeignKeys loads foreign keys.
func (tl TypeLoader) LoadForeignKeys(args *ArgType, tableMap map[string]*Type) (map[string]*ForeignKey, error) | {
var err error
fkMap := map[string]*ForeignKey{}
for _, t := range tableMap {
// load keys per table
err = tl.LoadTableForeignKeys(args, tableMap, t, fkMap)
if err != nil {
return nil, err
}
}
// determine foreign key names
for _, fk := range fkMap {
fk.Name = args.ForeignKeyName(fkMap, fk)
}
// generate templates
for _, fk := range fkMap {
err = args.ExecuteTemplate(ForeignKeyTemplate, fk.Type.Name, fk.ForeignKey.ForeignKeyName, fk)
if err != nil {
return nil, err
}
}
return fkMap, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/loader.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/loader.go#L582-L650 | go | train | // LoadTableForeignKeys loads schema foreign key definitions per table. | func (tl TypeLoader) LoadTableForeignKeys(args *ArgType, tableMap map[string]*Type, typeTpl *Type, fkMap map[string]*ForeignKey) error | // LoadTableForeignKeys loads schema foreign key definitions per table.
func (tl TypeLoader) LoadTableForeignKeys(args *ArgType, tableMap map[string]*Type, typeTpl *Type, fkMap map[string]*ForeignKey) error | {
var err error
// load foreign keys
foreignKeyList, err := tl.ForeignKeyList(args.DB, args.Schema, typeTpl.Table.TableName)
if err != nil {
return err
}
// loop over foreign keys for table
for _, fk := range foreignKeyList {
var refTpl *Type
var col, refCol *Field
colLoop:
// find column
for _, f := range typeTpl.Fields {
if f.Col.ColumnName == fk.ColumnName {
col = f
break colLoop
}
}
refTplLoop:
// find ref table
for _, t := range tableMap {
if t.Table.TableName == fk.RefTableName {
refTpl = t
break refTplLoop
}
}
refColLoop:
// find ref column
for _, f := range refTpl.Fields {
if f.Col.ColumnName == fk.RefColumnName {
refCol = f
break refColLoop
}
}
// no ref col, but have ref tpl, so use primary key
if refTpl != nil && refCol == nil {
refCol = refTpl.PrimaryKey
}
// check everything was found
if col == nil || refTpl == nil || refCol == nil {
return errors.New("could not find col, refTpl, or refCol")
}
// foreign key name
if fk.ForeignKeyName == "" {
fk.ForeignKeyName = typeTpl.Table.TableName + "_" + col.Col.ColumnName + "_fkey"
}
// create foreign key template
fkMap[fk.ForeignKeyName] = &ForeignKey{
Schema: args.Schema,
Type: typeTpl,
Field: col,
RefType: refTpl,
RefField: refCol,
ForeignKey: fk,
}
}
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/loader.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/loader.go#L653-L674 | go | train | // LoadIndexes loads schema index definitions. | func (tl TypeLoader) LoadIndexes(args *ArgType, tableMap map[string]*Type) (map[string]*Index, error) | // LoadIndexes loads schema index definitions.
func (tl TypeLoader) LoadIndexes(args *ArgType, tableMap map[string]*Type) (map[string]*Index, error) | {
var err error
ixMap := map[string]*Index{}
for _, t := range tableMap {
// load table indexes
err = tl.LoadTableIndexes(args, t, ixMap)
if err != nil {
return nil, err
}
}
// generate templates
for _, ix := range ixMap {
err = args.ExecuteTemplate(IndexTemplate, ix.Type.Name, ix.Index.IndexName, ix)
if err != nil {
return nil, err
}
}
return ixMap, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/loader.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/loader.go#L677-L742 | go | train | // LoadTableIndexes loads schema index definitions per table. | func (tl TypeLoader) LoadTableIndexes(args *ArgType, typeTpl *Type, ixMap map[string]*Index) error | // LoadTableIndexes loads schema index definitions per table.
func (tl TypeLoader) LoadTableIndexes(args *ArgType, typeTpl *Type, ixMap map[string]*Index) error | {
var err error
var priIxLoaded bool
// load indexes
indexList, err := tl.IndexList(args.DB, args.Schema, typeTpl.Table.TableName)
if err != nil {
return err
}
// process indexes
for _, ix := range indexList {
// save whether or not the primary key index was processed
priIxLoaded = priIxLoaded || ix.IsPrimary || (ix.Origin == "pk")
// create index template
ixTpl := &Index{
Schema: args.Schema,
Type: typeTpl,
Fields: []*Field{},
Index: ix,
}
// load index columns
err = tl.LoadIndexColumns(args, ixTpl)
if err != nil {
return err
}
// build func name
args.BuildIndexFuncName(ixTpl)
ixMap[typeTpl.Table.TableName+"_"+ix.IndexName] = ixTpl
}
// search for primary key if it was skipped being set in the type
pk := typeTpl.PrimaryKey
if pk == nil {
for _, f := range typeTpl.Fields {
if f.Col.IsPrimaryKey {
pk = f
break
}
}
}
// if no primary key index loaded, but a primary key column was defined in
// the type, then create the definition here. this is needed for sqlite, as
// sqlite doesn't define primary keys in its index list
if args.LoaderType != "ora" && !priIxLoaded && pk != nil {
ixName := typeTpl.Table.TableName + "_" + pk.Col.ColumnName + "_pkey"
ixMap[ixName] = &Index{
FuncName: typeTpl.Name + "By" + pk.Name,
Schema: args.Schema,
Type: typeTpl,
Fields: []*Field{pk},
Index: &models.Index{
IndexName: ixName,
IsUnique: true,
IsPrimary: true,
},
}
}
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/loader.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/loader.go#L745-L775 | go | train | // LoadIndexColumns loads the index column information. | func (tl TypeLoader) LoadIndexColumns(args *ArgType, ixTpl *Index) error | // LoadIndexColumns loads the index column information.
func (tl TypeLoader) LoadIndexColumns(args *ArgType, ixTpl *Index) error | {
var err error
// load index columns
indexCols, err := tl.IndexColumnList(args.DB, args.Schema, ixTpl.Type.Table.TableName, ixTpl.Index.IndexName)
if err != nil {
return err
}
// process index columns
for _, ic := range indexCols {
var field *Field
fieldLoop:
// find field
for _, f := range ixTpl.Type.Fields {
if f.Col.ColumnName == ic.ColumnName {
field = f
break fieldLoop
}
}
if field == nil {
continue
}
ixTpl.Fields = append(ixTpl.Fields, field)
}
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/pgcatalog/ischema/sp_pgexpandarray.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/pgcatalog/ischema/sp_pgexpandarray.xo.go#L9-L24 | go | train | // Code generated by xo. DO NOT EDIT.
// PgExpandarray calls the stored procedure 'information_schema._pg_expandarray(anyarray) SETOF record' on db. | func PgExpandarray(db XODB, v0 pgtypes.Anyarray) ([]pgtypes.Record, error) | // Code generated by xo. DO NOT EDIT.
// PgExpandarray calls the stored procedure 'information_schema._pg_expandarray(anyarray) SETOF record' on db.
func PgExpandarray(db XODB, v0 pgtypes.Anyarray) ([]pgtypes.Record, error) | {
var err error
// sql query
const sqlstr = `SELECT information_schema._pg_expandarray($1)`
// run query
var ret []pgtypes.Record
XOLog(sqlstr, v0)
err = db.QueryRow(sqlstr, v0).Scan(&ret)
if err != nil {
return nil, err
}
return ret, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authpermission.xo.go#L32-L58 | go | train | // Insert inserts the AuthPermission to the database. | func (ap *AuthPermission) Insert(db XODB) error | // Insert inserts the AuthPermission to the database.
func (ap *AuthPermission) Insert(db XODB) error | {
var err error
// if already exist, bail
if ap._exists {
return errors.New("insert failed: already exists")
}
// sql insert query, primary key provided by sequence
const sqlstr = `INSERT INTO public.auth_permission (` +
`name, content_type_id, codename` +
`) VALUES (` +
`$1, $2, $3` +
`) RETURNING id`
// run query
XOLog(sqlstr, ap.Name, ap.ContentTypeID, ap.Codename)
err = db.QueryRow(sqlstr, ap.Name, ap.ContentTypeID, ap.Codename).Scan(&ap.ID)
if err != nil {
return err
}
// set existence
ap._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authpermission.xo.go#L99-L129 | go | train | // Upsert performs an upsert for AuthPermission.
//
// NOTE: PostgreSQL 9.5+ only | func (ap *AuthPermission) Upsert(db XODB) error | // Upsert performs an upsert for AuthPermission.
//
// NOTE: PostgreSQL 9.5+ only
func (ap *AuthPermission) Upsert(db XODB) error | {
var err error
// if already exist, bail
if ap._exists {
return errors.New("insert failed: already exists")
}
// sql query
const sqlstr = `INSERT INTO public.auth_permission (` +
`id, name, content_type_id, codename` +
`) VALUES (` +
`$1, $2, $3, $4` +
`) ON CONFLICT (id) DO UPDATE SET (` +
`id, name, content_type_id, codename` +
`) = (` +
`EXCLUDED.id, EXCLUDED.name, EXCLUDED.content_type_id, EXCLUDED.codename` +
`)`
// run query
XOLog(sqlstr, ap.ID, ap.Name, ap.ContentTypeID, ap.Codename)
_, err = db.Exec(sqlstr, ap.ID, ap.Name, ap.ContentTypeID, ap.Codename)
if err != nil {
return err
}
// set existence
ap._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authpermission.xo.go#L210-L231 | go | train | // AuthPermissionByContentTypeIDCodename retrieves a row from 'public.auth_permission' as a AuthPermission.
//
// Generated from index 'auth_permission_content_type_id_01ab375a_uniq'. | func AuthPermissionByContentTypeIDCodename(db XODB, contentTypeID int, codename string) (*AuthPermission, error) | // AuthPermissionByContentTypeIDCodename retrieves a row from 'public.auth_permission' as a AuthPermission.
//
// Generated from index 'auth_permission_content_type_id_01ab375a_uniq'.
func AuthPermissionByContentTypeIDCodename(db XODB, contentTypeID int, codename string) (*AuthPermission, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, name, content_type_id, codename ` +
`FROM public.auth_permission ` +
`WHERE content_type_id = $1 AND codename = $2`
// run query
XOLog(sqlstr, contentTypeID, codename)
ap := AuthPermission{
_exists: true,
}
err = db.QueryRow(sqlstr, contentTypeID, codename).Scan(&ap.ID, &ap.Name, &ap.ContentTypeID, &ap.Codename)
if err != nil {
return nil, err
}
return &ap, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authpermission.xo.go#L236-L257 | go | train | // AuthPermissionByID retrieves a row from 'public.auth_permission' as a AuthPermission.
//
// Generated from index 'auth_permission_pkey'. | func AuthPermissionByID(db XODB, id int) (*AuthPermission, error) | // AuthPermissionByID retrieves a row from 'public.auth_permission' as a AuthPermission.
//
// Generated from index 'auth_permission_pkey'.
func AuthPermissionByID(db XODB, id int) (*AuthPermission, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, name, content_type_id, codename ` +
`FROM public.auth_permission ` +
`WHERE id = $1`
// run query
XOLog(sqlstr, id)
ap := AuthPermission{
_exists: true,
}
err = db.QueryRow(sqlstr, id).Scan(&ap.ID, &ap.Name, &ap.ContentTypeID, &ap.Codename)
if err != nil {
return nil, err
}
return &ap, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | models/sequence.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/models/sequence.xo.go#L12-L47 | go | train | // PgSequences runs a custom query, returning results as Sequence. | func PgSequences(db XODB, schema string) ([]*Sequence, error) | // PgSequences runs a custom query, returning results as Sequence.
func PgSequences(db XODB, schema string) ([]*Sequence, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`t.relname ` + // ::varchar AS table_name
`FROM pg_class s ` +
`JOIN pg_depend d ON d.objid = s.oid ` +
`JOIN pg_class t ON d.objid = s.oid AND d.refobjid = t.oid ` +
`JOIN pg_namespace n ON n.oid = s.relnamespace ` +
`WHERE n.nspname = $1 AND s.relkind = 'S'`
// run query
XOLog(sqlstr, schema)
q, err := db.Query(sqlstr, schema)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*Sequence{}
for q.Next() {
s := Sequence{}
// scan
err = q.Scan(&s.TableName)
if err != nil {
return nil, err
}
res = append(res, &s)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | models/sqcolumn.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/models/sqcolumn.xo.go#L21-L50 | go | train | // SqTableColumns runs a custom query, returning results as SqColumn. | func SqTableColumns(db XODB, table string) ([]*SqColumn, error) | // SqTableColumns runs a custom query, returning results as SqColumn.
func SqTableColumns(db XODB, table string) ([]*SqColumn, error) | {
var err error
// sql query
var sqlstr = `PRAGMA table_info(` + table + `)`
// run query
XOLog(sqlstr)
q, err := db.Query(sqlstr, table)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*SqColumn{}
for q.Next() {
sc := SqColumn{}
// scan
err = q.Scan(&sc.FieldOrdinal, &sc.ColumnName, &sc.DataType, &sc.NotNull, &sc.DefaultValue, &sc.PkColIndex)
if err != nil {
return nil, err
}
res = append(res, &sc)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/authuseruserpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/authuseruserpermission.xo.go#L90-L96 | go | train | // Save saves the AuthUserUserPermission to the database. | func (auup *AuthUserUserPermission) Save(db XODB) error | // Save saves the AuthUserUserPermission to the database.
func (auup *AuthUserUserPermission) Save(db XODB) error | {
if auup.Exists() {
return auup.Update(db)
}
return auup.Insert(db)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/authuseruserpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/authuseruserpermission.xo.go#L131-L133 | go | train | // AuthPermission returns the AuthPermission associated with the AuthUserUserPermission's PermissionID (permission_id).
//
// Generated from foreign key 'd86aa2ae91c20ae0c7ed11fa07e6da'. | func (auup *AuthUserUserPermission) AuthPermission(db XODB) (*AuthPermission, error) | // AuthPermission returns the AuthPermission associated with the AuthUserUserPermission's PermissionID (permission_id).
//
// Generated from foreign key 'd86aa2ae91c20ae0c7ed11fa07e6da'.
func (auup *AuthUserUserPermission) AuthPermission(db XODB) (*AuthPermission, error) | {
return AuthPermissionByID(db, auup.PermissionID)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/authuseruserpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/authuseruserpermission.xo.go#L138-L140 | go | train | // AuthUser returns the AuthUser associated with the AuthUserUserPermission's UserID (user_id).
//
// Generated from foreign key 'd9da0966de759042d839a70a2bd885'. | func (auup *AuthUserUserPermission) AuthUser(db XODB) (*AuthUser, error) | // AuthUser returns the AuthUser associated with the AuthUserUserPermission's UserID (user_id).
//
// Generated from foreign key 'd9da0966de759042d839a70a2bd885'.
func (auup *AuthUserUserPermission) AuthUser(db XODB) (*AuthUser, error) | {
return AuthUserByID(db, auup.UserID)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/authuseruserpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/authuseruserpermission.xo.go#L145-L166 | go | train | // AuthUserUserPermissionByUserIDPermissionID retrieves a row from 'django.auth_user_user_permissions' as a AuthUserUserPermission.
//
// Generated from index 'auth_use_user_id_14a6b632_uniq'. | func AuthUserUserPermissionByUserIDPermissionID(db XODB, userID float64, permissionID float64) (*AuthUserUserPermission, error) | // AuthUserUserPermissionByUserIDPermissionID retrieves a row from 'django.auth_user_user_permissions' as a AuthUserUserPermission.
//
// Generated from index 'auth_use_user_id_14a6b632_uniq'.
func AuthUserUserPermissionByUserIDPermissionID(db XODB, userID float64, permissionID float64) (*AuthUserUserPermission, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, user_id, permission_id ` +
`FROM django.auth_user_user_permissions ` +
`WHERE user_id = :1 AND permission_id = :2`
// run query
XOLog(sqlstr, userID, permissionID)
auup := AuthUserUserPermission{
_exists: true,
}
err = db.QueryRow(sqlstr, userID, permissionID).Scan(&auup.ID, &auup.UserID, &auup.PermissionID)
if err != nil {
return nil, err
}
return &auup, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/authuseruserpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/authuseruserpermission.xo.go#L171-L205 | go | train | // AuthUserUserPermissionsByUserID retrieves a row from 'django.auth_user_user_permissions' as a AuthUserUserPermission.
//
// Generated from index 'auth_user_user_permissions1cca'. | func AuthUserUserPermissionsByUserID(db XODB, userID float64) ([]*AuthUserUserPermission, error) | // AuthUserUserPermissionsByUserID retrieves a row from 'django.auth_user_user_permissions' as a AuthUserUserPermission.
//
// Generated from index 'auth_user_user_permissions1cca'.
func AuthUserUserPermissionsByUserID(db XODB, userID float64) ([]*AuthUserUserPermission, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, user_id, permission_id ` +
`FROM django.auth_user_user_permissions ` +
`WHERE user_id = :1`
// run query
XOLog(sqlstr, userID)
q, err := db.Query(sqlstr, userID)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*AuthUserUserPermission{}
for q.Next() {
auup := AuthUserUserPermission{
_exists: true,
}
// scan
err = q.Scan(&auup.ID, &auup.UserID, &auup.PermissionID)
if err != nil {
return nil, err
}
res = append(res, &auup)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/sqlite3/djangomigration.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/sqlite3/djangomigration.xo.go#L94-L100 | go | train | // Save saves the DjangoMigration to the database. | func (dm *DjangoMigration) Save(db XODB) error | // Save saves the DjangoMigration to the database.
func (dm *DjangoMigration) Save(db XODB) error | {
if dm.Exists() {
return dm.Update(db)
}
return dm.Insert(db)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/mysql.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/mysql.go#L35-L51 | go | train | // MySchema retrieves the name of the current schema. | func MySchema(args *internal.ArgType) (string, error) | // MySchema retrieves the name of the current schema.
func MySchema(args *internal.ArgType) (string, error) | {
var err error
// sql query
const sqlstr = `SELECT SCHEMA()`
var schema string
// run query
models.XOLog(sqlstr)
err = args.DB.QueryRow(sqlstr).Scan(&schema)
if err != nil {
return "", err
}
return schema, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/mysql.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/mysql.go#L69-L218 | go | train | // MyParseType parse a mysql type into a Go type based on the column
// definition. | func MyParseType(args *internal.ArgType, dt string, nullable bool) (int, string, string) | // MyParseType parse a mysql type into a Go type based on the column
// definition.
func MyParseType(args *internal.ArgType, dt string, nullable bool) (int, string, string) | {
precision := 0
nilVal := "nil"
unsigned := false
// extract unsigned
if strings.HasSuffix(dt, " unsigned") {
unsigned = true
dt = dt[:len(dt)-len(" unsigned")]
}
// extract precision
dt, precision, _ = args.ParsePrecision(dt)
var typ string
switchDT:
switch dt {
case "bit":
nilVal = "0"
if precision == 1 {
nilVal = "false"
typ = "bool"
if nullable {
nilVal = "sql.NullBool{}"
typ = "sql.NullBool"
}
break switchDT
} else if precision <= 8 {
typ = "uint8"
} else if precision <= 16 {
typ = "uint16"
} else if precision <= 32 {
typ = "uint32"
} else {
typ = "uint64"
}
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "bool", "boolean":
nilVal = "false"
typ = "bool"
if nullable {
nilVal = "sql.NullBool{}"
typ = "sql.NullBool"
}
case "char", "varchar", "tinytext", "text", "mediumtext", "longtext":
nilVal = `""`
typ = "string"
if nullable {
nilVal = "sql.NullString{}"
typ = "sql.NullString"
}
case "tinyint":
//people using tinyint(1) really want a bool
if precision == 1 {
nilVal = "false"
typ = "bool"
if nullable {
nilVal = "sql.NullBool{}"
typ = "sql.NullBool"
}
break
}
nilVal = "0"
typ = "int8"
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "smallint":
nilVal = "0"
typ = "int16"
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "mediumint", "int", "integer":
nilVal = "0"
typ = args.Int32Type
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "bigint":
nilVal = "0"
typ = "int64"
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "float":
nilVal = "0.0"
typ = "float32"
if nullable {
nilVal = "sql.NullFloat64{}"
typ = "sql.NullFloat64"
}
case "decimal", "double":
nilVal = "0.0"
typ = "float64"
if nullable {
nilVal = "sql.NullFloat64{}"
typ = "sql.NullFloat64"
}
case "binary", "varbinary", "tinyblob", "blob", "mediumblob", "longblob":
typ = "[]byte"
case "timestamp", "datetime", "date":
nilVal = "time.Time{}"
typ = "time.Time"
if nullable {
nilVal = "mysql.NullTime{}"
typ = "mysql.NullTime"
}
case "time":
// time is not supported by the MySQL driver. Can parse the string to time.Time in the user code.
typ = "string"
default:
if strings.HasPrefix(dt, args.Schema+".") {
// in the same schema, so chop off
typ = snaker.SnakeToCamelIdentifier(dt[len(args.Schema)+1:])
nilVal = typ + "(0)"
} else {
typ = snaker.SnakeToCamelIdentifier(dt)
nilVal = typ + "{}"
}
}
// add 'u' as prefix to type if its unsigned
// FIXME: this needs to be tested properly...
if unsigned && internal.IntRE.MatchString(typ) {
typ = "u" + typ
}
return precision, nilVal, typ
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/mysql.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/mysql.go#L221-L240 | go | train | // MyEnumValues loads the enum values. | func MyEnumValues(db models.XODB, schema string, enum string) ([]*models.EnumValue, error) | // MyEnumValues loads the enum values.
func MyEnumValues(db models.XODB, schema string, enum string) ([]*models.EnumValue, error) | {
var err error
// load enum vals
res, err := models.MyEnumValues(db, schema, enum)
if err != nil {
return nil, err
}
// process enum vals
enumVals := []*models.EnumValue{}
for i, ev := range strings.Split(res.EnumValues[1:len(res.EnumValues)-1], "','") {
enumVals = append(enumVals, &models.EnumValue{
EnumValue: ev,
ConstValue: i + 1,
})
}
return enumVals, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/mysql.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/mysql.go#L244-L278 | go | train | // MyTables returns the MySql tables with the manual PK information added.
// ManualPk is true when the table's primary key is not autoincrement. | func MyTables(db models.XODB, schema string, relkind string) ([]*models.Table, error) | // MyTables returns the MySql tables with the manual PK information added.
// ManualPk is true when the table's primary key is not autoincrement.
func MyTables(db models.XODB, schema string, relkind string) ([]*models.Table, error) | {
var err error
// get the tables
rows, err := models.MyTables(db, schema, relkind)
if err != nil {
return nil, err
}
// get the tables that have Autoincrementing included
autoIncrements, err := models.MyAutoIncrements(db, schema)
if err != nil {
// Set it to an empty set on error.
autoIncrements = []*models.MyAutoIncrement{}
}
// Add information about manual FK.
var tables []*models.Table
for _, row := range rows {
manualPk := true
// Look for a match in the table name where it contains the autoincrement
for _, autoInc := range autoIncrements {
if autoInc.TableName == row.TableName {
manualPk = false
}
}
tables = append(tables, &models.Table{
TableName: row.TableName,
Type: row.Type,
ManualPk: manualPk,
})
}
return tables, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/mysql.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/mysql.go#L281-L303 | go | train | // MyQueryColumns parses the query and generates a type for it. | func MyQueryColumns(args *internal.ArgType, inspect []string) ([]*models.Column, error) | // MyQueryColumns parses the query and generates a type for it.
func MyQueryColumns(args *internal.ArgType, inspect []string) ([]*models.Column, error) | {
var err error
// create temporary view xoid
xoid := "_xo_" + internal.GenRandomID()
viewq := `CREATE VIEW ` + xoid + ` AS (` + strings.Join(inspect, "\n") + `)`
models.XOLog(viewq)
_, err = args.DB.Exec(viewq)
if err != nil {
return nil, err
}
// load columns
cols, err := models.MyTableColumns(args.DB, args.Schema, xoid)
// drop inspect view
dropq := `DROP VIEW ` + xoid
models.XOLog(dropq)
_, _ = args.DB.Exec(dropq)
// load column information
return cols, err
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/argtype.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/argtype.go#L156-L210 | go | train | // NewDefaultArgs returns the default arguments. | func NewDefaultArgs() *ArgType | // NewDefaultArgs returns the default arguments.
func NewDefaultArgs() *ArgType | {
fkMode := FkModeSmart
return &ArgType{
Suffix: ".xo.go",
Int32Type: "int",
Uint32Type: "uint",
ForeignKeyMode: &fkMode,
QueryParamDelimiter: "%%",
NameConflictSuffix: "Val",
// KnownTypeMap is the collection of known Go types.
KnownTypeMap: map[string]bool{
"bool": true,
"string": true,
"byte": true,
"rune": true,
"int": true,
"int16": true,
"int32": true,
"int64": true,
"uint": true,
"uint8": true,
"uint16": true,
"uint32": true,
"uint64": true,
"float32": true,
"float64": true,
"Slice": true,
"StringSlice": true,
},
// ShortNameTypeMap is the collection of Go style short names for types, mainly
// used for use with declaring a func receiver on a type.
ShortNameTypeMap: map[string]string{
"bool": "b",
"string": "s",
"byte": "b",
"rune": "r",
"int": "i",
"int16": "i",
"int32": "i",
"int64": "i",
"uint": "u",
"uint8": "u",
"uint16": "u",
"uint32": "u",
"uint64": "u",
"float32": "f",
"float64": "f",
"Slice": "s",
"StringSlice": "ss",
},
}
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | models/msidentity.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/models/msidentity.xo.go#L12-L44 | go | train | // MsIdentities runs a custom query, returning results as MsIdentity. | func MsIdentities(db XODB, schema string) ([]*MsIdentity, error) | // MsIdentities runs a custom query, returning results as MsIdentity.
func MsIdentities(db XODB, schema string) ([]*MsIdentity, error) | {
var err error
// sql query
const sqlstr = `SELECT o.name as table_name ` +
`FROM sys.objects o inner join sys.columns c on o.object_id = c.object_id ` +
`WHERE c.is_identity = 1 ` +
`AND schema_name(o.schema_id) = $1 AND o.type = 'U'`
// run query
XOLog(sqlstr, schema)
q, err := db.Query(sqlstr, schema)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*MsIdentity{}
for q.Next() {
mi := MsIdentity{}
// scan
err = q.Scan(&mi.TableName)
if err != nil {
return nil, err
}
res = append(res, &mi)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/postgres.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/postgres.go#L39-L50 | go | train | // PgRelkind returns the postgres string representation for RelType. | func PgRelkind(relType internal.RelType) string | // PgRelkind returns the postgres string representation for RelType.
func PgRelkind(relType internal.RelType) string | {
var s string
switch relType {
case internal.Table:
s = "r"
case internal.View:
s = "v"
default:
panic("unsupported RelType")
}
return s
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/postgres.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/postgres.go#L54-L211 | go | train | // PgParseType parse a postgres type into a Go type based on the column
// definition. | func PgParseType(args *internal.ArgType, dt string, nullable bool) (int, string, string) | // PgParseType parse a postgres type into a Go type based on the column
// definition.
func PgParseType(args *internal.ArgType, dt string, nullable bool) (int, string, string) | {
precision := 0
nilVal := "nil"
asSlice := false
// handle SETOF
if strings.HasPrefix(dt, "SETOF ") {
_, _, t := PgParseType(args, dt[len("SETOF "):], false)
return 0, "nil", "[]" + t
}
// determine if it's a slice
if strings.HasSuffix(dt, "[]") {
dt = dt[:len(dt)-2]
asSlice = true
}
// extract precision
dt, precision, _ = args.ParsePrecision(dt)
var typ string
switch dt {
case "boolean":
nilVal = "false"
typ = "bool"
if nullable {
nilVal = "sql.NullBool{}"
typ = "sql.NullBool"
}
case "character", "character varying", "text", "money", "inet":
nilVal = `""`
typ = "string"
if nullable {
nilVal = "sql.NullString{}"
typ = "sql.NullString"
}
case "smallint":
nilVal = "0"
typ = "int16"
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "integer":
nilVal = "0"
typ = args.Int32Type
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "bigint":
nilVal = "0"
typ = "int64"
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "smallserial":
nilVal = "0"
typ = "uint16"
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "serial":
nilVal = "0"
typ = args.Uint32Type
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "bigserial":
nilVal = "0"
typ = "uint64"
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "real":
nilVal = "0.0"
typ = "float32"
if nullable {
nilVal = "sql.NullFloat64{}"
typ = "sql.NullFloat64"
}
case "numeric", "double precision":
nilVal = "0.0"
typ = "float64"
if nullable {
nilVal = "sql.NullFloat64{}"
typ = "sql.NullFloat64"
}
case "bytea":
asSlice = true
typ = "byte"
case "date", "timestamp with time zone", "time with time zone", "time without time zone", "timestamp without time zone":
nilVal = "time.Time{}"
typ = "time.Time"
if nullable {
nilVal = "pq.NullTime{}"
typ = "pq.NullTime"
}
case "interval":
typ = "*time.Duration"
case `"char"`, "bit":
// FIXME: this needs to actually be tested ...
// i think this should be 'rune' but I don't think database/sql
// supports 'rune' as a type?
//
// this is mainly here because postgres's pg_catalog.* meta tables have
// this as a type.
//typ = "rune"
nilVal = `uint8(0)`
typ = "uint8"
case `"any"`, "bit varying":
asSlice = true
typ = "byte"
case "hstore":
typ = "hstore.Hstore"
case "uuid":
nilVal = "uuid.New()"
typ = "uuid.UUID"
default:
if strings.HasPrefix(dt, args.Schema+".") {
// in the same schema, so chop off
typ = snaker.SnakeToCamelIdentifier(dt[len(args.Schema)+1:])
nilVal = typ + "(0)"
} else {
typ = snaker.SnakeToCamelIdentifier(dt)
nilVal = typ + "{}"
}
}
// special case for []slice
if typ == "string" && asSlice {
return precision, "StringSlice{}", "StringSlice"
}
// correct type if slice
if asSlice {
typ = "[]" + typ
nilVal = "nil"
}
return precision, nilVal, typ
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/postgres.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/postgres.go#L219-L229 | go | train | // PgQueryStrip strips stuff. | func PgQueryStrip(query []string, queryComments []string) | // PgQueryStrip strips stuff.
func PgQueryStrip(query []string, queryComments []string) | {
for i, l := range query {
pos := pgQueryStripRE.FindStringIndex(l)
if pos != nil {
query[i] = l[:pos[0]] + l[pos[1]:]
queryComments[i+1] = l[pos[0]:pos[1]]
} else {
queryComments[i+1] = ""
}
}
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/postgres.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/postgres.go#L233-L267 | go | train | // PgTables returns the Postgres tables with the manual PK information added.
// ManualPk is true when the table does not have a sequence defined. | func PgTables(db models.XODB, schema string, relkind string) ([]*models.Table, error) | // PgTables returns the Postgres tables with the manual PK information added.
// ManualPk is true when the table does not have a sequence defined.
func PgTables(db models.XODB, schema string, relkind string) ([]*models.Table, error) | {
var err error
// get the tables
rows, err := models.PgTables(db, schema, relkind)
if err != nil {
return nil, err
}
// Get the tables that have a sequence defined.
sequences, err := models.PgSequences(db, schema)
if err != nil {
// Set it to an empty set on error.
sequences = []*models.Sequence{}
}
// Add information about manual FK.
var tables []*models.Table
for _, row := range rows {
manualPk := true
// Look for a match in the table name where it contains the sequence
for _, sequence := range sequences {
if sequence.TableName == row.TableName {
manualPk = false
}
}
tables = append(tables, &models.Table{
TableName: row.TableName,
Type: row.Type,
ManualPk: manualPk,
})
}
return tables, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/postgres.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/postgres.go#L270-L298 | go | train | // PgQueryColumns parses the query and generates a type for it. | func PgQueryColumns(args *internal.ArgType, inspect []string) ([]*models.Column, error) | // PgQueryColumns parses the query and generates a type for it.
func PgQueryColumns(args *internal.ArgType, inspect []string) ([]*models.Column, error) | {
var err error
// create temporary view xoid
xoid := "_xo_" + internal.GenRandomID()
viewq := `CREATE TEMPORARY VIEW ` + xoid + ` AS (` + strings.Join(inspect, "\n") + `)`
models.XOLog(viewq)
_, err = args.DB.Exec(viewq)
if err != nil {
return nil, err
}
// query to determine schema name where temporary view was created
var nspq = `SELECT n.nspname ` +
`FROM pg_class c ` +
`JOIN pg_namespace n ON n.oid = c.relnamespace ` +
`WHERE n.nspname LIKE 'pg_temp%' AND c.relname = $1`
// run query
var schema string
models.XOLog(nspq, xoid)
err = args.DB.QueryRow(nspq, xoid).Scan(&schema)
if err != nil {
return nil, err
}
// load column information
return models.PgTableColumns(args.DB, schema, xoid, false)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/postgres.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/postgres.go#L301-L350 | go | train | // PgIndexColumns returns the column list for an index. | func PgIndexColumns(db models.XODB, schema string, table string, index string) ([]*models.IndexColumn, error) | // PgIndexColumns returns the column list for an index.
func PgIndexColumns(db models.XODB, schema string, table string, index string) ([]*models.IndexColumn, error) | {
var err error
// load columns
cols, err := models.PgIndexColumns(db, schema, index)
if err != nil {
return nil, err
}
// load col order
colOrd, err := models.PgGetColOrder(db, schema, index)
if err != nil {
return nil, err
}
// build schema name used in errors
s := schema
if s != "" {
s = s + "."
}
// put cols in order using colOrder
ret := []*models.IndexColumn{}
for _, v := range strings.Split(colOrd.Ord, " ") {
cid, err := strconv.Atoi(v)
if err != nil {
return nil, fmt.Errorf("could not convert %s%s index %s column %s to int", s, table, index, v)
}
// find column
found := false
var c *models.IndexColumn
for _, ic := range cols {
if cid == ic.Cid {
found = true
c = ic
break
}
}
// sanity check
if !found {
return nil, fmt.Errorf("could not find %s%s index %s column id %d", s, table, index, cid)
}
ret = append(ret, c)
}
return ret, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/djangocontenttype.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/djangocontenttype.xo.go#L32-L65 | go | train | // Insert inserts the DjangoContentType to the database. | func (dct *DjangoContentType) Insert(db XODB) error | // Insert inserts the DjangoContentType to the database.
func (dct *DjangoContentType) Insert(db XODB) error | {
var err error
// if already exist, bail
if dct._exists {
return errors.New("insert failed: already exists")
}
// sql query
const sqlstr = `INSERT INTO django.django_content_type (` +
`app_label, model` +
`) VALUES (` +
`:1, :2` +
`) RETURNING id /*lastInsertId*/ INTO :pk`
// run query
XOLog(sqlstr, dct.AppLabel, dct.Model, nil)
res, err := db.Exec(sqlstr, dct.AppLabel, dct.Model, nil)
if err != nil {
return err
}
// retrieve id
id, err := res.LastInsertId()
if err != nil {
return err
}
// set primary key and existence
dct.ID = float64(id)
dct._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/djangocontenttype.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/djangocontenttype.xo.go#L31-L57 | go | train | // Insert inserts the DjangoContentType to the database. | func (dct *DjangoContentType) Insert(db XODB) error | // Insert inserts the DjangoContentType to the database.
func (dct *DjangoContentType) Insert(db XODB) error | {
var err error
// if already exist, bail
if dct._exists {
return errors.New("insert failed: already exists")
}
// sql insert query, primary key provided by sequence
const sqlstr = `INSERT INTO public.django_content_type (` +
`app_label, model` +
`) VALUES (` +
`$1, $2` +
`) RETURNING id`
// run query
XOLog(sqlstr, dct.AppLabel, dct.Model)
err = db.QueryRow(sqlstr, dct.AppLabel, dct.Model).Scan(&dct.ID)
if err != nil {
return err
}
// set existence
dct._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/djangocontenttype.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/djangocontenttype.xo.go#L60-L84 | go | train | // Update updates the DjangoContentType in the database. | func (dct *DjangoContentType) Update(db XODB) error | // Update updates the DjangoContentType in the database.
func (dct *DjangoContentType) Update(db XODB) error | {
var err error
// if doesn't exist, bail
if !dct._exists {
return errors.New("update failed: does not exist")
}
// if deleted, bail
if dct._deleted {
return errors.New("update failed: marked for deletion")
}
// sql query
const sqlstr = `UPDATE public.django_content_type SET (` +
`app_label, model` +
`) = ( ` +
`$1, $2` +
`) WHERE id = $3`
// run query
XOLog(sqlstr, dct.AppLabel, dct.Model, dct.ID)
_, err = db.Exec(sqlstr, dct.AppLabel, dct.Model, dct.ID)
return err
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/djangocontenttype.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/djangocontenttype.xo.go#L98-L128 | go | train | // Upsert performs an upsert for DjangoContentType.
//
// NOTE: PostgreSQL 9.5+ only | func (dct *DjangoContentType) Upsert(db XODB) error | // Upsert performs an upsert for DjangoContentType.
//
// NOTE: PostgreSQL 9.5+ only
func (dct *DjangoContentType) Upsert(db XODB) error | {
var err error
// if already exist, bail
if dct._exists {
return errors.New("insert failed: already exists")
}
// sql query
const sqlstr = `INSERT INTO public.django_content_type (` +
`id, app_label, model` +
`) VALUES (` +
`$1, $2, $3` +
`) ON CONFLICT (id) DO UPDATE SET (` +
`id, app_label, model` +
`) = (` +
`EXCLUDED.id, EXCLUDED.app_label, EXCLUDED.model` +
`)`
// run query
XOLog(sqlstr, dct.ID, dct.AppLabel, dct.Model)
_, err = db.Exec(sqlstr, dct.ID, dct.AppLabel, dct.Model)
if err != nil {
return err
}
// set existence
dct._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/djangocontenttype.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/djangocontenttype.xo.go#L131-L158 | go | train | // Delete deletes the DjangoContentType from the database. | func (dct *DjangoContentType) Delete(db XODB) error | // Delete deletes the DjangoContentType from the database.
func (dct *DjangoContentType) Delete(db XODB) error | {
var err error
// if doesn't exist, bail
if !dct._exists {
return nil
}
// if deleted, bail
if dct._deleted {
return nil
}
// sql query
const sqlstr = `DELETE FROM public.django_content_type WHERE id = $1`
// run query
XOLog(sqlstr, dct.ID)
_, err = db.Exec(sqlstr, dct.ID)
if err != nil {
return err
}
// set deleted
dct._deleted = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/authgrouppermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/authgrouppermission.xo.go#L145-L166 | go | train | // AuthGroupPermissionByGroupIDPermissionID retrieves a row from 'django.auth_group_permissions' as a AuthGroupPermission.
//
// Generated from index 'auth_gr_group_id_0cd325b0_uniq'. | func AuthGroupPermissionByGroupIDPermissionID(db XODB, groupID float64, permissionID float64) (*AuthGroupPermission, error) | // AuthGroupPermissionByGroupIDPermissionID retrieves a row from 'django.auth_group_permissions' as a AuthGroupPermission.
//
// Generated from index 'auth_gr_group_id_0cd325b0_uniq'.
func AuthGroupPermissionByGroupIDPermissionID(db XODB, groupID float64, permissionID float64) (*AuthGroupPermission, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, group_id, permission_id ` +
`FROM django.auth_group_permissions ` +
`WHERE group_id = :1 AND permission_id = :2`
// run query
XOLog(sqlstr, groupID, permissionID)
agp := AuthGroupPermission{
_exists: true,
}
err = db.QueryRow(sqlstr, groupID, permissionID).Scan(&agp.ID, &agp.GroupID, &agp.PermissionID)
if err != nil {
return nil, err
}
return &agp, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | models/procparam.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/models/procparam.xo.go#L12-L45 | go | train | // PgProcParams runs a custom query, returning results as ProcParam. | func PgProcParams(db XODB, schema string, proc string) ([]*ProcParam, error) | // PgProcParams runs a custom query, returning results as ProcParam.
func PgProcParams(db XODB, schema string, proc string) ([]*ProcParam, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`UNNEST(STRING_TO_ARRAY(oidvectortypes(p.proargtypes), ', ')) ` + // ::varchar AS param_type
`FROM pg_proc p ` +
`JOIN ONLY pg_namespace n ON p.pronamespace = n.oid ` +
`WHERE n.nspname = $1 AND p.proname = $2`
// run query
XOLog(sqlstr, schema, proc)
q, err := db.Query(sqlstr, schema, proc)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*ProcParam{}
for q.Next() {
pp := ProcParam{}
// scan
err = q.Scan(&pp.ParamType)
if err != nil {
return nil, err
}
res = append(res, &pp)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/mysql/authusergroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/mysql/authusergroup.xo.go#L147-L181 | go | train | // AuthUserGroupsByGroupID retrieves a row from 'django.auth_user_groups' as a AuthUserGroup.
//
// Generated from index 'auth_user_groups_group_id_97559544_fk_auth_group_id'. | func AuthUserGroupsByGroupID(db XODB, groupID int) ([]*AuthUserGroup, error) | // AuthUserGroupsByGroupID retrieves a row from 'django.auth_user_groups' as a AuthUserGroup.
//
// Generated from index 'auth_user_groups_group_id_97559544_fk_auth_group_id'.
func AuthUserGroupsByGroupID(db XODB, groupID int) ([]*AuthUserGroup, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, user_id, group_id ` +
`FROM django.auth_user_groups ` +
`WHERE group_id = ?`
// run query
XOLog(sqlstr, groupID)
q, err := db.Query(sqlstr, groupID)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*AuthUserGroup{}
for q.Next() {
aug := AuthUserGroup{
_exists: true,
}
// scan
err = q.Scan(&aug.ID, &aug.UserID, &aug.GroupID)
if err != nil {
return nil, err
}
res = append(res, &aug)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/mysql/authusergroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/mysql/authusergroup.xo.go#L186-L207 | go | train | // AuthUserGroupByID retrieves a row from 'django.auth_user_groups' as a AuthUserGroup.
//
// Generated from index 'auth_user_groups_id_pkey'. | func AuthUserGroupByID(db XODB, id int) (*AuthUserGroup, error) | // AuthUserGroupByID retrieves a row from 'django.auth_user_groups' as a AuthUserGroup.
//
// Generated from index 'auth_user_groups_id_pkey'.
func AuthUserGroupByID(db XODB, id int) (*AuthUserGroup, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, user_id, group_id ` +
`FROM django.auth_user_groups ` +
`WHERE id = ?`
// run query
XOLog(sqlstr, id)
aug := AuthUserGroup{
_exists: true,
}
err = db.QueryRow(sqlstr, id).Scan(&aug.ID, &aug.UserID, &aug.GroupID)
if err != nil {
return nil, err
}
return &aug, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/mssql.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/mssql.go#L68-L182 | go | train | // MsParseType parse a mssql type into a Go type based on the column
// definition. | func MsParseType(args *internal.ArgType, dt string, nullable bool) (int, string, string) | // MsParseType parse a mssql type into a Go type based on the column
// definition.
func MsParseType(args *internal.ArgType, dt string, nullable bool) (int, string, string) | {
precision := 0
nilVal := "nil"
// extract precision
dt, precision, _ = args.ParsePrecision(dt)
var typ string
switch dt {
case "tinyint", "bit":
nilVal = "false"
typ = "bool"
if nullable {
nilVal = "sql.NullBool{}"
typ = "sql.NullBool"
}
case "char", "varchar", "text", "nchar", "nvarchar", "ntext", "smallmoney", "money":
nilVal = `""`
typ = "string"
if nullable {
nilVal = "sql.NullString{}"
typ = "sql.NullString"
}
case "smallint":
nilVal = "0"
typ = "int16"
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "int":
nilVal = "0"
typ = args.Int32Type
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "bigint":
nilVal = "0"
typ = "int64"
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "smallserial":
nilVal = "0"
typ = "uint16"
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "serial":
nilVal = "0"
typ = args.Uint32Type
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "bigserial":
nilVal = "0"
typ = "uint64"
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "real":
nilVal = "0.0"
typ = "float32"
if nullable {
nilVal = "sql.NullFloat64{}"
typ = "sql.NullFloat64"
}
case "numeric", "decimal":
nilVal = "0.0"
typ = "float64"
if nullable {
nilVal = "sql.NullFloat64{}"
typ = "sql.NullFloat64"
}
case "binary", "varbinary":
typ = "[]byte"
case "datetime", "datetime2", "timestamp":
nilVal = "time.Time{}"
typ = "time.Time"
case "time with time zone", "time without time zone", "timestamp without time zone":
nilVal = "0"
typ = "int64"
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "interval":
typ = "*time.Duration"
default:
if strings.HasPrefix(dt, args.Schema+".") {
// in the same schema, so chop off
typ = snaker.SnakeToCamelIdentifier(dt[len(args.Schema)+1:])
nilVal = typ + "(0)"
} else {
typ = snaker.SnakeToCamelIdentifier(dt)
nilVal = typ + "{}"
}
}
return precision, nilVal, typ
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/mssql.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/mssql.go#L185-L215 | go | train | // MsQueryColumns parses the query and generates a type for it. | func MsQueryColumns(args *internal.ArgType, inspect []string) ([]*models.Column, error) | // MsQueryColumns parses the query and generates a type for it.
func MsQueryColumns(args *internal.ArgType, inspect []string) ([]*models.Column, error) | {
var err error
// process inspect -- cannot have 'order by' in a CREATE VIEW
ins := []string{}
for _, l := range inspect {
if !strings.HasPrefix(strings.ToUpper(l), "ORDER BY ") {
ins = append(ins, l)
}
}
// create temporary view xoid
xoid := "_xo_" + internal.GenRandomID()
viewq := `CREATE VIEW ` + xoid + ` AS ` + strings.Join(ins, "\n")
models.XOLog(viewq)
_, err = args.DB.Exec(viewq)
if err != nil {
return nil, err
}
// load columns
cols, err := models.MsTableColumns(args.DB, args.Schema, xoid)
// drop inspect view
dropq := `DROP VIEW ` + xoid
models.XOLog(dropq)
_, _ = args.DB.Exec(dropq)
// load column information
return cols, err
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/mssql.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/mssql.go#L219-L253 | go | train | // MsTables returns the MsSQL tables with the manual PK information added.
// ManualPk is true when the table's primary key is not an identity. | func MsTables(db models.XODB, schema string, relkind string) ([]*models.Table, error) | // MsTables returns the MsSQL tables with the manual PK information added.
// ManualPk is true when the table's primary key is not an identity.
func MsTables(db models.XODB, schema string, relkind string) ([]*models.Table, error) | {
var err error
// get the tables
rows, err := models.MsTables(db, schema, relkind)
if err != nil {
return nil, err
}
// get the tables that have Identity included
identities, err := models.MsIdentities(db, schema)
if err != nil {
// Set it to an empty set on error.
identities = []*models.MsIdentity{}
}
// Add information about manual FK.
var tables []*models.Table
for _, row := range rows {
manualPk := true
// Look for a match in the table name where it contains the identity
for _, identity := range identities {
if identity.TableName == row.TableName {
manualPk = false
}
}
tables = append(tables, &models.Table{
TableName: row.TableName,
Type: row.Type,
ManualPk: manualPk,
})
}
return tables, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/mysql/djangoadminlog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/mysql/djangoadminlog.xo.go#L108-L135 | go | train | // Delete deletes the DjangoAdminLog from the database. | func (dal *DjangoAdminLog) Delete(db XODB) error | // Delete deletes the DjangoAdminLog from the database.
func (dal *DjangoAdminLog) Delete(db XODB) error | {
var err error
// if doesn't exist, bail
if !dal._exists {
return nil
}
// if deleted, bail
if dal._deleted {
return nil
}
// sql query
const sqlstr = `DELETE FROM django.django_admin_log WHERE id = ?`
// run query
XOLog(sqlstr, dal.ID)
_, err = db.Exec(sqlstr, dal.ID)
if err != nil {
return err
}
// set deleted
dal._deleted = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/djangomigration.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/djangomigration.xo.go#L33-L59 | go | train | // Insert inserts the DjangoMigration to the database. | func (dm *DjangoMigration) Insert(db XODB) error | // Insert inserts the DjangoMigration to the database.
func (dm *DjangoMigration) Insert(db XODB) error | {
var err error
// if already exist, bail
if dm._exists {
return errors.New("insert failed: already exists")
}
// sql insert query, primary key provided by sequence
const sqlstr = `INSERT INTO public.django_migrations (` +
`app, name, applied` +
`) VALUES (` +
`$1, $2, $3` +
`) RETURNING id`
// run query
XOLog(sqlstr, dm.App, dm.Name, dm.Applied)
err = db.QueryRow(sqlstr, dm.App, dm.Name, dm.Applied).Scan(&dm.ID)
if err != nil {
return err
}
// set existence
dm._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/djangomigration.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/djangomigration.xo.go#L100-L130 | go | train | // Upsert performs an upsert for DjangoMigration.
//
// NOTE: PostgreSQL 9.5+ only | func (dm *DjangoMigration) Upsert(db XODB) error | // Upsert performs an upsert for DjangoMigration.
//
// NOTE: PostgreSQL 9.5+ only
func (dm *DjangoMigration) Upsert(db XODB) error | {
var err error
// if already exist, bail
if dm._exists {
return errors.New("insert failed: already exists")
}
// sql query
const sqlstr = `INSERT INTO public.django_migrations (` +
`id, app, name, applied` +
`) VALUES (` +
`$1, $2, $3, $4` +
`) ON CONFLICT (id) DO UPDATE SET (` +
`id, app, name, applied` +
`) = (` +
`EXCLUDED.id, EXCLUDED.app, EXCLUDED.name, EXCLUDED.applied` +
`)`
// run query
XOLog(sqlstr, dm.ID, dm.App, dm.Name, dm.Applied)
_, err = db.Exec(sqlstr, dm.ID, dm.App, dm.Name, dm.Applied)
if err != nil {
return err
}
// set existence
dm._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/mysql/djangosession.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/mysql/djangosession.xo.go#L127-L161 | go | train | // DjangoSessionsByExpireDate retrieves a row from 'django.django_session' as a DjangoSession.
//
// Generated from index 'django_session_de54fa62'. | func DjangoSessionsByExpireDate(db XODB, expireDate *time.Time) ([]*DjangoSession, error) | // DjangoSessionsByExpireDate retrieves a row from 'django.django_session' as a DjangoSession.
//
// Generated from index 'django_session_de54fa62'.
func DjangoSessionsByExpireDate(db XODB, expireDate *time.Time) ([]*DjangoSession, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`session_key, session_data, expire_date ` +
`FROM django.django_session ` +
`WHERE expire_date = ?`
// run query
XOLog(sqlstr, expireDate)
q, err := db.Query(sqlstr, expireDate)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*DjangoSession{}
for q.Next() {
ds := DjangoSession{
_exists: true,
}
// scan
err = q.Scan(&ds.SessionKey, &ds.SessionData, &ds.ExpireDate)
if err != nil {
return nil, err
}
res = append(res, &ds)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/mysql/djangosession.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/mysql/djangosession.xo.go#L166-L187 | go | train | // DjangoSessionBySessionKey retrieves a row from 'django.django_session' as a DjangoSession.
//
// Generated from index 'django_session_session_key_pkey'. | func DjangoSessionBySessionKey(db XODB, sessionKey string) (*DjangoSession, error) | // DjangoSessionBySessionKey retrieves a row from 'django.django_session' as a DjangoSession.
//
// Generated from index 'django_session_session_key_pkey'.
func DjangoSessionBySessionKey(db XODB, sessionKey string) (*DjangoSession, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`session_key, session_data, expire_date ` +
`FROM django.django_session ` +
`WHERE session_key = ?`
// run query
XOLog(sqlstr, sessionKey)
ds := DjangoSession{
_exists: true,
}
err = db.QueryRow(sqlstr, sessionKey).Scan(&ds.SessionKey, &ds.SessionData, &ds.ExpireDate)
if err != nil {
return nil, err
}
return &ds, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/mysql/authuseruserpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/mysql/authuseruserpermission.xo.go#L31-L64 | go | train | // Insert inserts the AuthUserUserPermission to the database. | func (auup *AuthUserUserPermission) Insert(db XODB) error | // Insert inserts the AuthUserUserPermission to the database.
func (auup *AuthUserUserPermission) Insert(db XODB) error | {
var err error
// if already exist, bail
if auup._exists {
return errors.New("insert failed: already exists")
}
// sql insert query, primary key provided by autoincrement
const sqlstr = `INSERT INTO django.auth_user_user_permissions (` +
`user_id, permission_id` +
`) VALUES (` +
`?, ?` +
`)`
// run query
XOLog(sqlstr, auup.UserID, auup.PermissionID)
res, err := db.Exec(sqlstr, auup.UserID, auup.PermissionID)
if err != nil {
return err
}
// retrieve id
id, err := res.LastInsertId()
if err != nil {
return err
}
// set primary key and existence
auup.ID = int(id)
auup._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/mysql/authuseruserpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/mysql/authuseruserpermission.xo.go#L67-L89 | go | train | // Update updates the AuthUserUserPermission in the database. | func (auup *AuthUserUserPermission) Update(db XODB) error | // Update updates the AuthUserUserPermission in the database.
func (auup *AuthUserUserPermission) Update(db XODB) error | {
var err error
// if doesn't exist, bail
if !auup._exists {
return errors.New("update failed: does not exist")
}
// if deleted, bail
if auup._deleted {
return errors.New("update failed: marked for deletion")
}
// sql query
const sqlstr = `UPDATE django.auth_user_user_permissions SET ` +
`user_id = ?, permission_id = ?` +
` WHERE id = ?`
// run query
XOLog(sqlstr, auup.UserID, auup.PermissionID, auup.ID)
_, err = db.Exec(sqlstr, auup.UserID, auup.PermissionID, auup.ID)
return err
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/djangomigration.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/djangomigration.xo.go#L34-L67 | go | train | // Insert inserts the DjangoMigration to the database. | func (dm *DjangoMigration) Insert(db XODB) error | // Insert inserts the DjangoMigration to the database.
func (dm *DjangoMigration) Insert(db XODB) error | {
var err error
// if already exist, bail
if dm._exists {
return errors.New("insert failed: already exists")
}
// sql query
const sqlstr = `INSERT INTO django.django_migrations (` +
`app, name, applied` +
`) VALUES (` +
`:1, :2, :3` +
`) RETURNING id /*lastInsertId*/ INTO :pk`
// run query
XOLog(sqlstr, dm.App, dm.Name, dm.Applied, nil)
res, err := db.Exec(sqlstr, dm.App, dm.Name, dm.Applied, nil)
if err != nil {
return err
}
// retrieve id
id, err := res.LastInsertId()
if err != nil {
return err
}
// set primary key and existence
dm.ID = float64(id)
dm._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/djangomigration.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/djangomigration.xo.go#L70-L92 | go | train | // Update updates the DjangoMigration in the database. | func (dm *DjangoMigration) Update(db XODB) error | // Update updates the DjangoMigration in the database.
func (dm *DjangoMigration) Update(db XODB) error | {
var err error
// if doesn't exist, bail
if !dm._exists {
return errors.New("update failed: does not exist")
}
// if deleted, bail
if dm._deleted {
return errors.New("update failed: marked for deletion")
}
// sql query
const sqlstr = `UPDATE django.django_migrations SET ` +
`app = :1, name = :2, applied = :3` +
` WHERE id = :4`
// run query
XOLog(sqlstr, dm.App, dm.Name, dm.Applied, dm.ID)
_, err = db.Exec(sqlstr, dm.App, dm.Name, dm.Applied, dm.ID)
return err
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/djangomigration.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/djangomigration.xo.go#L104-L131 | go | train | // Delete deletes the DjangoMigration from the database. | func (dm *DjangoMigration) Delete(db XODB) error | // Delete deletes the DjangoMigration from the database.
func (dm *DjangoMigration) Delete(db XODB) error | {
var err error
// if doesn't exist, bail
if !dm._exists {
return nil
}
// if deleted, bail
if dm._deleted {
return nil
}
// sql query
const sqlstr = `DELETE FROM django.django_migrations WHERE id = :1`
// run query
XOLog(sqlstr, dm.ID)
_, err = db.Exec(sqlstr, dm.ID)
if err != nil {
return err
}
// set deleted
dm._deleted = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/djangomigration.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/djangomigration.xo.go#L136-L157 | go | train | // DjangoMigrationByID retrieves a row from 'django.django_migrations' as a DjangoMigration.
//
// Generated from index 'sys_c004953'. | func DjangoMigrationByID(db XODB, id float64) (*DjangoMigration, error) | // DjangoMigrationByID retrieves a row from 'django.django_migrations' as a DjangoMigration.
//
// Generated from index 'sys_c004953'.
func DjangoMigrationByID(db XODB, id float64) (*DjangoMigration, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, app, name, applied ` +
`FROM django.django_migrations ` +
`WHERE id = :1`
// run query
XOLog(sqlstr, id)
dm := DjangoMigration{
_exists: true,
}
err = db.QueryRow(sqlstr, id).Scan(&dm.ID, &dm.App, &dm.Name, &dm.Applied)
if err != nil {
return nil, err
}
return &dm, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/sqlite3/djangocontenttype.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/sqlite3/djangocontenttype.xo.go#L159-L180 | go | train | // DjangoContentTypeByID retrieves a row from 'django_content_type' as a DjangoContentType.
//
// Generated from index 'django_content_type_id_pkey'. | func DjangoContentTypeByID(db XODB, id int) (*DjangoContentType, error) | // DjangoContentTypeByID retrieves a row from 'django_content_type' as a DjangoContentType.
//
// Generated from index 'django_content_type_id_pkey'.
func DjangoContentTypeByID(db XODB, id int) (*DjangoContentType, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, app_label, model ` +
`FROM django_content_type ` +
`WHERE id = ?`
// run query
XOLog(sqlstr, id)
dct := DjangoContentType{
_exists: true,
}
err = db.QueryRow(sqlstr, id).Scan(&dct.ID, &dct.AppLabel, &dct.Model)
if err != nil {
return nil, err
}
return &dct, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/djangoadminlog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/djangoadminlog.xo.go#L38-L64 | go | train | // Insert inserts the DjangoAdminLog to the database. | func (dal *DjangoAdminLog) Insert(db XODB) error | // Insert inserts the DjangoAdminLog to the database.
func (dal *DjangoAdminLog) Insert(db XODB) error | {
var err error
// if already exist, bail
if dal._exists {
return errors.New("insert failed: already exists")
}
// sql insert query, primary key provided by sequence
const sqlstr = `INSERT INTO public.django_admin_log (` +
`action_time, object_id, object_repr, action_flag, change_message, content_type_id, user_id` +
`) VALUES (` +
`$1, $2, $3, $4, $5, $6, $7` +
`) RETURNING id`
// run query
XOLog(sqlstr, dal.ActionTime, dal.ObjectID, dal.ObjectRepr, dal.ActionFlag, dal.ChangeMessage, dal.ContentTypeID, dal.UserID)
err = db.QueryRow(sqlstr, dal.ActionTime, dal.ObjectID, dal.ObjectRepr, dal.ActionFlag, dal.ChangeMessage, dal.ContentTypeID, dal.UserID).Scan(&dal.ID)
if err != nil {
return err
}
// set existence
dal._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/djangoadminlog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/djangoadminlog.xo.go#L67-L91 | go | train | // Update updates the DjangoAdminLog in the database. | func (dal *DjangoAdminLog) Update(db XODB) error | // Update updates the DjangoAdminLog in the database.
func (dal *DjangoAdminLog) Update(db XODB) error | {
var err error
// if doesn't exist, bail
if !dal._exists {
return errors.New("update failed: does not exist")
}
// if deleted, bail
if dal._deleted {
return errors.New("update failed: marked for deletion")
}
// sql query
const sqlstr = `UPDATE public.django_admin_log SET (` +
`action_time, object_id, object_repr, action_flag, change_message, content_type_id, user_id` +
`) = ( ` +
`$1, $2, $3, $4, $5, $6, $7` +
`) WHERE id = $8`
// run query
XOLog(sqlstr, dal.ActionTime, dal.ObjectID, dal.ObjectRepr, dal.ActionFlag, dal.ChangeMessage, dal.ContentTypeID, dal.UserID, dal.ID)
_, err = db.Exec(sqlstr, dal.ActionTime, dal.ObjectID, dal.ObjectRepr, dal.ActionFlag, dal.ChangeMessage, dal.ContentTypeID, dal.UserID, dal.ID)
return err
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/djangoadminlog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/djangoadminlog.xo.go#L184-L218 | go | train | // DjangoAdminLogsByContentTypeID retrieves a row from 'public.django_admin_log' as a DjangoAdminLog.
//
// Generated from index 'django_admin_log_417f1b1c'. | func DjangoAdminLogsByContentTypeID(db XODB, contentTypeID sql.NullInt64) ([]*DjangoAdminLog, error) | // DjangoAdminLogsByContentTypeID retrieves a row from 'public.django_admin_log' as a DjangoAdminLog.
//
// Generated from index 'django_admin_log_417f1b1c'.
func DjangoAdminLogsByContentTypeID(db XODB, contentTypeID sql.NullInt64) ([]*DjangoAdminLog, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, action_time, object_id, object_repr, action_flag, change_message, content_type_id, user_id ` +
`FROM public.django_admin_log ` +
`WHERE content_type_id = $1`
// run query
XOLog(sqlstr, contentTypeID)
q, err := db.Query(sqlstr, contentTypeID)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*DjangoAdminLog{}
for q.Next() {
dal := DjangoAdminLog{
_exists: true,
}
// scan
err = q.Scan(&dal.ID, &dal.ActionTime, &dal.ObjectID, &dal.ObjectRepr, &dal.ActionFlag, &dal.ChangeMessage, &dal.ContentTypeID, &dal.UserID)
if err != nil {
return nil, err
}
res = append(res, &dal)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | models/proc.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/models/proc.xo.go#L13-L47 | go | train | // PgProcs runs a custom query, returning results as Proc. | func PgProcs(db XODB, schema string) ([]*Proc, error) | // PgProcs runs a custom query, returning results as Proc.
func PgProcs(db XODB, schema string) ([]*Proc, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`p.proname, ` + // ::varchar AS proc_name
`pg_get_function_result(p.oid) ` + // ::varchar AS return_type
`FROM pg_proc p ` +
`JOIN ONLY pg_namespace n ON p.pronamespace = n.oid ` +
`WHERE n.nspname = $1`
// run query
XOLog(sqlstr, schema)
q, err := db.Query(sqlstr, schema)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*Proc{}
for q.Next() {
p := Proc{}
// scan
err = q.Scan(&p.ProcName, &p.ReturnType)
if err != nil {
return nil, err
}
res = append(res, &p)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/authgroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/authgroup.xo.go#L31-L64 | go | train | // Insert inserts the AuthGroup to the database. | func (ag *AuthGroup) Insert(db XODB) error | // Insert inserts the AuthGroup to the database.
func (ag *AuthGroup) Insert(db XODB) error | {
var err error
// if already exist, bail
if ag._exists {
return errors.New("insert failed: already exists")
}
// sql query
const sqlstr = `INSERT INTO django.auth_group (` +
`name` +
`) VALUES (` +
`:1` +
`) RETURNING id /*lastInsertId*/ INTO :pk`
// run query
XOLog(sqlstr, ag.Name, nil)
res, err := db.Exec(sqlstr, ag.Name, nil)
if err != nil {
return err
}
// retrieve id
id, err := res.LastInsertId()
if err != nil {
return err
}
// set primary key and existence
ag.ID = float64(id)
ag._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/authgroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/authgroup.xo.go#L101-L128 | go | train | // Delete deletes the AuthGroup from the database. | func (ag *AuthGroup) Delete(db XODB) error | // Delete deletes the AuthGroup from the database.
func (ag *AuthGroup) Delete(db XODB) error | {
var err error
// if doesn't exist, bail
if !ag._exists {
return nil
}
// if deleted, bail
if ag._deleted {
return nil
}
// sql query
const sqlstr = `DELETE FROM django.auth_group WHERE id = :1`
// run query
XOLog(sqlstr, ag.ID)
_, err = db.Exec(sqlstr, ag.ID)
if err != nil {
return err
}
// set deleted
ag._deleted = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/sqlite3/authgroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/sqlite3/authgroup.xo.go#L66-L88 | go | train | // Update updates the AuthGroup in the database. | func (ag *AuthGroup) Update(db XODB) error | // Update updates the AuthGroup in the database.
func (ag *AuthGroup) Update(db XODB) error | {
var err error
// if doesn't exist, bail
if !ag._exists {
return errors.New("update failed: does not exist")
}
// if deleted, bail
if ag._deleted {
return errors.New("update failed: marked for deletion")
}
// sql query
const sqlstr = `UPDATE auth_group SET ` +
`name = ?` +
` WHERE id = ?`
// run query
XOLog(sqlstr, ag.Name, ag.ID)
_, err = db.Exec(sqlstr, ag.Name, ag.ID)
return err
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/authuser.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/authuser.xo.go#L111-L138 | go | train | // Delete deletes the AuthUser from the database. | func (au *AuthUser) Delete(db XODB) error | // Delete deletes the AuthUser from the database.
func (au *AuthUser) Delete(db XODB) error | {
var err error
// if doesn't exist, bail
if !au._exists {
return nil
}
// if deleted, bail
if au._deleted {
return nil
}
// sql query
const sqlstr = `DELETE FROM django.auth_user WHERE id = :1`
// run query
XOLog(sqlstr, au.ID)
_, err = db.Exec(sqlstr, au.ID)
if err != nil {
return err
}
// set deleted
au._deleted = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/authuser.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/authuser.xo.go#L169-L190 | go | train | // AuthUserByUsername retrieves a row from 'django.auth_user' as a AuthUser.
//
// Generated from index 'sys_c004977'. | func AuthUserByUsername(db XODB, username sql.NullString) (*AuthUser, error) | // AuthUserByUsername retrieves a row from 'django.auth_user' as a AuthUser.
//
// Generated from index 'sys_c004977'.
func AuthUserByUsername(db XODB, username sql.NullString) (*AuthUser, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, password, last_login, is_superuser, username, first_name, last_name, email, is_staff, is_active, date_joined ` +
`FROM django.auth_user ` +
`WHERE username = :1`
// run query
XOLog(sqlstr, username)
au := AuthUser{
_exists: true,
}
err = db.QueryRow(sqlstr, username).Scan(&au.ID, &au.Password, &au.LastLogin, &au.IsSuperuser, &au.Username, &au.FirstName, &au.LastName, &au.Email, &au.IsStaff, &au.IsActive, &au.DateJoined)
if err != nil {
return nil, err
}
return &au, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/fkmode.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/fkmode.go#L44-L60 | go | train | // UnmarshalText unmarshals FkMode from text. | func (f *FkMode) UnmarshalText(text []byte) error | // UnmarshalText unmarshals FkMode from text.
func (f *FkMode) UnmarshalText(text []byte) error | {
switch strings.ToLower(string(text)) {
case "smart", "default":
*f = FkModeSmart
case "parent":
*f = FkModeParent
case "field":
*f = FkModeField
case "key":
*f = FkModeKey
default:
return errors.New("invalid FkMode")
}
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/fkmode.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/fkmode.go#L79-L99 | go | train | // fkName returns the name for the foreign key. | func fkName(mode FkMode, fkMap map[string]*ForeignKey, fk *ForeignKey) string | // fkName returns the name for the foreign key.
func fkName(mode FkMode, fkMap map[string]*ForeignKey, fk *ForeignKey) string | {
switch mode {
case FkModeParent:
return fk.RefType.Name
case FkModeField:
return fk.RefType.Name + "By" + fk.Field.Name
case FkModeKey:
return fk.RefType.Name + "By" + snaker.SnakeToCamelIdentifier(fk.ForeignKey.ForeignKeyName)
}
// mode is FkModeSmart
// inspect all foreign keys and use FkModeField if conflict found
for _, f := range fkMap {
if fk != f && fk.Type.Name == f.Type.Name && fk.RefType.Name == f.RefType.Name {
return fkName(FkModeField, fkMap, fk)
}
}
// no conflict, so use FkModeParent
return fkName(FkModeParent, fkMap, fk)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/fkmode.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/fkmode.go#L102-L104 | go | train | // ForeignKeyName returns the foreign key name for the passed type. | func (a *ArgType) ForeignKeyName(fkMap map[string]*ForeignKey, fk *ForeignKey) string | // ForeignKeyName returns the foreign key name for the passed type.
func (a *ArgType) ForeignKeyName(fkMap map[string]*ForeignKey, fk *ForeignKey) string | {
return fkName(*a.ForeignKeyMode, fkMap, fk)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authuseruserpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authuseruserpermission.xo.go#L31-L57 | go | train | // Insert inserts the AuthUserUserPermission to the database. | func (auup *AuthUserUserPermission) Insert(db XODB) error | // Insert inserts the AuthUserUserPermission to the database.
func (auup *AuthUserUserPermission) Insert(db XODB) error | {
var err error
// if already exist, bail
if auup._exists {
return errors.New("insert failed: already exists")
}
// sql insert query, primary key provided by sequence
const sqlstr = `INSERT INTO public.auth_user_user_permissions (` +
`user_id, permission_id` +
`) VALUES (` +
`$1, $2` +
`) RETURNING id`
// run query
XOLog(sqlstr, auup.UserID, auup.PermissionID)
err = db.QueryRow(sqlstr, auup.UserID, auup.PermissionID).Scan(&auup.ID)
if err != nil {
return err
}
// set existence
auup._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authuseruserpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authuseruserpermission.xo.go#L98-L128 | go | train | // Upsert performs an upsert for AuthUserUserPermission.
//
// NOTE: PostgreSQL 9.5+ only | func (auup *AuthUserUserPermission) Upsert(db XODB) error | // Upsert performs an upsert for AuthUserUserPermission.
//
// NOTE: PostgreSQL 9.5+ only
func (auup *AuthUserUserPermission) Upsert(db XODB) error | {
var err error
// if already exist, bail
if auup._exists {
return errors.New("insert failed: already exists")
}
// sql query
const sqlstr = `INSERT INTO public.auth_user_user_permissions (` +
`id, user_id, permission_id` +
`) VALUES (` +
`$1, $2, $3` +
`) ON CONFLICT (id) DO UPDATE SET (` +
`id, user_id, permission_id` +
`) = (` +
`EXCLUDED.id, EXCLUDED.user_id, EXCLUDED.permission_id` +
`)`
// run query
XOLog(sqlstr, auup.ID, auup.UserID, auup.PermissionID)
_, err = db.Exec(sqlstr, auup.ID, auup.UserID, auup.PermissionID)
if err != nil {
return err
}
// set existence
auup._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authuseruserpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authuseruserpermission.xo.go#L131-L158 | go | train | // Delete deletes the AuthUserUserPermission from the database. | func (auup *AuthUserUserPermission) Delete(db XODB) error | // Delete deletes the AuthUserUserPermission from the database.
func (auup *AuthUserUserPermission) Delete(db XODB) error | {
var err error
// if doesn't exist, bail
if !auup._exists {
return nil
}
// if deleted, bail
if auup._deleted {
return nil
}
// sql query
const sqlstr = `DELETE FROM public.auth_user_user_permissions WHERE id = $1`
// run query
XOLog(sqlstr, auup.ID)
_, err = db.Exec(sqlstr, auup.ID)
if err != nil {
return err
}
// set deleted
auup._deleted = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authuseruserpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authuseruserpermission.xo.go#L255-L276 | go | train | // AuthUserUserPermissionByID retrieves a row from 'public.auth_user_user_permissions' as a AuthUserUserPermission.
//
// Generated from index 'auth_user_user_permissions_pkey'. | func AuthUserUserPermissionByID(db XODB, id int) (*AuthUserUserPermission, error) | // AuthUserUserPermissionByID retrieves a row from 'public.auth_user_user_permissions' as a AuthUserUserPermission.
//
// Generated from index 'auth_user_user_permissions_pkey'.
func AuthUserUserPermissionByID(db XODB, id int) (*AuthUserUserPermission, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, user_id, permission_id ` +
`FROM public.auth_user_user_permissions ` +
`WHERE id = $1`
// run query
XOLog(sqlstr, id)
auup := AuthUserUserPermission{
_exists: true,
}
err = db.QueryRow(sqlstr, id).Scan(&auup.ID, &auup.UserID, &auup.PermissionID)
if err != nil {
return nil, err
}
return &auup, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/authusergroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/authusergroup.xo.go#L29-L62 | go | train | // Insert inserts the AuthUserGroup to the database. | func (aug *AuthUserGroup) Insert(db XODB) error | // Insert inserts the AuthUserGroup to the database.
func (aug *AuthUserGroup) Insert(db XODB) error | {
var err error
// if already exist, bail
if aug._exists {
return errors.New("insert failed: already exists")
}
// sql query
const sqlstr = `INSERT INTO django.auth_user_groups (` +
`user_id, group_id` +
`) VALUES (` +
`:1, :2` +
`) RETURNING id /*lastInsertId*/ INTO :pk`
// run query
XOLog(sqlstr, aug.UserID, aug.GroupID, nil)
res, err := db.Exec(sqlstr, aug.UserID, aug.GroupID, nil)
if err != nil {
return err
}
// retrieve id
id, err := res.LastInsertId()
if err != nil {
return err
}
// set primary key and existence
aug.ID = float64(id)
aug._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/authusergroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/authusergroup.xo.go#L99-L126 | go | train | // Delete deletes the AuthUserGroup from the database. | func (aug *AuthUserGroup) Delete(db XODB) error | // Delete deletes the AuthUserGroup from the database.
func (aug *AuthUserGroup) Delete(db XODB) error | {
var err error
// if doesn't exist, bail
if !aug._exists {
return nil
}
// if deleted, bail
if aug._deleted {
return nil
}
// sql query
const sqlstr = `DELETE FROM django.auth_user_groups WHERE id = :1`
// run query
XOLog(sqlstr, aug.ID)
_, err = db.Exec(sqlstr, aug.ID)
if err != nil {
return err
}
// set deleted
aug._deleted = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/pgcatalog/ischema/sp_pgtruetypid.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/pgcatalog/ischema/sp_pgtruetypid.xo.go#L9-L24 | go | train | // Code generated by xo. DO NOT EDIT.
// PgTruetypid calls the stored procedure 'information_schema._pg_truetypid(pg_attribute, pg_type) oid' on db. | func PgTruetypid(db XODB, v0 pgtypes.PgAttribute, v1 pgtypes.PgType) (pgtypes.Oid, error) | // Code generated by xo. DO NOT EDIT.
// PgTruetypid calls the stored procedure 'information_schema._pg_truetypid(pg_attribute, pg_type) oid' on db.
func PgTruetypid(db XODB, v0 pgtypes.PgAttribute, v1 pgtypes.PgType) (pgtypes.Oid, error) | {
var err error
// sql query
const sqlstr = `SELECT information_schema._pg_truetypid($1, $2)`
// run query
var ret pgtypes.Oid
XOLog(sqlstr, v0, v1)
err = db.QueryRow(sqlstr, v0, v1).Scan(&ret)
if err != nil {
return pgtypes.Oid{}, err
}
return ret, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | models/myenumvalue.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/models/myenumvalue.xo.go#L12-L30 | go | train | // MyEnumValues runs a custom query, returning results as MyEnumValue. | func MyEnumValues(db XODB, schema string, enum string) (*MyEnumValue, error) | // MyEnumValues runs a custom query, returning results as MyEnumValue.
func MyEnumValues(db XODB, schema string, enum string) (*MyEnumValue, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`SUBSTRING(column_type, 6, CHAR_LENGTH(column_type) - 6) AS enum_values ` +
`FROM information_schema.columns ` +
`WHERE data_type = 'enum' AND table_schema = ? AND column_name = ?`
// run query
XOLog(sqlstr, schema, enum)
var mev MyEnumValue
err = db.QueryRow(sqlstr, schema, enum).Scan(&mev.EnumValues)
if err != nil {
return nil, err
}
return &mev, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authusergroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authusergroup.xo.go#L31-L57 | go | train | // Insert inserts the AuthUserGroup to the database. | func (aug *AuthUserGroup) Insert(db XODB) error | // Insert inserts the AuthUserGroup to the database.
func (aug *AuthUserGroup) Insert(db XODB) error | {
var err error
// if already exist, bail
if aug._exists {
return errors.New("insert failed: already exists")
}
// sql insert query, primary key provided by sequence
const sqlstr = `INSERT INTO public.auth_user_groups (` +
`user_id, group_id` +
`) VALUES (` +
`$1, $2` +
`) RETURNING id`
// run query
XOLog(sqlstr, aug.UserID, aug.GroupID)
err = db.QueryRow(sqlstr, aug.UserID, aug.GroupID).Scan(&aug.ID)
if err != nil {
return err
}
// set existence
aug._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authusergroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authusergroup.xo.go#L60-L84 | go | train | // Update updates the AuthUserGroup in the database. | func (aug *AuthUserGroup) Update(db XODB) error | // Update updates the AuthUserGroup in the database.
func (aug *AuthUserGroup) Update(db XODB) error | {
var err error
// if doesn't exist, bail
if !aug._exists {
return errors.New("update failed: does not exist")
}
// if deleted, bail
if aug._deleted {
return errors.New("update failed: marked for deletion")
}
// sql query
const sqlstr = `UPDATE public.auth_user_groups SET (` +
`user_id, group_id` +
`) = ( ` +
`$1, $2` +
`) WHERE id = $3`
// run query
XOLog(sqlstr, aug.UserID, aug.GroupID, aug.ID)
_, err = db.Exec(sqlstr, aug.UserID, aug.GroupID, aug.ID)
return err
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authusergroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authusergroup.xo.go#L98-L128 | go | train | // Upsert performs an upsert for AuthUserGroup.
//
// NOTE: PostgreSQL 9.5+ only | func (aug *AuthUserGroup) Upsert(db XODB) error | // Upsert performs an upsert for AuthUserGroup.
//
// NOTE: PostgreSQL 9.5+ only
func (aug *AuthUserGroup) Upsert(db XODB) error | {
var err error
// if already exist, bail
if aug._exists {
return errors.New("insert failed: already exists")
}
// sql query
const sqlstr = `INSERT INTO public.auth_user_groups (` +
`id, user_id, group_id` +
`) VALUES (` +
`$1, $2, $3` +
`) ON CONFLICT (id) DO UPDATE SET (` +
`id, user_id, group_id` +
`) = (` +
`EXCLUDED.id, EXCLUDED.user_id, EXCLUDED.group_id` +
`)`
// run query
XOLog(sqlstr, aug.ID, aug.UserID, aug.GroupID)
_, err = db.Exec(sqlstr, aug.ID, aug.UserID, aug.GroupID)
if err != nil {
return err
}
// set existence
aug._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | models/column.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/models/column.xo.go#L66-L104 | go | train | // MyTableColumns runs a custom query, returning results as Column. | func MyTableColumns(db XODB, schema string, table string) ([]*Column, error) | // MyTableColumns runs a custom query, returning results as Column.
func MyTableColumns(db XODB, schema string, table string) ([]*Column, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`ordinal_position AS field_ordinal, ` +
`column_name, ` +
`IF(data_type = 'enum', column_name, column_type) AS data_type, ` +
`IF(is_nullable = 'YES', false, true) AS not_null, ` +
`column_default AS default_value, ` +
`IF(column_key = 'PRI', true, false) AS is_primary_key ` +
`FROM information_schema.columns ` +
`WHERE table_schema = ? AND table_name = ? ` +
`ORDER BY ordinal_position`
// run query
XOLog(sqlstr, schema, table)
q, err := db.Query(sqlstr, schema, table)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*Column{}
for q.Next() {
c := Column{}
// scan
err = q.Scan(&c.FieldOrdinal, &c.ColumnName, &c.DataType, &c.NotNull, &c.DefaultValue, &c.IsPrimaryKey)
if err != nil {
return nil, err
}
res = append(res, &c)
}
return res, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/methods.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/methods.go#L48-L56 | go | train | // CheckAndSetDefaults checks and sets defaults | func (a *AuthenticateUserRequest) CheckAndSetDefaults() error | // CheckAndSetDefaults checks and sets defaults
func (a *AuthenticateUserRequest) CheckAndSetDefaults() error | {
if a.Username == "" {
return trace.BadParameter("missing parameter 'username'")
}
if a.Pass == nil && a.U2F == nil && a.OTP == nil && a.Session == nil {
return trace.BadParameter("at least one authentication method is required")
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/methods.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/methods.go#L85-L102 | go | train | // AuthenticateUser authenticates user based on the request type | func (s *AuthServer) AuthenticateUser(req AuthenticateUserRequest) error | // AuthenticateUser authenticates user based on the request type
func (s *AuthServer) AuthenticateUser(req AuthenticateUserRequest) error | {
err := s.authenticateUser(req)
if err != nil {
s.EmitAuditEvent(events.UserLocalLoginFailure, events.EventFields{
events.EventUser: req.Username,
events.LoginMethod: events.LoginMethodLocal,
events.AuthAttemptSuccess: false,
events.AuthAttemptErr: err.Error(),
})
} else {
s.EmitAuditEvent(events.UserLocalLogin, events.EventFields{
events.EventUser: req.Username,
events.LoginMethod: events.LoginMethodLocal,
events.AuthAttemptSuccess: true,
})
}
return err
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/methods.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/methods.go#L165-L188 | go | train | // AuthenticateWebUser authenticates web user, creates and returns web session
// in case if authentication is successful. In case if existing session id
// is used to authenticate, returns session associated with the existing session id
// instead of creating the new one | func (s *AuthServer) AuthenticateWebUser(req AuthenticateUserRequest) (services.WebSession, error) | // AuthenticateWebUser authenticates web user, creates and returns web session
// in case if authentication is successful. In case if existing session id
// is used to authenticate, returns session associated with the existing session id
// instead of creating the new one
func (s *AuthServer) AuthenticateWebUser(req AuthenticateUserRequest) (services.WebSession, error) | {
if req.Session != nil {
session, err := s.GetWebSession(req.Username, req.Session.ID)
if err != nil {
return nil, trace.AccessDenied("session is invalid or has expired")
}
return session, nil
}
if err := s.AuthenticateUser(req); err != nil {
return nil, trace.Wrap(err)
}
sess, err := s.NewWebSession(req.Username)
if err != nil {
return nil, trace.Wrap(err)
}
if err := s.UpsertWebSession(req.Username, sess); err != nil {
return nil, trace.Wrap(err)
}
sess, err = services.GetWebSessionMarshaler().GenerateWebSession(sess)
if err != nil {
return nil, trace.Wrap(err)
}
return sess, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/methods.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/methods.go#L203-L216 | go | train | // CheckAndSetDefaults checks and sets default certificate values | func (a *AuthenticateSSHRequest) CheckAndSetDefaults() error | // CheckAndSetDefaults checks and sets default certificate values
func (a *AuthenticateSSHRequest) CheckAndSetDefaults() error | {
if err := a.AuthenticateUserRequest.CheckAndSetDefaults(); err != nil {
return trace.Wrap(err)
}
if len(a.PublicKey) == 0 {
return trace.BadParameter("missing parameter 'public_key'")
}
certificateFormat, err := utils.CheckCertificateFormatFlag(a.CompatibilityMode)
if err != nil {
return trace.Wrap(err)
}
a.CompatibilityMode = certificateFormat
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/methods.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/methods.go#L247-L257 | go | train | // SSHCertPublicKeys returns a list of trusted host SSH certificate authority public keys | func (c *TrustedCerts) SSHCertPublicKeys() ([]ssh.PublicKey, error) | // SSHCertPublicKeys returns a list of trusted host SSH certificate authority public keys
func (c *TrustedCerts) SSHCertPublicKeys() ([]ssh.PublicKey, error) | {
out := make([]ssh.PublicKey, 0, len(c.HostCertificates))
for _, keyBytes := range c.HostCertificates {
publicKey, _, _, _, err := ssh.ParseAuthorizedKey(keyBytes)
if err != nil {
return nil, trace.Wrap(err)
}
out = append(out, publicKey)
}
return out, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/methods.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/methods.go#L260-L270 | go | train | // AuthoritiesToTrustedCerts serializes authorities to TrustedCerts data structure | func AuthoritiesToTrustedCerts(authorities []services.CertAuthority) []TrustedCerts | // AuthoritiesToTrustedCerts serializes authorities to TrustedCerts data structure
func AuthoritiesToTrustedCerts(authorities []services.CertAuthority) []TrustedCerts | {
out := make([]TrustedCerts, len(authorities))
for i, ca := range authorities {
out[i] = TrustedCerts{
ClusterName: ca.GetClusterName(),
HostCertificates: ca.GetCheckingKeys(),
TLSCertificates: services.TLSCerts(ca),
}
}
return out
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.