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/pgcatalog/pgcatalog/pgcatalog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/pgcatalog/pgcatalog/pgcatalog.xo.go#L44047-L44066 | go | train | // PgTsConfigByOid retrieves a row from 'pg_catalog.pg_ts_config' as a PgTsConfig.
//
// Generated from index 'pg_ts_config_oid_index'. | func PgTsConfigByOid(db XODB, oid pgtypes.Oid) (*PgTsConfig, error) | // PgTsConfigByOid retrieves a row from 'pg_catalog.pg_ts_config' as a PgTsConfig.
//
// Generated from index 'pg_ts_config_oid_index'.
func PgTsConfigByOid(db XODB, oid pgtypes.Oid) (*PgTsConfig, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`tableoid, cmax, xmax, cmin, xmin, oid, ctid, cfgname, cfgnamespace, cfgowner, cfgparser ` +
`FROM pg_catalog.pg_ts_config ` +
`WHERE oid = $1`
// run query
XOLog(sqlstr, oid)
ptc := PgTsConfig{}
err = db.QueryRow(sqlstr, oid).Scan(&ptc.Tableoid, &ptc.Cmax, &ptc.Xmax, &ptc.Cmin, &ptc.Xmin, &ptc.Oid, &ptc.Ctid, &ptc.Cfgname, &ptc.Cfgnamespace, &ptc.Cfgowner, &ptc.Cfgparser)
if err != nil {
return nil, err
}
return &ptc, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/pgcatalog/pgcatalog/pgcatalog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/pgcatalog/pgcatalog/pgcatalog.xo.go#L44071-L44090 | go | train | // PgTsConfigMapByMapcfgMaptokentypeMapseqno retrieves a row from 'pg_catalog.pg_ts_config_map' as a PgTsConfigMap.
//
// Generated from index 'pg_ts_config_map_index'. | func PgTsConfigMapByMapcfgMaptokentypeMapseqno(db XODB, mapcfg pgtypes.Oid, maptokentype int, mapseqno int) (*PgTsConfigMap, error) | // PgTsConfigMapByMapcfgMaptokentypeMapseqno retrieves a row from 'pg_catalog.pg_ts_config_map' as a PgTsConfigMap.
//
// Generated from index 'pg_ts_config_map_index'.
func PgTsConfigMapByMapcfgMaptokentypeMapseqno(db XODB, mapcfg pgtypes.Oid, maptokentype int, mapseqno int) (*PgTsConfigMap, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`tableoid, cmax, xmax, cmin, xmin, ctid, mapcfg, maptokentype, mapseqno, mapdict ` +
`FROM pg_catalog.pg_ts_config_map ` +
`WHERE mapcfg = $1 AND maptokentype = $2 AND mapseqno = $3`
// run query
XOLog(sqlstr, mapcfg, maptokentype, mapseqno)
ptcm := PgTsConfigMap{}
err = db.QueryRow(sqlstr, mapcfg, maptokentype, mapseqno).Scan(&ptcm.Tableoid, &ptcm.Cmax, &ptcm.Xmax, &ptcm.Cmin, &ptcm.Xmin, &ptcm.Ctid, &ptcm.Mapcfg, &ptcm.Maptokentype, &ptcm.Mapseqno, &ptcm.Mapdict)
if err != nil {
return nil, err
}
return &ptcm, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/pgcatalog/pgcatalog/pgcatalog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/pgcatalog/pgcatalog/pgcatalog.xo.go#L44095-L44114 | go | train | // PgTsDictByDictnameDictnamespace retrieves a row from 'pg_catalog.pg_ts_dict' as a PgTsDict.
//
// Generated from index 'pg_ts_dict_dictname_index'. | func PgTsDictByDictnameDictnamespace(db XODB, dictname pgtypes.Name, dictnamespace pgtypes.Oid) (*PgTsDict, error) | // PgTsDictByDictnameDictnamespace retrieves a row from 'pg_catalog.pg_ts_dict' as a PgTsDict.
//
// Generated from index 'pg_ts_dict_dictname_index'.
func PgTsDictByDictnameDictnamespace(db XODB, dictname pgtypes.Name, dictnamespace pgtypes.Oid) (*PgTsDict, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`tableoid, cmax, xmax, cmin, xmin, oid, ctid, dictname, dictnamespace, dictowner, dicttemplate, dictinitoption ` +
`FROM pg_catalog.pg_ts_dict ` +
`WHERE dictname = $1 AND dictnamespace = $2`
// run query
XOLog(sqlstr, dictname, dictnamespace)
ptd := PgTsDict{}
err = db.QueryRow(sqlstr, dictname, dictnamespace).Scan(&ptd.Tableoid, &ptd.Cmax, &ptd.Xmax, &ptd.Cmin, &ptd.Xmin, &ptd.Oid, &ptd.Ctid, &ptd.Dictname, &ptd.Dictnamespace, &ptd.Dictowner, &ptd.Dicttemplate, &ptd.Dictinitoption)
if err != nil {
return nil, err
}
return &ptd, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/pgcatalog/pgcatalog/pgcatalog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/pgcatalog/pgcatalog/pgcatalog.xo.go#L44143-L44162 | go | train | // PgTsParserByOid retrieves a row from 'pg_catalog.pg_ts_parser' as a PgTsParser.
//
// Generated from index 'pg_ts_parser_oid_index'. | func PgTsParserByOid(db XODB, oid pgtypes.Oid) (*PgTsParser, error) | // PgTsParserByOid retrieves a row from 'pg_catalog.pg_ts_parser' as a PgTsParser.
//
// Generated from index 'pg_ts_parser_oid_index'.
func PgTsParserByOid(db XODB, oid pgtypes.Oid) (*PgTsParser, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`tableoid, cmax, xmax, cmin, xmin, oid, ctid, prsname, prsnamespace, prsstart, prstoken, prsend, prsheadline, prslextype ` +
`FROM pg_catalog.pg_ts_parser ` +
`WHERE oid = $1`
// run query
XOLog(sqlstr, oid)
ptp := PgTsParser{}
err = db.QueryRow(sqlstr, oid).Scan(&ptp.Tableoid, &ptp.Cmax, &ptp.Xmax, &ptp.Cmin, &ptp.Xmin, &ptp.Oid, &ptp.Ctid, &ptp.Prsname, &ptp.Prsnamespace, &ptp.Prsstart, &ptp.Prstoken, &ptp.Prsend, &ptp.Prsheadline, &ptp.Prslextype)
if err != nil {
return nil, err
}
return &ptp, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/pgcatalog/pgcatalog/pgcatalog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/pgcatalog/pgcatalog/pgcatalog.xo.go#L44191-L44210 | go | train | // PgTsTemplateByOid retrieves a row from 'pg_catalog.pg_ts_template' as a PgTsTemplate.
//
// Generated from index 'pg_ts_template_oid_index'. | func PgTsTemplateByOid(db XODB, oid pgtypes.Oid) (*PgTsTemplate, error) | // PgTsTemplateByOid retrieves a row from 'pg_catalog.pg_ts_template' as a PgTsTemplate.
//
// Generated from index 'pg_ts_template_oid_index'.
func PgTsTemplateByOid(db XODB, oid pgtypes.Oid) (*PgTsTemplate, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`tableoid, cmax, xmax, cmin, xmin, oid, ctid, tmplname, tmplnamespace, tmplinit, tmpllexize ` +
`FROM pg_catalog.pg_ts_template ` +
`WHERE oid = $1`
// run query
XOLog(sqlstr, oid)
ptt := PgTsTemplate{}
err = db.QueryRow(sqlstr, oid).Scan(&ptt.Tableoid, &ptt.Cmax, &ptt.Xmax, &ptt.Cmin, &ptt.Xmin, &ptt.Oid, &ptt.Ctid, &ptt.Tmplname, &ptt.Tmplnamespace, &ptt.Tmplinit, &ptt.Tmpllexize)
if err != nil {
return nil, err
}
return &ptt, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/pgcatalog/pgcatalog/pgcatalog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/pgcatalog/pgcatalog/pgcatalog.xo.go#L44215-L44234 | go | train | // PgTsTemplateByTmplnameTmplnamespace retrieves a row from 'pg_catalog.pg_ts_template' as a PgTsTemplate.
//
// Generated from index 'pg_ts_template_tmplname_index'. | func PgTsTemplateByTmplnameTmplnamespace(db XODB, tmplname pgtypes.Name, tmplnamespace pgtypes.Oid) (*PgTsTemplate, error) | // PgTsTemplateByTmplnameTmplnamespace retrieves a row from 'pg_catalog.pg_ts_template' as a PgTsTemplate.
//
// Generated from index 'pg_ts_template_tmplname_index'.
func PgTsTemplateByTmplnameTmplnamespace(db XODB, tmplname pgtypes.Name, tmplnamespace pgtypes.Oid) (*PgTsTemplate, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`tableoid, cmax, xmax, cmin, xmin, oid, ctid, tmplname, tmplnamespace, tmplinit, tmpllexize ` +
`FROM pg_catalog.pg_ts_template ` +
`WHERE tmplname = $1 AND tmplnamespace = $2`
// run query
XOLog(sqlstr, tmplname, tmplnamespace)
ptt := PgTsTemplate{}
err = db.QueryRow(sqlstr, tmplname, tmplnamespace).Scan(&ptt.Tableoid, &ptt.Cmax, &ptt.Xmax, &ptt.Cmin, &ptt.Xmin, &ptt.Oid, &ptt.Ctid, &ptt.Tmplname, &ptt.Tmplnamespace, &ptt.Tmplinit, &ptt.Tmpllexize)
if err != nil {
return nil, err
}
return &ptt, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/pgcatalog/pgcatalog/pgcatalog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/pgcatalog/pgcatalog/pgcatalog.xo.go#L44239-L44258 | go | train | // PgTypeByOid retrieves a row from 'pg_catalog.pg_type' as a PgType.
//
// Generated from index 'pg_type_oid_index'. | func PgTypeByOid(db XODB, oid pgtypes.Oid) (*PgType, error) | // PgTypeByOid retrieves a row from 'pg_catalog.pg_type' as a PgType.
//
// Generated from index 'pg_type_oid_index'.
func PgTypeByOid(db XODB, oid pgtypes.Oid) (*PgType, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`tableoid, cmax, xmax, cmin, xmin, oid, ctid, typname, typnamespace, typowner, typlen, typbyval, typtype, typcategory, typispreferred, typisdefined, typdelim, typrelid, typelem, typarray, typinput, typoutput, typreceive, typsend, typmodin, typmodout, typanalyze, typalign, typstorage, typnotnull, typbasetype, typtypmod, typndims, typcollation, typdefaultbin, typdefault, typacl ` +
`FROM pg_catalog.pg_type ` +
`WHERE oid = $1`
// run query
XOLog(sqlstr, oid)
pt := PgType{}
err = db.QueryRow(sqlstr, oid).Scan(&pt.Tableoid, &pt.Cmax, &pt.Xmax, &pt.Cmin, &pt.Xmin, &pt.Oid, &pt.Ctid, &pt.Typname, &pt.Typnamespace, &pt.Typowner, &pt.Typlen, &pt.Typbyval, &pt.Typtype, &pt.Typcategory, &pt.Typispreferred, &pt.Typisdefined, &pt.Typdelim, &pt.Typrelid, &pt.Typelem, &pt.Typarray, &pt.Typinput, &pt.Typoutput, &pt.Typreceive, &pt.Typsend, &pt.Typmodin, &pt.Typmodout, &pt.Typanalyze, &pt.Typalign, &pt.Typstorage, &pt.Typnotnull, &pt.Typbasetype, &pt.Typtypmod, &pt.Typndims, &pt.Typcollation, &pt.Typdefaultbin, &pt.Typdefault, &pt.Typacl)
if err != nil {
return nil, err
}
return &pt, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/pgcatalog/pgcatalog/pgcatalog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/pgcatalog/pgcatalog/pgcatalog.xo.go#L44287-L44306 | go | train | // PgUserMappingByOid retrieves a row from 'pg_catalog.pg_user_mapping' as a PgUserMapping.
//
// Generated from index 'pg_user_mapping_oid_index'. | func PgUserMappingByOid(db XODB, oid pgtypes.Oid) (*PgUserMapping, error) | // PgUserMappingByOid retrieves a row from 'pg_catalog.pg_user_mapping' as a PgUserMapping.
//
// Generated from index 'pg_user_mapping_oid_index'.
func PgUserMappingByOid(db XODB, oid pgtypes.Oid) (*PgUserMapping, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`tableoid, cmax, xmax, cmin, xmin, oid, ctid, umuser, umserver, umoptions ` +
`FROM pg_catalog.pg_user_mapping ` +
`WHERE oid = $1`
// run query
XOLog(sqlstr, oid)
pum := PgUserMapping{}
err = db.QueryRow(sqlstr, oid).Scan(&pum.Tableoid, &pum.Cmax, &pum.Xmax, &pum.Cmin, &pum.Xmin, &pum.Oid, &pum.Ctid, &pum.Umuser, &pum.Umserver, &pum.Umoptions)
if err != nil {
return nil, err
}
return &pum, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/pgcatalog/pgcatalog/pgcatalog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/pgcatalog/pgcatalog/pgcatalog.xo.go#L44359-L44389 | go | train | // Scan satisfies the sql.Scanner interface for StringSlice. | func (ss *StringSlice) Scan(src interface{}) error | // Scan satisfies the sql.Scanner interface for StringSlice.
func (ss *StringSlice) Scan(src interface{}) error | {
buf, ok := src.([]byte)
if !ok {
return errors.New("invalid StringSlice")
}
// change quote escapes for csv parser
str := quoteEscapeRegex.ReplaceAllString(string(buf), `$1""`)
str = strings.Replace(str, `\\`, `\`, -1)
// remove braces
str = str[1 : len(str)-1]
// bail if only one
if len(str) == 0 {
*ss = StringSlice([]string{})
return nil
}
// parse with csv reader
cr := csv.NewReader(strings.NewReader(str))
slice, err := cr.Read()
if err != nil {
fmt.Printf("exiting!: %v\n", err)
return err
}
*ss = StringSlice(slice)
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/pgcatalog/pgcatalog/pgcatalog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/pgcatalog/pgcatalog/pgcatalog.xo.go#L44392-L44398 | go | train | // Value satisfies the driver.Valuer interface for StringSlice. | func (ss StringSlice) Value() (driver.Value, error) | // Value satisfies the driver.Valuer interface for StringSlice.
func (ss StringSlice) Value() (driver.Value, error) | {
v := make([]string, len(ss))
for i, s := range ss {
v[i] = `"` + strings.Replace(strings.Replace(s, `\`, `\\\`, -1), `"`, `\"`, -1) + `"`
}
return "{" + strings.Join(v, ",") + "}", nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/mysql/djangocontenttype.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/mysql/djangocontenttype.xo.go#L92-L98 | go | train | // Save saves the DjangoContentType to the database. | func (dct *DjangoContentType) Save(db XODB) error | // Save saves the DjangoContentType to the database.
func (dct *DjangoContentType) Save(db XODB) error | {
if dct.Exists() {
return dct.Update(db)
}
return dct.Insert(db)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/mysql/djangocontenttype.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/mysql/djangocontenttype.xo.go#L133-L154 | go | train | // DjangoContentTypeByAppLabelModel retrieves a row from 'django.django_content_type' as a DjangoContentType.
//
// Generated from index 'django_content_type_app_label_76bd3d3b_uniq'. | func DjangoContentTypeByAppLabelModel(db XODB, appLabel string, model string) (*DjangoContentType, error) | // DjangoContentTypeByAppLabelModel retrieves a row from 'django.django_content_type' as a DjangoContentType.
//
// Generated from index 'django_content_type_app_label_76bd3d3b_uniq'.
func DjangoContentTypeByAppLabelModel(db XODB, appLabel string, model string) (*DjangoContentType, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, app_label, model ` +
`FROM django.django_content_type ` +
`WHERE app_label = ? AND model = ?`
// run query
XOLog(sqlstr, appLabel, model)
dct := DjangoContentType{
_exists: true,
}
err = db.QueryRow(sqlstr, appLabel, model).Scan(&dct.ID, &dct.AppLabel, &dct.Model)
if err != nil {
return nil, err
}
return &dct, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/mysql/authgroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/mysql/authgroup.xo.go#L91-L97 | go | train | // Save saves the AuthGroup to the database. | func (ag *AuthGroup) Save(db XODB) error | // Save saves the AuthGroup to the database.
func (ag *AuthGroup) Save(db XODB) error | {
if ag.Exists() {
return ag.Update(db)
}
return ag.Insert(db)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/mysql/authgroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/mysql/authgroup.xo.go#L132-L153 | go | train | // AuthGroupByID retrieves a row from 'django.auth_group' as a AuthGroup.
//
// Generated from index 'auth_group_id_pkey'. | func AuthGroupByID(db XODB, id int) (*AuthGroup, error) | // AuthGroupByID retrieves a row from 'django.auth_group' as a AuthGroup.
//
// Generated from index 'auth_group_id_pkey'.
func AuthGroupByID(db XODB, id int) (*AuthGroup, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, name ` +
`FROM django.auth_group ` +
`WHERE id = ?`
// run query
XOLog(sqlstr, id)
ag := AuthGroup{
_exists: true,
}
err = db.QueryRow(sqlstr, id).Scan(&ag.ID, &ag.Name)
if err != nil {
return nil, err
}
return &ag, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/djangosession.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/djangosession.xo.go#L33-L66 | go | train | // Insert inserts the DjangoSession to the database. | func (ds *DjangoSession) Insert(db XODB) error | // Insert inserts the DjangoSession to the database.
func (ds *DjangoSession) Insert(db XODB) error | {
var err error
// if already exist, bail
if ds._exists {
return errors.New("insert failed: already exists")
}
// sql query
const sqlstr = `INSERT INTO django.django_session (` +
`session_data, expire_date` +
`) VALUES (` +
`:1, :2` +
`) RETURNING session_key /*lastInsertId*/ INTO :pk`
// run query
XOLog(sqlstr, ds.SessionData, ds.ExpireDate, nil)
res, err := db.Exec(sqlstr, ds.SessionData, ds.ExpireDate, nil)
if err != nil {
return err
}
// retrieve id
id, err := res.LastInsertId()
if err != nil {
return err
}
// set primary key and existence
ds.SessionKey = string(id)
ds._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/djangosession.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/djangosession.xo.go#L94-L100 | go | train | // Save saves the DjangoSession to the database. | func (ds *DjangoSession) Save(db XODB) error | // Save saves the DjangoSession to the database.
func (ds *DjangoSession) Save(db XODB) error | {
if ds.Exists() {
return ds.Update(db)
}
return ds.Insert(db)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/djangosession.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/djangosession.xo.go#L103-L130 | go | train | // Delete deletes the DjangoSession from the database. | func (ds *DjangoSession) Delete(db XODB) error | // Delete deletes the DjangoSession from the database.
func (ds *DjangoSession) Delete(db XODB) error | {
var err error
// if doesn't exist, bail
if !ds._exists {
return nil
}
// if deleted, bail
if ds._deleted {
return nil
}
// sql query
const sqlstr = `DELETE FROM django.django_session WHERE session_key = :1`
// run query
XOLog(sqlstr, ds.SessionKey)
_, err = db.Exec(sqlstr, ds.SessionKey)
if err != nil {
return err
}
// set deleted
ds._deleted = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/authpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/authpermission.xo.go#L94-L100 | go | train | // Save saves the AuthPermission to the database. | func (ap *AuthPermission) Save(db XODB) error | // Save saves the AuthPermission to the database.
func (ap *AuthPermission) Save(db XODB) error | {
if ap.Exists() {
return ap.Update(db)
}
return ap.Insert(db)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/authpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/authpermission.xo.go#L135-L137 | go | train | // DjangoContentType returns the DjangoContentType associated with the AuthPermission's ContentTypeID (content_type_id).
//
// Generated from foreign key 'cca0f0681577d4054ed10f5351689a'. | func (ap *AuthPermission) DjangoContentType(db XODB) (*DjangoContentType, error) | // DjangoContentType returns the DjangoContentType associated with the AuthPermission's ContentTypeID (content_type_id).
//
// Generated from foreign key 'cca0f0681577d4054ed10f5351689a'.
func (ap *AuthPermission) DjangoContentType(db XODB) (*DjangoContentType, error) | {
return DjangoContentTypeByID(db, ap.ContentTypeID)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/authpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/authpermission.xo.go#L142-L176 | go | train | // AuthPermissionsByContentTypeID retrieves a row from 'django.auth_permission' as a AuthPermission.
//
// Generated from index 'auth_permission_417f1b1c'. | func AuthPermissionsByContentTypeID(db XODB, contentTypeID float64) ([]*AuthPermission, error) | // AuthPermissionsByContentTypeID retrieves a row from 'django.auth_permission' as a AuthPermission.
//
// Generated from index 'auth_permission_417f1b1c'.
func AuthPermissionsByContentTypeID(db XODB, contentTypeID float64) ([]*AuthPermission, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, name, content_type_id, codename ` +
`FROM django.auth_permission ` +
`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 := []*AuthPermission{}
for q.Next() {
ap := AuthPermission{
_exists: true,
}
// scan
err = q.Scan(&ap.ID, &ap.Name, &ap.ContentTypeID, &ap.Codename)
if err != nil {
return nil, err
}
res = append(res, &ap)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | models/pgcolorder.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/models/pgcolorder.xo.go#L12-L33 | go | train | // PgGetColOrder runs a custom query, returning results as PgColOrder. | func PgGetColOrder(db XODB, schema string, index string) (*PgColOrder, error) | // PgGetColOrder runs a custom query, returning results as PgColOrder.
func PgGetColOrder(db XODB, schema string, index string) (*PgColOrder, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`i.indkey ` + // ::varchar AS ord
`FROM pg_index i ` +
`JOIN ONLY pg_class c ON c.oid = i.indrelid ` +
`JOIN ONLY pg_namespace n ON n.oid = c.relnamespace ` +
`JOIN ONLY pg_class ic ON ic.oid = i.indexrelid ` +
`WHERE n.nspname = $1 AND ic.relname = $2`
// run query
XOLog(sqlstr, schema, index)
var pco PgColOrder
err = db.QueryRow(sqlstr, schema, index).Scan(&pco.Ord)
if err != nil {
return nil, err
}
return &pco, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/funcs.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/funcs.go#L14-L37 | go | train | // NewTemplateFuncs returns a set of template funcs bound to the supplied args. | func (a *ArgType) NewTemplateFuncs() template.FuncMap | // NewTemplateFuncs returns a set of template funcs bound to the supplied args.
func (a *ArgType) NewTemplateFuncs() template.FuncMap | {
return template.FuncMap{
"colcount": a.colcount,
"colnames": a.colnames,
"colnamesmulti": a.colnamesmulti,
"colnamesquery": a.colnamesquery,
"colnamesquerymulti": a.colnamesquerymulti,
"colprefixnames": a.colprefixnames,
"colvals": a.colvals,
"colvalsmulti": a.colvalsmulti,
"fieldnames": a.fieldnames,
"fieldnamesmulti": a.fieldnamesmulti,
"goparamlist": a.goparamlist,
"reniltype": a.reniltype,
"retype": a.retype,
"shortname": a.shortname,
"convext": a.convext,
"schema": a.schemafn,
"colname": a.colname,
"hascolumn": a.hascolumn,
"hasfield": a.hasfield,
"getstartcount": a.getstartcount,
}
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/funcs.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/funcs.go#L41-L62 | go | train | // retype checks typ against known types, and prefixing
// ArgType.CustomTypePackage (if applicable). | func (a *ArgType) retype(typ string) string | // retype checks typ against known types, and prefixing
// ArgType.CustomTypePackage (if applicable).
func (a *ArgType) retype(typ string) string | {
if strings.Contains(typ, ".") {
return typ
}
prefix := ""
for strings.HasPrefix(typ, "[]") {
typ = typ[2:]
prefix = prefix + "[]"
}
if _, ok := a.KnownTypeMap[typ]; !ok {
pkg := a.CustomTypePackage
if pkg != "" {
pkg = pkg + "."
}
return prefix + pkg + typ
}
return prefix + typ
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/funcs.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/funcs.go#L66-L85 | go | train | // reniltype checks typ against known nil types (similar to retype), prefixing
// ArgType.CustomTypePackage (if applicable). | func (a *ArgType) reniltype(typ string) string | // reniltype checks typ against known nil types (similar to retype), prefixing
// ArgType.CustomTypePackage (if applicable).
func (a *ArgType) reniltype(typ string) string | {
if strings.Contains(typ, ".") {
return typ
}
if strings.HasSuffix(typ, "{}") {
if _, ok := a.KnownTypeMap[typ[:len(typ)-2]]; ok {
return typ
}
pkg := a.CustomTypePackage
if pkg != "" {
pkg = pkg + "."
}
return pkg + typ
}
return typ
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/funcs.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/funcs.go#L103-L166 | go | train | // shortname generates a safe Go identifier for typ. typ is first checked
// against ArgType.ShortNameTypeMap, and if not found, then the value is
// calculated and stored in the ShortNameTypeMap for future use.
//
// A shortname is the concatentation of the lowercase of the first character in
// the words comprising the name. For example, "MyCustomName" will have have
// the shortname of "mcn".
//
// If a generated shortname conflicts with a Go reserved name, then the
// corresponding value in goReservedNames map will be used.
//
// Generated shortnames that have conflicts with any scopeConflicts member will
// have ArgType.NameConflictSuffix appended.
//
// Note: recognized types for scopeConflicts are string, []*Field,
// []*QueryParam. | func (a *ArgType) shortname(typ string, scopeConflicts ...interface{}) string | // shortname generates a safe Go identifier for typ. typ is first checked
// against ArgType.ShortNameTypeMap, and if not found, then the value is
// calculated and stored in the ShortNameTypeMap for future use.
//
// A shortname is the concatentation of the lowercase of the first character in
// the words comprising the name. For example, "MyCustomName" will have have
// the shortname of "mcn".
//
// If a generated shortname conflicts with a Go reserved name, then the
// corresponding value in goReservedNames map will be used.
//
// Generated shortnames that have conflicts with any scopeConflicts member will
// have ArgType.NameConflictSuffix appended.
//
// Note: recognized types for scopeConflicts are string, []*Field,
// []*QueryParam.
func (a *ArgType) shortname(typ string, scopeConflicts ...interface{}) string | {
var v string
var ok bool
// check short name map
if v, ok = a.ShortNameTypeMap[typ]; !ok {
// calc the short name
u := []string{}
for _, s := range strings.Split(strings.ToLower(snaker.CamelToSnake(typ)), "_") {
if len(s) > 0 && s != "id" {
u = append(u, s[:1])
}
}
v = strings.Join(u, "")
// check go reserved names
if n, ok := goReservedNames[v]; ok {
v = n
}
// store back to short name map
a.ShortNameTypeMap[typ] = v
}
// initial conflicts are the default imported packages from
// xo_package.go.tpl
conflicts := map[string]bool{
"sql": true,
"driver": true,
"csv": true,
"errors": true,
"fmt": true,
"regexp": true,
"strings": true,
"time": true,
}
// add scopeConflicts to conflicts
for _, c := range scopeConflicts {
switch k := c.(type) {
case string:
conflicts[k] = true
case []*Field:
for _, f := range k {
conflicts[f.Name] = true
}
case []*QueryParam:
for _, f := range k {
conflicts[f.Name] = true
}
default:
panic("not implemented")
}
}
// append suffix if conflict exists
if _, ok := conflicts[v]; ok {
v = v + a.NameConflictSuffix
}
return v
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/funcs.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/funcs.go#L174-L195 | go | train | // colnames creates a list of the column names found in fields, excluding any
// Field with Name contained in ignoreNames.
//
// Used to present a comma separated list of column names, that can be used in
// a SELECT, or UPDATE, or other SQL clause requiring an list of identifiers
// (ie, "field_1, field_2, field_3, ..."). | func (a *ArgType) colnames(fields []*Field, ignoreNames ...string) string | // colnames creates a list of the column names found in fields, excluding any
// Field with Name contained in ignoreNames.
//
// Used to present a comma separated list of column names, that can be used in
// a SELECT, or UPDATE, or other SQL clause requiring an list of identifiers
// (ie, "field_1, field_2, field_3, ...").
func (a *ArgType) colnames(fields []*Field, ignoreNames ...string) string | {
ignore := map[string]bool{}
for _, n := range ignoreNames {
ignore[n] = true
}
str := ""
i := 0
for _, f := range fields {
if ignore[f.Name] {
continue
}
if i != 0 {
str = str + ", "
}
str = str + a.colname(f.Col)
i++
}
return str
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/funcs.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/funcs.go#L232-L253 | go | train | // colnamesquery creates a list of the column names in fields as a query and
// joined by sep, excluding any Field with Name contained in ignoreNames.
//
// Used to create a list of column names in a WHERE clause (ie, "field_1 = $1
// AND field_2 = $2 AND ...") or in an UPDATE clause (ie, "field = $1, field =
// $2, ..."). | func (a *ArgType) colnamesquery(fields []*Field, sep string, ignoreNames ...string) string | // colnamesquery creates a list of the column names in fields as a query and
// joined by sep, excluding any Field with Name contained in ignoreNames.
//
// Used to create a list of column names in a WHERE clause (ie, "field_1 = $1
// AND field_2 = $2 AND ...") or in an UPDATE clause (ie, "field = $1, field =
// $2, ...").
func (a *ArgType) colnamesquery(fields []*Field, sep string, ignoreNames ...string) string | {
ignore := map[string]bool{}
for _, n := range ignoreNames {
ignore[n] = true
}
str := ""
i := 0
for _, f := range fields {
if ignore[f.Name] {
continue
}
if i != 0 {
str = str + sep
}
str = str + a.colname(f.Col) + " = " + a.Loader.NthParam(i)
i++
}
return str
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/funcs.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/funcs.go#L261-L282 | go | train | // colnamesquerymulti creates a list of the column names in fields as a query and
// joined by sep, excluding any Field with Name contained in the slice of fields in ignoreNames.
//
// Used to create a list of column names in a WHERE clause (ie, "field_1 = $1
// AND field_2 = $2 AND ...") or in an UPDATE clause (ie, "field = $1, field =
// $2, ..."). | func (a *ArgType) colnamesquerymulti(fields []*Field, sep string, startCount int, ignoreNames []*Field) string | // colnamesquerymulti creates a list of the column names in fields as a query and
// joined by sep, excluding any Field with Name contained in the slice of fields in ignoreNames.
//
// Used to create a list of column names in a WHERE clause (ie, "field_1 = $1
// AND field_2 = $2 AND ...") or in an UPDATE clause (ie, "field = $1, field =
// $2, ...").
func (a *ArgType) colnamesquerymulti(fields []*Field, sep string, startCount int, ignoreNames []*Field) string | {
ignore := map[string]bool{}
for _, f := range ignoreNames {
ignore[f.Name] = true
}
str := ""
i := startCount
for _, f := range fields {
if ignore[f.Name] {
continue
}
if i > startCount {
str = str + sep
}
str = str + a.colname(f.Col) + " = " + a.Loader.NthParam(i)
i++
}
return str
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/funcs.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/funcs.go#L317-L338 | go | train | // colvals creates a list of value place holders for fields excluding any Field
// with Name contained in ignoreNames.
//
// Used to present a comma separated list of column place holders, used in a
// SELECT or UPDATE statement (ie, "$1, $2, $3 ..."). | func (a *ArgType) colvals(fields []*Field, ignoreNames ...string) string | // colvals creates a list of value place holders for fields excluding any Field
// with Name contained in ignoreNames.
//
// Used to present a comma separated list of column place holders, used in a
// SELECT or UPDATE statement (ie, "$1, $2, $3 ...").
func (a *ArgType) colvals(fields []*Field, ignoreNames ...string) string | {
ignore := map[string]bool{}
for _, n := range ignoreNames {
ignore[n] = true
}
str := ""
i := 0
for _, f := range fields {
if ignore[f.Name] {
continue
}
if i != 0 {
str = str + ", "
}
str = str + a.Loader.NthParam(i)
i++
}
return str
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/funcs.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/funcs.go#L429-L444 | go | train | // colcount returns the 1-based count of fields, excluding any Field with Name
// contained in ignoreNames.
//
// Used to get the count of fields, and useful for specifying the last SQL
// parameter. | func (a *ArgType) colcount(fields []*Field, ignoreNames ...string) int | // colcount returns the 1-based count of fields, excluding any Field with Name
// contained in ignoreNames.
//
// Used to get the count of fields, and useful for specifying the last SQL
// parameter.
func (a *ArgType) colcount(fields []*Field, ignoreNames ...string) int | {
ignore := map[string]bool{}
for _, n := range ignoreNames {
ignore[n] = true
}
i := 1
for _, f := range fields {
if ignore[f.Name] {
continue
}
i++
}
return i
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/funcs.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/funcs.go#L509-L551 | go | train | // goparamlist converts a list of fields into their named Go parameters,
// skipping any Field with Name contained in ignoreNames. addType will cause
// the go Type to be added after each variable name. addPrefix will cause the
// returned string to be prefixed with ", " if the generated string is not
// empty.
//
// Any field name encountered will be checked against goReservedNames, and will
// have its name substituted by its corresponding looked up value.
//
// Used to present a comma separated list of Go variable names for use with as
// either a Go func parameter list, or in a call to another Go func.
// (ie, ", a, b, c, ..." or ", a T1, b T2, c T3, ..."). | func (a *ArgType) goparamlist(fields []*Field, addPrefix bool, addType bool, ignoreNames ...string) string | // goparamlist converts a list of fields into their named Go parameters,
// skipping any Field with Name contained in ignoreNames. addType will cause
// the go Type to be added after each variable name. addPrefix will cause the
// returned string to be prefixed with ", " if the generated string is not
// empty.
//
// Any field name encountered will be checked against goReservedNames, and will
// have its name substituted by its corresponding looked up value.
//
// Used to present a comma separated list of Go variable names for use with as
// either a Go func parameter list, or in a call to another Go func.
// (ie, ", a, b, c, ..." or ", a T1, b T2, c T3, ...").
func (a *ArgType) goparamlist(fields []*Field, addPrefix bool, addType bool, ignoreNames ...string) string | {
ignore := map[string]bool{}
for _, n := range ignoreNames {
ignore[n] = true
}
i := 0
vals := []string{}
for _, f := range fields {
if ignore[f.Name] {
continue
}
s := "v" + strconv.Itoa(i)
if len(f.Name) > 0 {
n := strings.Split(snaker.CamelToSnake(f.Name), "_")
s = strings.ToLower(n[0]) + f.Name[len(n[0]):]
}
// check go reserved names
if r, ok := goReservedNames[strings.ToLower(s)]; ok {
s = r
}
// add the go type
if addType {
s += " " + a.retype(f.Type)
}
// add to vals
vals = append(vals, s)
i++
}
// concat generated values
str := strings.Join(vals, ", ")
if addPrefix && str != "" {
return ", " + str
}
return str
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/funcs.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/funcs.go#L557-L574 | go | train | // convext generates the Go conversion for f in order for it to be assignable
// to t.
//
// FIXME: this should be a better name, like "goconversion" or some such. | func (a *ArgType) convext(prefix string, f *Field, t *Field) string | // convext generates the Go conversion for f in order for it to be assignable
// to t.
//
// FIXME: this should be a better name, like "goconversion" or some such.
func (a *ArgType) convext(prefix string, f *Field, t *Field) string | {
expr := prefix + "." + f.Name
if f.Type == t.Type {
return expr
}
ft := f.Type
if strings.HasPrefix(ft, "sql.Null") {
expr = expr + "." + f.Type[8:]
ft = strings.ToLower(f.Type[8:])
}
if t.Type != ft {
expr = t.Type + "(" + expr + ")"
}
return expr
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/funcs.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/funcs.go#L577-L599 | go | train | // schemafn takes a series of names and joins them with the schema name. | func (a *ArgType) schemafn(s string, names ...string) string | // schemafn takes a series of names and joins them with the schema name.
func (a *ArgType) schemafn(s string, names ...string) string | {
// escape table names
if a.EscapeTableNames {
for i, t := range names {
names[i] = a.Loader.Escape(TableEsc, t)
}
}
n := strings.Join(names, ".")
if s == "" && n == "" {
return ""
}
if s != "" && n != "" {
if a.EscapeSchemaName {
s = a.Loader.Escape(SchemaEsc, s)
}
s = s + "."
}
return s + n
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/funcs.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/funcs.go#L603-L609 | go | train | // colname returns the ColumnName of col, optionally escaping it if
// ArgType.EscapeColumnNames is toggled. | func (a *ArgType) colname(col *models.Column) string | // colname returns the ColumnName of col, optionally escaping it if
// ArgType.EscapeColumnNames is toggled.
func (a *ArgType) colname(col *models.Column) string | {
if a.EscapeColumnNames {
return a.Loader.Escape(ColumnEsc, col.ColumnName)
}
return col.ColumnName
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/funcs.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/funcs.go#L613-L621 | go | train | // hascolumn takes a list of fields and determines if field with the specified
// column name is in the list. | func (a *ArgType) hascolumn(fields []*Field, name string) bool | // hascolumn takes a list of fields and determines if field with the specified
// column name is in the list.
func (a *ArgType) hascolumn(fields []*Field, name string) bool | {
for _, f := range fields {
if f.Col.ColumnName == name {
return true
}
}
return false
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/funcs.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/funcs.go#L625-L633 | go | train | // hasfield takes a list of fields and determines if field with the specified
// field name is in the list. | func (a *ArgType) hasfield(fields []*Field, name string) bool | // hasfield takes a list of fields and determines if field with the specified
// field name is in the list.
func (a *ArgType) hasfield(fields []*Field, name string) bool | {
for _, f := range fields {
if f.Name == name {
return true
}
}
return false
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/funcs.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/funcs.go#L636-L638 | go | train | // getstartcount returns a starting count for numbering columsn in queries | func (a *ArgType) getstartcount(fields []*Field, pkFields []*Field) int | // getstartcount returns a starting count for numbering columsn in queries
func (a *ArgType) getstartcount(fields []*Field, pkFields []*Field) int | {
return len(fields) - len(pkFields)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | models/enum.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/models/enum.xo.go#L12-L46 | go | train | // PgEnums runs a custom query, returning results as Enum. | func PgEnums(db XODB, schema string) ([]*Enum, error) | // PgEnums runs a custom query, returning results as Enum.
func PgEnums(db XODB, schema string) ([]*Enum, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`t.typname ` + // ::varchar AS enum_name
`FROM pg_type t ` +
`JOIN ONLY pg_namespace n ON n.oid = t.typnamespace ` +
`JOIN ONLY pg_enum e ON t.oid = e.enumtypid ` +
`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 := []*Enum{}
for q.Next() {
e := Enum{}
// scan
err = q.Scan(&e.EnumName)
if err != nil {
return nil, err
}
res = append(res, &e)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/pgcatalog/ischema/sp_pgtruetypmod.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/pgcatalog/ischema/sp_pgtruetypmod.xo.go#L9-L24 | go | train | // Code generated by xo. DO NOT EDIT.
// PgTruetypmod calls the stored procedure 'information_schema._pg_truetypmod(pg_attribute, pg_type) integer' on db. | func PgTruetypmod(db XODB, v0 pgtypes.PgAttribute, v1 pgtypes.PgType) (int, error) | // Code generated by xo. DO NOT EDIT.
// PgTruetypmod calls the stored procedure 'information_schema._pg_truetypmod(pg_attribute, pg_type) integer' on db.
func PgTruetypmod(db XODB, v0 pgtypes.PgAttribute, v1 pgtypes.PgType) (int, error) | {
var err error
// sql query
const sqlstr = `SELECT information_schema._pg_truetypmod($1, $2)`
// run query
var ret int
XOLog(sqlstr, v0, v1)
err = db.QueryRow(sqlstr, v0, v1).Scan(&ret)
if err != nil {
return 0, err
}
return ret, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/types.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/types.go#L23-L46 | go | train | // String returns the name for the associated template type. | func (tt TemplateType) String() string | // String returns the name for the associated template type.
func (tt TemplateType) String() string | {
var s string
switch tt {
case XOTemplate:
s = "xo_db"
case EnumTemplate:
s = "enum"
case ProcTemplate:
s = "proc"
case TypeTemplate:
s = "type"
case ForeignKeyTemplate:
s = "foreignkey"
case IndexTemplate:
s = "index"
case QueryTypeTemplate:
s = "querytype"
case QueryTemplate:
s = "query"
default:
panic("unknown TemplateType")
}
return s
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/types.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/types.go#L69-L80 | go | train | // String provides the string representation of RelType. | func (rt RelType) String() string | // String provides the string representation of RelType.
func (rt RelType) String() string | {
var s string
switch rt {
case Table:
s = "TABLE"
case View:
s = "VIEW"
default:
panic("unknown RelType")
}
return s
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/djangoadminlog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/djangoadminlog.xo.go#L38-L71 | 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 query
const sqlstr = `INSERT INTO django.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 /*lastInsertId*/ INTO :pk`
// run query
XOLog(sqlstr, dal.ActionTime, dal.ObjectID, dal.ObjectRepr, dal.ActionFlag, dal.ChangeMessage, dal.ContentTypeID, dal.UserID, nil)
res, err := db.Exec(sqlstr, dal.ActionTime, dal.ObjectID, dal.ObjectRepr, dal.ActionFlag, dal.ChangeMessage, dal.ContentTypeID, dal.UserID, nil)
if err != nil {
return err
}
// retrieve id
id, err := res.LastInsertId()
if err != nil {
return err
}
// set primary key and existence
dal.ID = float64(id)
dal._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/djangoadminlog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/djangoadminlog.xo.go#L99-L105 | go | train | // Save saves the DjangoAdminLog to the database. | func (dal *DjangoAdminLog) Save(db XODB) error | // Save saves the DjangoAdminLog to the database.
func (dal *DjangoAdminLog) Save(db XODB) error | {
if dal.Exists() {
return dal.Update(db)
}
return dal.Insert(db)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/djangoadminlog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/djangoadminlog.xo.go#L140-L142 | go | train | // DjangoContentType returns the DjangoContentType associated with the DjangoAdminLog's ContentTypeID (content_type_id).
//
// Generated from foreign key 'd66d09ff3188e34f6a42ff99b3e0eb'. | func (dal *DjangoAdminLog) DjangoContentType(db XODB) (*DjangoContentType, error) | // DjangoContentType returns the DjangoContentType associated with the DjangoAdminLog's ContentTypeID (content_type_id).
//
// Generated from foreign key 'd66d09ff3188e34f6a42ff99b3e0eb'.
func (dal *DjangoAdminLog) DjangoContentType(db XODB) (*DjangoContentType, error) | {
return DjangoContentTypeByID(db, dal.ContentTypeID.Float64)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/djangoadminlog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/djangoadminlog.xo.go#L147-L149 | go | train | // AuthUser returns the AuthUser associated with the DjangoAdminLog's UserID (user_id).
//
// Generated from foreign key 'e3cca4fe721a3e54da54a29c371971'. | func (dal *DjangoAdminLog) AuthUser(db XODB) (*AuthUser, error) | // AuthUser returns the AuthUser associated with the DjangoAdminLog's UserID (user_id).
//
// Generated from foreign key 'e3cca4fe721a3e54da54a29c371971'.
func (dal *DjangoAdminLog) AuthUser(db XODB) (*AuthUser, error) | {
return AuthUserByID(db, dal.UserID)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/oracle/djangoadminlog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/oracle/djangoadminlog.xo.go#L193-L227 | go | train | // DjangoAdminLogsByUserID retrieves a row from 'django.django_admin_log' as a DjangoAdminLog.
//
// Generated from index 'django_admin_log_e8701ad4'. | func DjangoAdminLogsByUserID(db XODB, userID float64) ([]*DjangoAdminLog, error) | // DjangoAdminLogsByUserID retrieves a row from 'django.django_admin_log' as a DjangoAdminLog.
//
// Generated from index 'django_admin_log_e8701ad4'.
func DjangoAdminLogsByUserID(db XODB, userID float64) ([]*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 django.django_admin_log ` +
`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 := []*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 | examples/django/sqlite3/authuser.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/sqlite3/authuser.xo.go#L40-L73 | 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 autoincrement
const sqlstr = `INSERT INTO auth_user (` +
`password, last_login, is_superuser, first_name, last_name, email, is_staff, is_active, date_joined, username` +
`) VALUES (` +
`?, ?, ?, ?, ?, ?, ?, ?, ?, ?` +
`)`
// run query
XOLog(sqlstr, au.Password, au.LastLogin, au.IsSuperuser, au.FirstName, au.LastName, au.Email, au.IsStaff, au.IsActive, au.DateJoined, au.Username)
res, err := db.Exec(sqlstr, au.Password, au.LastLogin, au.IsSuperuser, au.FirstName, au.LastName, au.Email, au.IsStaff, au.IsActive, au.DateJoined, au.Username)
if err != nil {
return err
}
// retrieve id
id, err := res.LastInsertId()
if err != nil {
return err
}
// set primary key and existence
au.ID = int(id)
au._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/sqlite3/authuser.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/sqlite3/authuser.xo.go#L101-L107 | go | train | // Save saves the AuthUser to the database. | func (au *AuthUser) Save(db XODB) error | // Save saves the AuthUser to the database.
func (au *AuthUser) Save(db XODB) error | {
if au.Exists() {
return au.Update(db)
}
return au.Insert(db)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/sqlite3/djangoadminlog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/sqlite3/djangoadminlog.xo.go#L140-L142 | go | train | // DjangoContentType returns the DjangoContentType associated with the DjangoAdminLog's ContentTypeID (content_type_id).
//
// Generated from foreign key 'django_admin_log_content_type_id_fkey'. | func (dal *DjangoAdminLog) DjangoContentType(db XODB) (*DjangoContentType, error) | // DjangoContentType returns the DjangoContentType associated with the DjangoAdminLog's ContentTypeID (content_type_id).
//
// Generated from foreign key 'django_admin_log_content_type_id_fkey'.
func (dal *DjangoAdminLog) DjangoContentType(db XODB) (*DjangoContentType, error) | {
return DjangoContentTypeByID(db, int(dal.ContentTypeID.Int64))
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/sqlite3/djangoadminlog.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/sqlite3/djangoadminlog.xo.go#L232-L253 | go | train | // DjangoAdminLogByID retrieves a row from 'django_admin_log' as a DjangoAdminLog.
//
// Generated from index 'django_admin_log_id_pkey'. | func DjangoAdminLogByID(db XODB, id int) (*DjangoAdminLog, error) | // DjangoAdminLogByID retrieves a row from 'django_admin_log' as a DjangoAdminLog.
//
// Generated from index 'django_admin_log_id_pkey'.
func DjangoAdminLogByID(db XODB, id int) (*DjangoAdminLog, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, object_id, object_repr, action_flag, change_message, content_type_id, user_id, action_time ` +
`FROM django_admin_log ` +
`WHERE id = ?`
// run query
XOLog(sqlstr, id)
dal := DjangoAdminLog{
_exists: true,
}
err = db.QueryRow(sqlstr, id).Scan(&dal.ID, &dal.ObjectID, &dal.ObjectRepr, &dal.ActionFlag, &dal.ChangeMessage, &dal.ContentTypeID, &dal.UserID, &dal.ActionTime)
if err != nil {
return nil, err
}
return &dal, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authgroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authgroup.xo.go#L30-L56 | 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 insert query, primary key provided by sequence
const sqlstr = `INSERT INTO public.auth_group (` +
`name` +
`) VALUES (` +
`$1` +
`) RETURNING id`
// run query
XOLog(sqlstr, ag.Name)
err = db.QueryRow(sqlstr, ag.Name).Scan(&ag.ID)
if err != nil {
return err
}
// set existence
ag._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authgroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authgroup.xo.go#L97-L127 | go | train | // Upsert performs an upsert for AuthGroup.
//
// NOTE: PostgreSQL 9.5+ only | func (ag *AuthGroup) Upsert(db XODB) error | // Upsert performs an upsert for AuthGroup.
//
// NOTE: PostgreSQL 9.5+ only
func (ag *AuthGroup) Upsert(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 public.auth_group (` +
`id, name` +
`) VALUES (` +
`$1, $2` +
`) ON CONFLICT (id) DO UPDATE SET (` +
`id, name` +
`) = (` +
`EXCLUDED.id, EXCLUDED.name` +
`)`
// run query
XOLog(sqlstr, ag.ID, ag.Name)
_, err = db.Exec(sqlstr, ag.ID, ag.Name)
if err != nil {
return err
}
// set existence
ag._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authgroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authgroup.xo.go#L162-L196 | go | train | // AuthGroupsByName retrieves a row from 'public.auth_group' as a AuthGroup.
//
// Generated from index 'auth_group_name_a6ea08ec_like'. | func AuthGroupsByName(db XODB, name string) ([]*AuthGroup, error) | // AuthGroupsByName retrieves a row from 'public.auth_group' as a AuthGroup.
//
// Generated from index 'auth_group_name_a6ea08ec_like'.
func AuthGroupsByName(db XODB, name string) ([]*AuthGroup, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, name ` +
`FROM public.auth_group ` +
`WHERE name = $1`
// run query
XOLog(sqlstr, name)
q, err := db.Query(sqlstr, name)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*AuthGroup{}
for q.Next() {
ag := AuthGroup{
_exists: true,
}
// scan
err = q.Scan(&ag.ID, &ag.Name)
if err != nil {
return nil, err
}
res = append(res, &ag)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authgroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authgroup.xo.go#L201-L222 | go | train | // AuthGroupByName retrieves a row from 'public.auth_group' as a AuthGroup.
//
// Generated from index 'auth_group_name_key'. | func AuthGroupByName(db XODB, name string) (*AuthGroup, error) | // AuthGroupByName retrieves a row from 'public.auth_group' as a AuthGroup.
//
// Generated from index 'auth_group_name_key'.
func AuthGroupByName(db XODB, name string) (*AuthGroup, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, name ` +
`FROM public.auth_group ` +
`WHERE name = $1`
// run query
XOLog(sqlstr, name)
ag := AuthGroup{
_exists: true,
}
err = db.QueryRow(sqlstr, name).Scan(&ag.ID, &ag.Name)
if err != nil {
return nil, err
}
return &ag, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | models/index.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/models/index.xo.go#L17-L57 | go | train | // PgTableIndexes runs a custom query, returning results as Index. | func PgTableIndexes(db XODB, schema string, table string) ([]*Index, error) | // PgTableIndexes runs a custom query, returning results as Index.
func PgTableIndexes(db XODB, schema string, table string) ([]*Index, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`DISTINCT ic.relname, ` + // ::varchar AS index_name
`i.indisunique, ` + // ::boolean AS is_unique
`i.indisprimary, ` + // ::boolean AS is_primary
`0, ` + // ::integer AS seq_no
`'', ` + // ::varchar AS origin
`false ` + // ::boolean AS is_partial
`FROM pg_index i ` +
`JOIN ONLY pg_class c ON c.oid = i.indrelid ` +
`JOIN ONLY pg_namespace n ON n.oid = c.relnamespace ` +
`JOIN ONLY pg_class ic ON ic.oid = i.indexrelid ` +
`WHERE i.indkey <> '0' AND n.nspname = $1 AND c.relname = $2`
// 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 := []*Index{}
for q.Next() {
i := Index{}
// scan
err = q.Scan(&i.IndexName, &i.IsUnique, &i.IsPrimary, &i.SeqNo, &i.Origin, &i.IsPartial)
if err != nil {
return nil, err
}
res = append(res, &i)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | models/table.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/models/table.xo.go#L122-L155 | go | train | // MsTables runs a custom query, returning results as Table. | func MsTables(db XODB, schema string, relkind string) ([]*Table, error) | // MsTables runs a custom query, returning results as Table.
func MsTables(db XODB, schema string, relkind string) ([]*Table, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`xtype AS type, ` +
`name AS table_name ` +
`FROM sysobjects ` +
`WHERE SCHEMA_NAME(uid) = $1 AND xtype = $2`
// run query
XOLog(sqlstr, schema, relkind)
q, err := db.Query(sqlstr, schema, relkind)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*Table{}
for q.Next() {
t := Table{}
// scan
err = q.Scan(&t.Type, &t.TableName)
if err != nil {
return nil, err
}
res = append(res, &t)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | models/enumvalue.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/models/enumvalue.xo.go#L13-L48 | go | train | // PgEnumValues runs a custom query, returning results as EnumValue. | func PgEnumValues(db XODB, schema string, enum string) ([]*EnumValue, error) | // PgEnumValues runs a custom query, returning results as EnumValue.
func PgEnumValues(db XODB, schema string, enum string) ([]*EnumValue, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`e.enumlabel, ` + // ::varchar AS enum_value
`e.enumsortorder ` + // ::integer AS const_value
`FROM pg_type t ` +
`JOIN ONLY pg_namespace n ON n.oid = t.typnamespace ` +
`LEFT JOIN pg_enum e ON t.oid = e.enumtypid ` +
`WHERE n.nspname = $1 AND t.typname = $2`
// run query
XOLog(sqlstr, schema, enum)
q, err := db.Query(sqlstr, schema, enum)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*EnumValue{}
for q.Next() {
ev := EnumValue{}
// scan
err = q.Scan(&ev.EnumValue, &ev.ConstValue)
if err != nil {
return nil, err
}
res = append(res, &ev)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/oracle.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/oracle.go#L75-L166 | go | train | // OrParseType parse a oracle type into a Go type based on the column
// definition. | func OrParseType(args *internal.ArgType, dt string, nullable bool) (int, string, string) | // OrParseType parse a oracle type into a Go type based on the column
// definition.
func OrParseType(args *internal.ArgType, dt string, nullable bool) (int, string, string) | {
nilVal := "nil"
dt = strings.ToLower(dt)
// extract precision
dt, precision, scale := args.ParsePrecision(dt)
var typ string
// strip remaining length (on things like timestamp)
switch OrLenRE.ReplaceAllString(dt, "") {
case "char", "nchar", "varchar", "varchar2", "nvarchar2",
"long",
"clob", "nclob",
"rowid":
nilVal = `""`
typ = "string"
case "shortint":
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 "longinteger":
nilVal = "0"
typ = "int64"
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "float", "shortdecimal":
nilVal = "0.0"
typ = "float32"
if nullable {
nilVal = "sql.NullFloat64{}"
typ = "sql.NullFloat64"
}
case "number", "decimal":
nilVal = "0.0"
if 0 < precision && precision < 18 && scale > 0 {
typ = "float64"
if nullable {
nilVal = "sql.NullFloat64{}"
typ = "sql.NullFloat64"
}
} else if 0 < precision && precision <= 19 && scale == 0 {
typ = "int64"
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
} else {
nilVal = `""`
typ = "string"
}
case "blob", "long raw", "raw":
typ = "[]byte"
case "date", "timestamp", "timestamp with time zone":
typ = "time.Time"
nilVal = "time.Time{}"
default:
// bail
fmt.Fprintf(os.Stderr, "error: unknown type %q\n", dt)
os.Exit(1)
}
// special case for bool
if typ == "int" && precision == 1 {
nilVal = "false"
typ = "bool"
if nullable {
nilVal = "sql.NullBool{}"
typ = "sql.NullBool"
}
}
return precision, nilVal, typ
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | models/indexcolumn.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/models/indexcolumn.xo.go#L14-L52 | go | train | // PgIndexColumns runs a custom query, returning results as IndexColumn. | func PgIndexColumns(db XODB, schema string, index string) ([]*IndexColumn, error) | // PgIndexColumns runs a custom query, returning results as IndexColumn.
func PgIndexColumns(db XODB, schema string, index string) ([]*IndexColumn, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`(row_number() over()), ` + // ::integer AS seq_no
`a.attnum, ` + // ::integer AS cid
`a.attname ` + // ::varchar AS column_name
`FROM pg_index i ` +
`JOIN ONLY pg_class c ON c.oid = i.indrelid ` +
`JOIN ONLY pg_namespace n ON n.oid = c.relnamespace ` +
`JOIN ONLY pg_class ic ON ic.oid = i.indexrelid ` +
`LEFT JOIN pg_attribute a ON i.indrelid = a.attrelid AND a.attnum = ANY(i.indkey) AND a.attisdropped = false ` +
`WHERE i.indkey <> '0' AND n.nspname = $1 AND ic.relname = $2`
// run query
XOLog(sqlstr, schema, index)
q, err := db.Query(sqlstr, schema, index)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*IndexColumn{}
for q.Next() {
ic := IndexColumn{}
// scan
err = q.Scan(&ic.SeqNo, &ic.Cid, &ic.ColumnName)
if err != nil {
return nil, err
}
res = append(res, &ic)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | models/foreignkey.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/models/foreignkey.xo.go#L21-L69 | go | train | // PgTableForeignKeys runs a custom query, returning results as ForeignKey. | func PgTableForeignKeys(db XODB, schema string, table string) ([]*ForeignKey, error) | // PgTableForeignKeys runs a custom query, returning results as ForeignKey.
func PgTableForeignKeys(db XODB, schema string, table string) ([]*ForeignKey, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`r.conname, ` + // ::varchar AS foreign_key_name
`b.attname, ` + // ::varchar AS column_name
`i.relname, ` + // ::varchar AS ref_index_name
`c.relname, ` + // ::varchar AS ref_table_name
`d.attname, ` + // ::varchar AS ref_column_name
`0, ` + // ::integer AS key_id
`0, ` + // ::integer AS seq_no
`'', ` + // ::varchar AS on_update
`'', ` + // ::varchar AS on_delete
`'' ` + // ::varchar AS match
`FROM pg_constraint r ` +
`JOIN ONLY pg_class a ON a.oid = r.conrelid ` +
`JOIN ONLY pg_attribute b ON b.attisdropped = false AND b.attnum = ANY(r.conkey) AND b.attrelid = r.conrelid ` +
`JOIN ONLY pg_class i on i.oid = r.conindid ` +
`JOIN ONLY pg_class c on c.oid = r.confrelid ` +
`JOIN ONLY pg_attribute d ON d.attisdropped = false AND d.attnum = ANY(r.confkey) AND d.attrelid = r.confrelid ` +
`JOIN ONLY pg_namespace n ON n.oid = r.connamespace ` +
`WHERE r.contype = 'f' AND n.nspname = $1 AND a.relname = $2 ` +
`ORDER BY r.conname, b.attname`
// 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 := []*ForeignKey{}
for q.Next() {
fk := ForeignKey{}
// scan
err = q.Scan(&fk.ForeignKeyName, &fk.ColumnName, &fk.RefIndexName, &fk.RefTableName, &fk.RefColumnName, &fk.KeyID, &fk.SeqNo, &fk.OnUpdate, &fk.OnDelete, &fk.Match)
if err != nil {
return nil, err
}
res = append(res, &fk)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | models/foreignkey.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/models/foreignkey.xo.go#L142-L182 | go | train | // MsTableForeignKeys runs a custom query, returning results as ForeignKey. | func MsTableForeignKeys(db XODB, schema string, table string) ([]*ForeignKey, error) | // MsTableForeignKeys runs a custom query, returning results as ForeignKey.
func MsTableForeignKeys(db XODB, schema string, table string) ([]*ForeignKey, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`f.name AS foreign_key_name, ` +
`c.name AS column_name, ` +
`o.name AS ref_table_name, ` +
`x.name AS ref_column_name ` +
`FROM sysobjects f ` +
`INNER JOIN sysobjects t ON f.parent_obj = t.id ` +
`INNER JOIN sysreferences r ON f.id = r.constid ` +
`INNER JOIN sysobjects o ON r.rkeyid = o.id ` +
`INNER JOIN syscolumns c ON r.rkeyid = c.id AND r.rkey1 = c.colid ` +
`INNER JOIN syscolumns x ON r.fkeyid = x.id AND r.fkey1 = x.colid ` +
`WHERE f.type = 'F' AND t.type = 'U' AND SCHEMA_NAME(t.uid) = $1 AND t.name = $2`
// 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 := []*ForeignKey{}
for q.Next() {
fk := ForeignKey{}
// scan
err = q.Scan(&fk.ForeignKeyName, &fk.ColumnName, &fk.RefTableName, &fk.RefColumnName)
if err != nil {
return nil, err
}
res = append(res, &fk)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/sqlite3/authpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/sqlite3/authpermission.xo.go#L32-L65 | 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 autoincrement
const sqlstr = `INSERT INTO auth_permission (` +
`content_type_id, codename, name` +
`) VALUES (` +
`?, ?, ?` +
`)`
// run query
XOLog(sqlstr, ap.ContentTypeID, ap.Codename, ap.Name)
res, err := db.Exec(sqlstr, ap.ContentTypeID, ap.Codename, ap.Name)
if err != nil {
return err
}
// retrieve id
id, err := res.LastInsertId()
if err != nil {
return err
}
// set primary key and existence
ap.ID = int(id)
ap._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/sqlite3/authpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/sqlite3/authpermission.xo.go#L68-L90 | go | train | // Update updates the AuthPermission in the database. | func (ap *AuthPermission) Update(db XODB) error | // Update updates the AuthPermission in the database.
func (ap *AuthPermission) Update(db XODB) error | {
var err error
// if doesn't exist, bail
if !ap._exists {
return errors.New("update failed: does not exist")
}
// if deleted, bail
if ap._deleted {
return errors.New("update failed: marked for deletion")
}
// sql query
const sqlstr = `UPDATE auth_permission SET ` +
`content_type_id = ?, codename = ?, name = ?` +
` WHERE id = ?`
// run query
XOLog(sqlstr, ap.ContentTypeID, ap.Codename, ap.Name, ap.ID)
_, err = db.Exec(sqlstr, ap.ContentTypeID, ap.Codename, ap.Name, ap.ID)
return err
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/sqlite3/authpermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/sqlite3/authpermission.xo.go#L102-L129 | go | train | // Delete deletes the AuthPermission from the database. | func (ap *AuthPermission) Delete(db XODB) error | // Delete deletes the AuthPermission from the database.
func (ap *AuthPermission) Delete(db XODB) error | {
var err error
// if doesn't exist, bail
if !ap._exists {
return nil
}
// if deleted, bail
if ap._deleted {
return nil
}
// sql query
const sqlstr = `DELETE FROM auth_permission WHERE id = ?`
// run query
XOLog(sqlstr, ap.ID)
_, err = db.Exec(sqlstr, ap.ID)
if err != nil {
return err
}
// set deleted
ap._deleted = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/mysql/authgrouppermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/mysql/authgrouppermission.xo.go#L92-L98 | go | train | // Save saves the AuthGroupPermission to the database. | func (agp *AuthGroupPermission) Save(db XODB) error | // Save saves the AuthGroupPermission to the database.
func (agp *AuthGroupPermission) Save(db XODB) error | {
if agp.Exists() {
return agp.Update(db)
}
return agp.Insert(db)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/mysql/authgrouppermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/mysql/authgrouppermission.xo.go#L133-L135 | go | train | // AuthPermission returns the AuthPermission associated with the AuthGroupPermission's PermissionID (permission_id).
//
// Generated from foreign key 'auth_group_permissi_permission_id_84c5c92e_fk_auth_permission_id'. | func (agp *AuthGroupPermission) AuthPermission(db XODB) (*AuthPermission, error) | // AuthPermission returns the AuthPermission associated with the AuthGroupPermission's PermissionID (permission_id).
//
// Generated from foreign key 'auth_group_permissi_permission_id_84c5c92e_fk_auth_permission_id'.
func (agp *AuthGroupPermission) AuthPermission(db XODB) (*AuthPermission, error) | {
return AuthPermissionByID(db, agp.PermissionID)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/mysql/authgrouppermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/mysql/authgrouppermission.xo.go#L140-L142 | go | train | // AuthGroup returns the AuthGroup associated with the AuthGroupPermission's GroupID (group_id).
//
// Generated from foreign key 'auth_group_permissions_group_id_b120cbf9_fk_auth_group_id'. | func (agp *AuthGroupPermission) AuthGroup(db XODB) (*AuthGroup, error) | // AuthGroup returns the AuthGroup associated with the AuthGroupPermission's GroupID (group_id).
//
// Generated from foreign key 'auth_group_permissions_group_id_b120cbf9_fk_auth_group_id'.
func (agp *AuthGroupPermission) AuthGroup(db XODB) (*AuthGroup, error) | {
return AuthGroupByID(db, agp.GroupID)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/mysql/authgrouppermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/mysql/authgrouppermission.xo.go#L147-L181 | go | train | // AuthGroupPermissionsByPermissionID retrieves a row from 'django.auth_group_permissions' as a AuthGroupPermission.
//
// Generated from index 'auth_group_permissi_permission_id_84c5c92e_fk_auth_permission_id'. | func AuthGroupPermissionsByPermissionID(db XODB, permissionID int) ([]*AuthGroupPermission, error) | // AuthGroupPermissionsByPermissionID retrieves a row from 'django.auth_group_permissions' as a AuthGroupPermission.
//
// Generated from index 'auth_group_permissi_permission_id_84c5c92e_fk_auth_permission_id'.
func AuthGroupPermissionsByPermissionID(db XODB, permissionID int) ([]*AuthGroupPermission, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, group_id, permission_id ` +
`FROM django.auth_group_permissions ` +
`WHERE permission_id = ?`
// run query
XOLog(sqlstr, permissionID)
q, err := db.Query(sqlstr, permissionID)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*AuthGroupPermission{}
for q.Next() {
agp := AuthGroupPermission{
_exists: true,
}
// scan
err = q.Scan(&agp.ID, &agp.GroupID, &agp.PermissionID)
if err != nil {
return nil, err
}
res = append(res, &agp)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | main.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/main.go#L100-L205 | go | train | // processArgs processs cli args. | func processArgs(args *internal.ArgType) error | // processArgs processs cli args.
func processArgs(args *internal.ArgType) error | {
var err error
// get working directory
cwd, err := os.Getwd()
if err != nil {
return err
}
// determine out path
if args.Out == "" {
args.Path = cwd
} else {
// determine what to do with Out
fi, err := os.Stat(args.Out)
if err == nil && fi.IsDir() {
// out is directory
args.Path = args.Out
} else if err == nil && !fi.IsDir() {
// file exists (will truncate later)
args.Path = path.Dir(args.Out)
args.Filename = path.Base(args.Out)
// error if not split was set, but destination is not a directory
if !args.SingleFile {
return errors.New("output path is not directory")
}
} else if _, ok := err.(*os.PathError); ok {
// path error (ie, file doesn't exist yet)
args.Path = path.Dir(args.Out)
args.Filename = path.Base(args.Out)
// error if split was set, but dest doesn't exist
if !args.SingleFile {
return errors.New("output path must be a directory and already exist when not writing to a single file")
}
} else {
return err
}
}
// check user template path
if args.TemplatePath != "" {
fi, err := os.Stat(args.TemplatePath)
if err == nil && !fi.IsDir() {
return errors.New("template path is not directory")
} else if err != nil {
return errors.New("template path must exist")
}
}
// fix path
if args.Path == "." {
args.Path = cwd
}
// determine package name
if args.Package == "" {
args.Package = path.Base(args.Path)
}
// determine filename if not previously set
if args.Filename == "" {
args.Filename = args.Package + args.Suffix
}
// if query mode toggled, but no query, read Stdin.
if args.QueryMode && args.Query == "" {
buf, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return err
}
args.Query = string(buf)
}
// query mode parsing
if args.Query != "" {
args.QueryMode = true
}
// check that query type was specified
if args.QueryMode && args.QueryType == "" {
return errors.New("query type must be supplied for query parsing mode")
}
// query trim
if args.QueryMode && args.QueryTrim {
args.Query = strings.TrimSpace(args.Query)
}
// escape all
if args.EscapeAll {
args.EscapeSchemaName = true
args.EscapeTableNames = true
args.EscapeColumnNames = true
}
// if verbose
if args.Verbose {
models.XOLog = func(s string, p ...interface{}) {
fmt.Printf("SQL:\n%s\nPARAMS:\n%v\n\n", s, p)
}
}
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | main.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/main.go#L208-L234 | go | train | // openDB attempts to open a database connection. | func openDB(args *internal.ArgType) error | // openDB attempts to open a database connection.
func openDB(args *internal.ArgType) error | {
var err error
// parse dsn
u, err := dburl.Parse(args.DSN)
if err != nil {
return err
}
// save driver type
args.LoaderType = u.Driver
// grab loader
var ok bool
args.Loader, ok = internal.SchemaLoaders[u.Driver]
if !ok {
return errors.New("unsupported database type")
}
// open database connection
args.DB, err = sql.Open(u.Driver, u.DSN)
if err != nil {
return err
}
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | main.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/main.go#L242-L300 | go | train | // getFile builds the filepath from the TBuf information, and retrieves the
// file from files. If the built filename is not already defined, then it calls
// the os.OpenFile with the correct parameters depending on the state of args. | func getFile(args *internal.ArgType, t *internal.TBuf) (*os.File, error) | // getFile builds the filepath from the TBuf information, and retrieves the
// file from files. If the built filename is not already defined, then it calls
// the os.OpenFile with the correct parameters depending on the state of args.
func getFile(args *internal.ArgType, t *internal.TBuf) (*os.File, error) | {
var f *os.File
var err error
// determine filename
var filename = strings.ToLower(t.Name) + args.Suffix
if args.SingleFile {
filename = args.Filename
}
filename = path.Join(args.Path, filename)
// lookup file
f, ok := files[filename]
if ok {
return f, nil
}
// default open mode
mode := os.O_RDWR | os.O_CREATE | os.O_TRUNC
// stat file to determine if file already exists
fi, err := os.Stat(filename)
if err == nil && fi.IsDir() {
return nil, errors.New("filename cannot be directory")
} else if _, ok = err.(*os.PathError); !ok && args.Append && t.TemplateType != internal.XOTemplate {
// file exists so append if append is set and not XO type
mode = os.O_APPEND | os.O_WRONLY
}
// skip
if t.TemplateType == internal.XOTemplate && fi != nil {
return nil, nil
}
// open file
f, err = os.OpenFile(filename, mode, 0666)
if err != nil {
return nil, err
}
// file didn't originally exist, so add package header
if fi == nil || !args.Append {
// add build tags
if args.Tags != "" {
f.WriteString(`// +build ` + args.Tags + "\n\n")
}
// execute
err = args.TemplateSet().Execute(f, "xo_package.go.tpl", args)
if err != nil {
return nil, err
}
}
// store file
files[filename] = f
return f, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | main.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/main.go#L303-L365 | go | train | // writeTypes writes the generated definitions. | func writeTypes(args *internal.ArgType) error | // writeTypes writes the generated definitions.
func writeTypes(args *internal.ArgType) error | {
var err error
out := internal.TBufSlice(args.Generated)
// sort segments
sort.Sort(out)
// loop, writing in order
for _, t := range out {
var f *os.File
// skip when in append and type is XO
if args.Append && t.TemplateType == internal.XOTemplate {
continue
}
// check if generated template is only whitespace/empty
bufStr := strings.TrimSpace(t.Buf.String())
if len(bufStr) == 0 {
continue
}
// get file and filename
f, err = getFile(args, &t)
if err != nil {
return err
}
// should only be nil when type == xo
if f == nil {
continue
}
// write segment
if !args.Append || (t.TemplateType != internal.TypeTemplate && t.TemplateType != internal.QueryTypeTemplate) {
_, err = t.Buf.WriteTo(f)
if err != nil {
return err
}
}
}
// build goimports parameters, closing files
params := []string{"-w"}
for k, f := range files {
params = append(params, k)
// close
err = f.Close()
if err != nil {
return err
}
}
// process written files with goimports
output, err := exec.Command("goimports", params...).CombinedOutput()
if err != nil {
return errors.New(string(output))
}
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | models/myautoincrement.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/models/myautoincrement.xo.go#L12-L44 | go | train | // MyAutoIncrements runs a custom query, returning results as MyAutoIncrement. | func MyAutoIncrements(db XODB, schema string) ([]*MyAutoIncrement, error) | // MyAutoIncrements runs a custom query, returning results as MyAutoIncrement.
func MyAutoIncrements(db XODB, schema string) ([]*MyAutoIncrement, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`table_name ` +
`FROM information_schema.tables ` +
`WHERE auto_increment IS NOT null AND table_schema = ?`
// run query
XOLog(sqlstr, schema)
q, err := db.Query(sqlstr, schema)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*MyAutoIncrement{}
for q.Next() {
mai := MyAutoIncrement{}
// scan
err = q.Scan(&mai.TableName)
if err != nil {
return nil, err
}
res = append(res, &mai)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | models/sqautoincrement.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/models/sqautoincrement.xo.go#L13-L46 | go | train | // SqAutoIncrements runs a custom query, returning results as SqAutoIncrement. | func SqAutoIncrements(db XODB) ([]*SqAutoIncrement, error) | // SqAutoIncrements runs a custom query, returning results as SqAutoIncrement.
func SqAutoIncrements(db XODB) ([]*SqAutoIncrement, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`name as table_name, sql ` +
`FROM sqlite_master ` +
`WHERE type='table' ` +
`ORDER BY name`
// run query
XOLog(sqlstr)
q, err := db.Query(sqlstr)
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*SqAutoIncrement{}
for q.Next() {
sai := SqAutoIncrement{}
// scan
err = q.Scan(&sai.TableName, &sai.SQL)
if err != nil {
return nil, err
}
res = append(res, &sai)
}
return res, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/util.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/util.go#L20-L93 | go | train | // ParseQuery takes the query in args and looks for strings in the form of
// "%%<name> <type>[,<option>,...]%%", replacing them with the supplied mask.
// mask can contain "%d" to indicate current position. The modified query is
// returned, and the slice of extracted QueryParam's. | func (a *ArgType) ParseQuery(mask string, interpol bool) (string, []*QueryParam) | // ParseQuery takes the query in args and looks for strings in the form of
// "%%<name> <type>[,<option>,...]%%", replacing them with the supplied mask.
// mask can contain "%d" to indicate current position. The modified query is
// returned, and the slice of extracted QueryParam's.
func (a *ArgType) ParseQuery(mask string, interpol bool) (string, []*QueryParam) | {
dl := a.QueryParamDelimiter
// create the regexp for the delimiter
placeholderRE := regexp.MustCompile(
dl + `[^` + dl[:1] + `]+` + dl,
)
// grab matches from query string
matches := placeholderRE.FindAllStringIndex(a.Query, -1)
// return vals and placeholders
str := ""
params := []*QueryParam{}
i := 1
last := 0
// loop over matches, extracting each placeholder and splitting to name/type
for _, m := range matches {
// generate place holder value
pstr := mask
if strings.Contains(mask, "%d") {
pstr = fmt.Sprintf(mask, i)
}
// extract parameter info
paramStr := a.Query[m[0]+len(dl) : m[1]-len(dl)]
p := strings.SplitN(paramStr, " ", 2)
param := &QueryParam{
Name: p[0],
Type: p[1],
}
// parse parameter options if present
if strings.Contains(param.Type, ",") {
opts := strings.Split(param.Type, ",")
param.Type = opts[0]
for _, opt := range opts[1:] {
switch opt {
case "interpolate":
if !a.QueryInterpolate {
panic("query interpolate is not enabled")
}
param.Interpolate = true
default:
panic(fmt.Errorf("unknown option encountered on query parameter '%s'", paramStr))
}
}
}
// add to string
str = str + a.Query[last:m[0]]
if interpol && param.Interpolate {
// handle interpolation case
xstr := `fmt.Sprintf("%v", ` + param.Name + `)`
if param.Type == "string" {
xstr = param.Name
}
str = str + "` + " + xstr + " + `"
} else {
str = str + pstr
}
params = append(params, param)
last = m[1]
i++
}
// add part of query remains
str = str + a.Query[last:]
return str, params
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/util.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/util.go#L104-L131 | go | train | // ParsePrecision extracts (precision[,scale]) strings from a data type and
// returns the data type without the string. | func (a *ArgType) ParsePrecision(dt string) (string, int, int) | // ParsePrecision extracts (precision[,scale]) strings from a data type and
// returns the data type without the string.
func (a *ArgType) ParsePrecision(dt string) (string, int, int) | {
var err error
precision := -1
scale := -1
m := PrecScaleRE.FindStringSubmatchIndex(dt)
if m != nil {
// extract precision
precision, err = strconv.Atoi(dt[m[2]:m[3]])
if err != nil {
panic("could not convert precision")
}
// extract scale
if m[4] != -1 {
scale, err = strconv.Atoi(dt[m[4]+1 : m[5]])
if err != nil {
panic("could not convert scale")
}
}
// change dt
dt = dt[:m[0]] + dt[m[1]:]
}
return dt, precision, scale
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/util.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/util.go#L137-L156 | go | train | // fmtIndexName formats the index name. | func fmtIndexName(ixName string, tableName string) string | // fmtIndexName formats the index name.
func fmtIndexName(ixName string, tableName string) string | {
// chop off _ix, _idx, _index, _pkey, or _key
m := IndexChopSuffixRE.FindStringIndex(ixName)
if m != nil {
ixName = ixName[:m[0]]
}
// check tableName
if ixName == tableName {
return ""
}
// chop off tablename_
if strings.HasPrefix(ixName, tableName+"_") {
ixName = ixName[len(tableName)+1:]
}
// camel case name
return snaker.SnakeToCamelIdentifier(ixName)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/util.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/util.go#L160-L182 | go | train | // BuildIndexFuncName builds the index func name for an index and its supplied
// fields. | func (a *ArgType) BuildIndexFuncName(ixTpl *Index) | // BuildIndexFuncName builds the index func name for an index and its supplied
// fields.
func (a *ArgType) BuildIndexFuncName(ixTpl *Index) | {
// build func name
funcName := ixTpl.Type.Name
if !ixTpl.Index.IsUnique {
funcName = inflector.Pluralize(ixTpl.Type.Name)
}
funcName = funcName + "By"
// add param names
paramNames := []string{}
ixName := fmtIndexName(ixTpl.Index.IndexName, ixTpl.Type.Table.TableName)
if a.UseIndexNames && ixName != "" {
paramNames = append(paramNames, ixName)
} else {
for _, f := range ixTpl.Fields {
paramNames = append(paramNames, f.Name)
}
}
// store resulting name back
ixTpl.FuncName = funcName + strings.Join(paramNames, "")
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/util.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/util.go#L198-L211 | go | train | // reverseIndexRune finds the last rune r in s, returning -1 if not present. | func reverseIndexRune(s string, r rune) int | // reverseIndexRune finds the last rune r in s, returning -1 if not present.
func reverseIndexRune(s string, r rune) int | {
if s == "" {
return -1
}
rs := []rune(s)
for i := len(rs) - 1; i >= 0; i-- {
if rs[i] == r {
return i
}
}
return -1
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/util.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/util.go#L215-L223 | go | train | // SinguralizeIdentifier will singularize a identifier, returning it in
// CamelCase. | func SingularizeIdentifier(s string) string | // SinguralizeIdentifier will singularize a identifier, returning it in
// CamelCase.
func SingularizeIdentifier(s string) string | {
if i := reverseIndexRune(s, '_'); i != -1 {
s = s[:i] + "_" + inflector.Singularize(s[i+1:])
} else {
s = inflector.Singularize(s)
}
return snaker.SnakeToCamelIdentifier(s)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/sqlite.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/sqlite.go#L52-L116 | go | train | // SqParseType parse a sqlite type into a Go type based on the column
// definition. | func SqParseType(args *internal.ArgType, dt string, nullable bool) (int, string, string) | // SqParseType parse a sqlite type into a Go type based on the column
// definition.
func SqParseType(args *internal.ArgType, dt string, nullable bool) (int, string, string) | {
precision := 0
nilVal := "nil"
unsigned := false
dt = strings.ToLower(dt)
// extract precision
dt, precision, _ = args.ParsePrecision(dt)
if uRE.MatchString(dt) {
unsigned = true
uRE.ReplaceAllString(dt, "")
}
var typ string
switch dt {
case "bool", "boolean":
nilVal = "false"
typ = "bool"
if nullable {
nilVal = "sql.NullBool{}"
typ = "sql.NullBool"
}
case "int", "integer", "tinyint", "smallint", "mediumint", "bigint":
nilVal = "0"
typ = args.Int32Type
if nullable {
nilVal = "sql.NullInt64{}"
typ = "sql.NullInt64"
}
case "numeric", "real", "double", "float", "decimal":
nilVal = "0.0"
typ = "float64"
if nullable {
nilVal = "sql.NullFloat64{}"
typ = "sql.NullFloat64"
}
case "blob":
typ = "[]byte"
case "timestamp", "datetime", "date", "timestamp with time zone", "time with time zone", "time without time zone", "timestamp without time zone":
nilVal = "xoutil.SqTime{}"
typ = "xoutil.SqTime"
default:
// case "varchar", "character", "varying character", "nchar", "native character", "nvarchar", "text", "clob", "datetime", "date", "time":
nilVal = `""`
typ = "string"
if nullable {
nilVal = "sql.NullString{}"
typ = "sql.NullString"
}
}
// if unsigned ...
if internal.IntRE.MatchString(typ) && unsigned {
typ = "u" + typ
}
return precision, nilVal, typ
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/sqlite.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/sqlite.go#L120-L170 | go | train | // SqTables returns the sqlite tables with the manual PK information added.
// ManualPk is true when the table's primary key is not autoincrement. | func SqTables(db models.XODB, schema string, relkind string) ([]*models.Table, error) | // SqTables returns the sqlite tables with the manual PK information added.
// ManualPk is true when the table's primary key is not autoincrement.
func SqTables(db models.XODB, schema string, relkind string) ([]*models.Table, error) | {
var err error
// get the tables
rows, err := models.SqTables(db, relkind)
if err != nil {
return nil, err
}
// get the SQL for the Autoincrement detection
autoIncrements, err := models.SqAutoIncrements(db)
if err != nil {
// Set it to an empty set on error.
autoIncrements = []*models.SqAutoIncrement{}
}
// 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
// keyword for the given table in the SQL.
for _, autoInc := range autoIncrements {
lSQL := strings.ToLower(autoInc.SQL)
if autoInc.TableName == row.TableName && strings.Contains(lSQL, "autoincrement") {
manualPk = false
} else {
cols, err := SqTableColumns(db, schema, row.TableName)
if err != nil {
return nil, err
}
for _, col := range cols {
if col.IsPrimaryKey == true {
dt := strings.ToUpper(col.DataType)
if dt == "INTEGER" {
manualPk = false
}
break
}
}
}
}
tables = append(tables, &models.Table{
TableName: row.TableName,
Type: row.Type,
ManualPk: manualPk,
})
}
return tables, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/sqlite.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/sqlite.go#L173-L196 | go | train | // SqTableColumns returns the sqlite table column info. | func SqTableColumns(db models.XODB, schema string, table string) ([]*models.Column, error) | // SqTableColumns returns the sqlite table column info.
func SqTableColumns(db models.XODB, schema string, table string) ([]*models.Column, error) | {
var err error
// grab
rows, err := models.SqTableColumns(db, table)
if err != nil {
return nil, err
}
// fix columns
var cols []*models.Column
for _, row := range rows {
cols = append(cols, &models.Column{
FieldOrdinal: row.FieldOrdinal,
ColumnName: row.ColumnName,
DataType: row.DataType,
NotNull: row.NotNull,
DefaultValue: row.DefaultValue,
IsPrimaryKey: row.PkColIndex != 0,
})
}
return cols, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | loaders/sqlite.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/loaders/sqlite.go#L199-L213 | go | train | // SqQueryColumns parses a sqlite query and generates a type for it. | func SqQueryColumns(args *internal.ArgType, inspect []string) ([]*models.Column, error) | // SqQueryColumns parses a sqlite query and generates a type for it.
func SqQueryColumns(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
}
// load column information
return SqTableColumns(args.DB, "", xoid)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authgrouppermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authgrouppermission.xo.go#L31-L57 | go | train | // Insert inserts the AuthGroupPermission to the database. | func (agp *AuthGroupPermission) Insert(db XODB) error | // Insert inserts the AuthGroupPermission to the database.
func (agp *AuthGroupPermission) Insert(db XODB) error | {
var err error
// if already exist, bail
if agp._exists {
return errors.New("insert failed: already exists")
}
// sql insert query, primary key provided by sequence
const sqlstr = `INSERT INTO public.auth_group_permissions (` +
`group_id, permission_id` +
`) VALUES (` +
`$1, $2` +
`) RETURNING id`
// run query
XOLog(sqlstr, agp.GroupID, agp.PermissionID)
err = db.QueryRow(sqlstr, agp.GroupID, agp.PermissionID).Scan(&agp.ID)
if err != nil {
return err
}
// set existence
agp._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authgrouppermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authgrouppermission.xo.go#L98-L128 | go | train | // Upsert performs an upsert for AuthGroupPermission.
//
// NOTE: PostgreSQL 9.5+ only | func (agp *AuthGroupPermission) Upsert(db XODB) error | // Upsert performs an upsert for AuthGroupPermission.
//
// NOTE: PostgreSQL 9.5+ only
func (agp *AuthGroupPermission) Upsert(db XODB) error | {
var err error
// if already exist, bail
if agp._exists {
return errors.New("insert failed: already exists")
}
// sql query
const sqlstr = `INSERT INTO public.auth_group_permissions (` +
`id, group_id, permission_id` +
`) VALUES (` +
`$1, $2, $3` +
`) ON CONFLICT (id) DO UPDATE SET (` +
`id, group_id, permission_id` +
`) = (` +
`EXCLUDED.id, EXCLUDED.group_id, EXCLUDED.permission_id` +
`)`
// run query
XOLog(sqlstr, agp.ID, agp.GroupID, agp.PermissionID)
_, err = db.Exec(sqlstr, agp.ID, agp.GroupID, agp.PermissionID)
if err != nil {
return err
}
// set existence
agp._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/authgrouppermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/authgrouppermission.xo.go#L281-L302 | go | train | // AuthGroupPermissionByID retrieves a row from 'public.auth_group_permissions' as a AuthGroupPermission.
//
// Generated from index 'auth_group_permissions_pkey'. | func AuthGroupPermissionByID(db XODB, id int) (*AuthGroupPermission, error) | // AuthGroupPermissionByID retrieves a row from 'public.auth_group_permissions' as a AuthGroupPermission.
//
// Generated from index 'auth_group_permissions_pkey'.
func AuthGroupPermissionByID(db XODB, id int) (*AuthGroupPermission, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, group_id, permission_id ` +
`FROM public.auth_group_permissions ` +
`WHERE id = $1`
// run query
XOLog(sqlstr, id)
agp := AuthGroupPermission{
_exists: true,
}
err = db.QueryRow(sqlstr, id).Scan(&agp.ID, &agp.GroupID, &agp.PermissionID)
if err != nil {
return nil, err
}
return &agp, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/djangosession.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/djangosession.xo.go#L32-L58 | go | train | // Insert inserts the DjangoSession to the database. | func (ds *DjangoSession) Insert(db XODB) error | // Insert inserts the DjangoSession to the database.
func (ds *DjangoSession) Insert(db XODB) error | {
var err error
// if already exist, bail
if ds._exists {
return errors.New("insert failed: already exists")
}
// sql insert query, primary key must be provided
const sqlstr = `INSERT INTO public.django_session (` +
`session_key, session_data, expire_date` +
`) VALUES (` +
`$1, $2, $3` +
`)`
// run query
XOLog(sqlstr, ds.SessionKey, ds.SessionData, ds.ExpireDate)
err = db.QueryRow(sqlstr, ds.SessionKey, ds.SessionData, ds.ExpireDate).Scan(&ds.SessionKey)
if err != nil {
return err
}
// set existence
ds._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/djangosession.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/djangosession.xo.go#L61-L85 | go | train | // Update updates the DjangoSession in the database. | func (ds *DjangoSession) Update(db XODB) error | // Update updates the DjangoSession in the database.
func (ds *DjangoSession) Update(db XODB) error | {
var err error
// if doesn't exist, bail
if !ds._exists {
return errors.New("update failed: does not exist")
}
// if deleted, bail
if ds._deleted {
return errors.New("update failed: marked for deletion")
}
// sql query
const sqlstr = `UPDATE public.django_session SET (` +
`session_data, expire_date` +
`) = ( ` +
`$1, $2` +
`) WHERE session_key = $3`
// run query
XOLog(sqlstr, ds.SessionData, ds.ExpireDate, ds.SessionKey)
_, err = db.Exec(sqlstr, ds.SessionData, ds.ExpireDate, ds.SessionKey)
return err
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/postgres/djangosession.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/postgres/djangosession.xo.go#L229-L263 | go | train | // DjangoSessionsBySessionKey retrieves a row from 'public.django_session' as a DjangoSession.
//
// Generated from index 'django_session_session_key_c0390e0f_like'. | func DjangoSessionsBySessionKey(db XODB, sessionKey string) ([]*DjangoSession, error) | // DjangoSessionsBySessionKey retrieves a row from 'public.django_session' as a DjangoSession.
//
// Generated from index 'django_session_session_key_c0390e0f_like'.
func DjangoSessionsBySessionKey(db XODB, sessionKey string) ([]*DjangoSession, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`session_key, session_data, expire_date ` +
`FROM public.django_session ` +
`WHERE session_key = $1`
// run query
XOLog(sqlstr, sessionKey)
q, err := db.Query(sqlstr, sessionKey)
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 | internal/templates.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/templates.go#L15-L22 | go | train | // TemplateLoader loads templates from the specified name. | func (a *ArgType) TemplateLoader(name string) ([]byte, error) | // TemplateLoader loads templates from the specified name.
func (a *ArgType) TemplateLoader(name string) ([]byte, error) | {
// no template path specified
if a.TemplatePath == "" {
return templates.Asset(name)
}
return ioutil.ReadFile(path.Join(a.TemplatePath, name))
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/templates.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/templates.go#L25-L35 | go | train | // TemplateSet retrieves the created template set. | func (a *ArgType) TemplateSet() *TemplateSet | // TemplateSet retrieves the created template set.
func (a *ArgType) TemplateSet() *TemplateSet | {
if a.templateSet == nil {
a.templateSet = &TemplateSet{
funcs: a.NewTemplateFuncs(),
l: a.TemplateLoader,
tpls: map[string]*template.Template{},
}
}
return a.templateSet
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/templates.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/templates.go#L39-L76 | go | train | // ExecuteTemplate loads and parses the supplied template with name and
// executes it with obj as the context. | func (a *ArgType) ExecuteTemplate(tt TemplateType, name string, sub string, obj interface{}) error | // ExecuteTemplate loads and parses the supplied template with name and
// executes it with obj as the context.
func (a *ArgType) ExecuteTemplate(tt TemplateType, name string, sub string, obj interface{}) error | {
var err error
// setup generated
if a.Generated == nil {
a.Generated = []TBuf{}
}
// create store
v := TBuf{
TemplateType: tt,
Name: name,
Subname: sub,
Buf: new(bytes.Buffer),
}
// build template name
loaderType := ""
if tt != XOTemplate {
if a.LoaderType == "oci8" || a.LoaderType == "ora" {
// force oracle for oci8 since the oracle driver doesn't recognize
// 'oracle' as valid protocol
loaderType = "oracle."
} else {
loaderType = a.LoaderType + "."
}
}
templateName := fmt.Sprintf("%s%s.go.tpl", loaderType, tt)
// execute template
err = a.TemplateSet().Execute(v.Buf, templateName, obj)
if err != nil {
return err
}
a.Generated = append(a.Generated, v)
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | internal/templates.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/internal/templates.go#L87-L104 | go | train | // Execute executes a specified template in the template set using the supplied
// obj as its parameters and writing the output to w. | func (ts *TemplateSet) Execute(w io.Writer, name string, obj interface{}) error | // Execute executes a specified template in the template set using the supplied
// obj as its parameters and writing the output to w.
func (ts *TemplateSet) Execute(w io.Writer, name string, obj interface{}) error | {
tpl, ok := ts.tpls[name]
if !ok {
// attempt to load and parse the template
buf, err := ts.l(name)
if err != nil {
return err
}
// parse template
tpl, err = template.New(name).Funcs(ts.funcs).Parse(string(buf))
if err != nil {
return err
}
}
return tpl.Execute(w, obj)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/sqlite3/authusergroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/sqlite3/authusergroup.xo.go#L92-L98 | go | train | // Save saves the AuthUserGroup to the database. | func (aug *AuthUserGroup) Save(db XODB) error | // Save saves the AuthUserGroup to the database.
func (aug *AuthUserGroup) Save(db XODB) error | {
if aug.Exists() {
return aug.Update(db)
}
return aug.Insert(db)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/sqlite3/authusergroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/sqlite3/authusergroup.xo.go#L133-L135 | go | train | // AuthGroup returns the AuthGroup associated with the AuthUserGroup's GroupID (group_id).
//
// Generated from foreign key 'auth_user_groups_group_id_fkey'. | func (aug *AuthUserGroup) AuthGroup(db XODB) (*AuthGroup, error) | // AuthGroup returns the AuthGroup associated with the AuthUserGroup's GroupID (group_id).
//
// Generated from foreign key 'auth_user_groups_group_id_fkey'.
func (aug *AuthUserGroup) AuthGroup(db XODB) (*AuthGroup, error) | {
return AuthGroupByID(db, aug.GroupID)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/sqlite3/authusergroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/sqlite3/authusergroup.xo.go#L140-L142 | go | train | // AuthUser returns the AuthUser associated with the AuthUserGroup's UserID (user_id).
//
// Generated from foreign key 'auth_user_groups_user_id_fkey'. | func (aug *AuthUserGroup) AuthUser(db XODB) (*AuthUser, error) | // AuthUser returns the AuthUser associated with the AuthUserGroup's UserID (user_id).
//
// Generated from foreign key 'auth_user_groups_user_id_fkey'.
func (aug *AuthUserGroup) AuthUser(db XODB) (*AuthUser, error) | {
return AuthUserByID(db, aug.UserID)
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/sqlite3/authusergroup.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/sqlite3/authusergroup.xo.go#L251-L272 | go | train | // AuthUserGroupByUserIDGroupID retrieves a row from 'auth_user_groups' as a AuthUserGroup.
//
// Generated from index 'auth_user_groups_user_id_94350c0c_uniq'. | func AuthUserGroupByUserIDGroupID(db XODB, userID int, groupID int) (*AuthUserGroup, error) | // AuthUserGroupByUserIDGroupID retrieves a row from 'auth_user_groups' as a AuthUserGroup.
//
// Generated from index 'auth_user_groups_user_id_94350c0c_uniq'.
func AuthUserGroupByUserIDGroupID(db XODB, userID int, groupID int) (*AuthUserGroup, error) | {
var err error
// sql query
const sqlstr = `SELECT ` +
`id, user_id, group_id ` +
`FROM auth_user_groups ` +
`WHERE user_id = ? AND group_id = ?`
// run query
XOLog(sqlstr, userID, groupID)
aug := AuthUserGroup{
_exists: true,
}
err = db.QueryRow(sqlstr, userID, groupID).Scan(&aug.ID, &aug.UserID, &aug.GroupID)
if err != nil {
return nil, err
}
return &aug, nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/sqlite3/authgrouppermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/sqlite3/authgrouppermission.xo.go#L31-L64 | go | train | // Insert inserts the AuthGroupPermission to the database. | func (agp *AuthGroupPermission) Insert(db XODB) error | // Insert inserts the AuthGroupPermission to the database.
func (agp *AuthGroupPermission) Insert(db XODB) error | {
var err error
// if already exist, bail
if agp._exists {
return errors.New("insert failed: already exists")
}
// sql insert query, primary key provided by autoincrement
const sqlstr = `INSERT INTO auth_group_permissions (` +
`group_id, permission_id` +
`) VALUES (` +
`?, ?` +
`)`
// run query
XOLog(sqlstr, agp.GroupID, agp.PermissionID)
res, err := db.Exec(sqlstr, agp.GroupID, agp.PermissionID)
if err != nil {
return err
}
// retrieve id
id, err := res.LastInsertId()
if err != nil {
return err
}
// set primary key and existence
agp.ID = int(id)
agp._exists = true
return nil
} |
xo/xo | 1a94fa516029cb306cce6d379d086e4d5b5bb232 | examples/django/sqlite3/authgrouppermission.xo.go | https://github.com/xo/xo/blob/1a94fa516029cb306cce6d379d086e4d5b5bb232/examples/django/sqlite3/authgrouppermission.xo.go#L67-L89 | go | train | // Update updates the AuthGroupPermission in the database. | func (agp *AuthGroupPermission) Update(db XODB) error | // Update updates the AuthGroupPermission in the database.
func (agp *AuthGroupPermission) Update(db XODB) error | {
var err error
// if doesn't exist, bail
if !agp._exists {
return errors.New("update failed: does not exist")
}
// if deleted, bail
if agp._deleted {
return errors.New("update failed: marked for deletion")
}
// sql query
const sqlstr = `UPDATE auth_group_permissions SET ` +
`group_id = ?, permission_id = ?` +
` WHERE id = ?`
// run query
XOLog(sqlstr, agp.GroupID, agp.PermissionID, agp.ID)
_, err = db.Exec(sqlstr, agp.GroupID, agp.PermissionID, agp.ID)
return err
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.