diff --git a/CHANGELOG.md b/CHANGELOG.md index 15e1527ad8c..15f4fe5fa22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ # 2.0.0 (unreleased) **New features** +- [Issue #1623](https://github.com/grafana/grafana/issues/1623). Share Dashboard: Dashboard snapshot sharing (dash and data snapshot), save to local or save to public snapshot dashboard snapshots.raintank.io site - [Issue #1622](https://github.com/grafana/grafana/issues/1622). Share Panel: The share modal now has an embed option, gives you an iframe that you can use to embedd a single graph on another web site - [Issue #718](https://github.com/grafana/grafana/issues/718). Dashboard: When saving a dashboard and another user has made changes inbetween the user is promted with a warning if he really wants to overwrite the other's changes - [Issue #1331](https://github.com/grafana/grafana/issues/1331). Graph & Singlestat: New axis/unit format selector and more units (kbytes, Joule, Watt, eV), and new design for graph axis & grid tab and single stat options tab views @@ -19,6 +20,7 @@ - [Issue #599](https://github.com/grafana/grafana/issues/599). Graph: Added right y axis label setting and graph support - [Issue #1253](https://github.com/grafana/grafana/issues/1253). Graph & Singlestat: Users can now set decimal precision for legend and tooltips (override auto precision) - [Issue #1255](https://github.com/grafana/grafana/issues/1255). Templating: Dashboard will now wait to load until all template variables that have refresh on load set or are initialized via url to be fully loaded and so all variables are in valid state before panels start issuing metric requests. +- [Issue #1344](https://github.com/grafana/grafana/issues/1344). OpenTSDB: Alias patterns (reference tag values), syntax is: $tag_tagname or [[tag_tagname]] **Fixes** - [Issue #1298](https://github.com/grafana/grafana/issues/1298). InfluxDB: Fix handling of empty array in templating variable query diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 79b49db2f0a..857b045ddd8 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -25,12 +25,12 @@ }, { "ImportPath": "github.com/go-xorm/core", - "Rev": "a949e067ced1cb6e6ef5c38b6f28b074fa718f1e" + "Rev": "be6e7ac47dc57bd0ada25322fa526944f66ccaa6" }, { "ImportPath": "github.com/go-xorm/xorm", - "Comment": "v0.4.1-19-g5c23849", - "Rev": "5c23849a66f4593e68909bb6c1fa30651b5b0541" + "Comment": "v0.4.2-58-ge2889e5", + "Rev": "e2889e5517600b82905f1d2ba8b70deb71823ffe" }, { "ImportPath": "github.com/jtolds/gls", @@ -51,7 +51,7 @@ }, { "ImportPath": "github.com/mattn/go-sqlite3", - "Rev": "d10e2c8f62100097910367dee90a9bd89d426a44" + "Rev": "e28cd440fabdd39b9520344bc26829f61db40ece" }, { "ImportPath": "github.com/smartystreets/goconvey/convey", diff --git a/Godeps/_workspace/src/github.com/go-xorm/core/README.md b/Godeps/_workspace/src/github.com/go-xorm/core/README.md new file mode 100644 index 00000000000..0ae94a584ab --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-xorm/core/README.md @@ -0,0 +1,114 @@ +Core is a lightweight wrapper of sql.DB. + +# Open +```Go +db, _ := core.Open(db, connstr) +``` + +# SetMapper +```Go +db.SetMapper(SameMapper()) +``` + +## Scan usage + +### Scan +```Go +rows, _ := db.Query() +for rows.Next() { + rows.Scan() +} +``` + +### ScanMap +```Go +rows, _ := db.Query() +for rows.Next() { + rows.ScanMap() +``` + +### ScanSlice + +You can use `[]string`, `[][]byte`, `[]interface{}`, `[]*string`, `[]sql.NullString` to ScanSclice. Notice, slice's length should be equal or less than select columns. + +```Go +rows, _ := db.Query() +cols, _ := rows.Columns() +for rows.Next() { + var s = make([]string, len(cols)) + rows.ScanSlice(&s) +} +``` + +```Go +rows, _ := db.Query() +cols, _ := rows.Columns() +for rows.Next() { + var s = make([]*string, len(cols)) + rows.ScanSlice(&s) +} +``` + +### ScanStruct +```Go +rows, _ := db.Query() +for rows.Next() { + rows.ScanStructByName() + rows.ScanStructByIndex() +} +``` + +## Query usage +```Go +rows, err := db.Query("select * from table where name = ?", name) + +user = User{ + Name:"lunny", +} +rows, err := db.QueryStruct("select * from table where name = ?Name", + &user) + +var user = map[string]interface{}{ + "name": "lunny", +} +rows, err = db.QueryMap("select * from table where name = ?name", + &user) +``` + +## QueryRow usage +```Go +row := db.QueryRow("select * from table where name = ?", name) + +user = User{ + Name:"lunny", +} +row := db.QueryRowStruct("select * from table where name = ?Name", + &user) + +var user = map[string]interface{}{ + "name": "lunny", +} +row = db.QueryRowMap("select * from table where name = ?name", + &user) +``` + +## Exec usage +```Go +db.Exec("insert into user (`name`, title, age, alias, nick_name,created) values (?,?,?,?,?,?)", name, title, age, alias...) + +user = User{ + Name:"lunny", + Title:"test", + Age: 18, +} +result, err = db.ExecStruct("insert into user (`name`, title, age, alias, nick_name,created) values (?Name,?Title,?Age,?Alias,?NickName,?Created)", + &user) + +var user = map[string]interface{}{ + "Name": "lunny", + "Title": "test", + "Age": 18, +} +result, err = db.ExecMap("insert into user (`name`, title, age, alias, nick_name,created) values (?Name,?Title,?Age,?Alias,?NickName,?Created)", + &user) +``` \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/go-xorm/core/column.go b/Godeps/_workspace/src/github.com/go-xorm/core/column.go index 18921ca7c4c..52468aa20e6 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/core/column.go +++ b/Godeps/_workspace/src/github.com/go-xorm/core/column.go @@ -121,6 +121,21 @@ func (col *Column) ValueOfV(dataStruct *reflect.Value) (*reflect.Value, error) { col.fieldPath = strings.Split(col.FieldName, ".") } + if dataStruct.Type().Kind() == reflect.Map { + var keyValue reflect.Value + + if len(col.fieldPath) == 1 { + keyValue = reflect.ValueOf(col.FieldName) + } else if len(col.fieldPath) == 2 { + keyValue = reflect.ValueOf(col.fieldPath[1]) + } else { + return nil, fmt.Errorf("Unsupported mutliderive %v", col.FieldName) + } + + fieldValue = dataStruct.MapIndex(keyValue) + return &fieldValue, nil + } + if len(col.fieldPath) == 1 { fieldValue = dataStruct.FieldByName(col.FieldName) } else if len(col.fieldPath) == 2 { diff --git a/Godeps/_workspace/src/github.com/go-xorm/core/dialect.go b/Godeps/_workspace/src/github.com/go-xorm/core/dialect.go index 05375642610..43a22670913 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/core/dialect.go +++ b/Godeps/_workspace/src/github.com/go-xorm/core/dialect.go @@ -47,15 +47,13 @@ type Dialect interface { SupportInsertMany() bool SupportEngine() bool SupportCharset() bool + SupportDropIfExists() bool IndexOnTable() bool ShowCreateNull() bool IndexCheckSql(tableName, idxName string) (string, []interface{}) TableCheckSql(tableName string) (string, []interface{}) - //ColumnCheckSql(tableName, colName string) (string, []interface{}) - //IsTableExist(tableName string) (bool, error) - //IsIndexExist(tableName string, idx *Index) (bool, error) IsColumnExist(tableName string, col *Column) (bool, error) CreateTableSql(table *Table, tableName, storeEngine, charset string) string @@ -65,15 +63,13 @@ type Dialect interface { ModifyColumnSql(tableName string, col *Column) string + //CreateTableIfNotExists(table *Table, tableName, storeEngine, charset string) error + //MustDropTable(tableName string) error + GetColumns(tableName string) ([]string, map[string]*Column, error) GetTables() ([]*Table, error) GetIndexes(tableName string) (map[string]*Index, error) - // Get data from db cell to a struct's field - //GetData(col *Column, fieldValue *reflect.Value, cellData interface{}) error - // Set field data to db - //SetData(col *Column, fieldValue *refelct.Value) (interface{}, error) - Filters() []Filter } @@ -144,6 +140,10 @@ func (db *Base) RollBackStr() string { return "ROLL BACK" } +func (db *Base) SupportDropIfExists() bool { + return true +} + func (db *Base) DropTableSql(tableName string) string { return fmt.Sprintf("DROP TABLE IF EXISTS `%s`", tableName) } @@ -170,35 +170,52 @@ func (db *Base) IsColumnExist(tableName string, col *Column) (bool, error) { return db.HasRecords(query, db.DbName, tableName, col.Name) } +/* +func (db *Base) CreateTableIfNotExists(table *Table, tableName, storeEngine, charset string) error { + sql, args := db.dialect.TableCheckSql(tableName) + rows, err := db.DB().Query(sql, args...) + if db.Logger != nil { + db.Logger.Info("[sql]", sql, args) + } + if err != nil { + return err + } + defer rows.Close() + + if rows.Next() { + return nil + } + + sql = db.dialect.CreateTableSql(table, tableName, storeEngine, charset) + _, err = db.DB().Exec(sql) + if db.Logger != nil { + db.Logger.Info("[sql]", sql) + } + return err +}*/ + func (db *Base) CreateIndexSql(tableName string, index *Index) string { quote := db.dialect.Quote var unique string var idxName string if index.Type == UniqueType { unique = " UNIQUE" - idxName = fmt.Sprintf("UQE_%v_%v", tableName, index.Name) - } else { - idxName = fmt.Sprintf("IDX_%v_%v", tableName, index.Name) } - return fmt.Sprintf("CREATE%s INDEX %v ON %v (%v);", unique, + idxName = index.XName(tableName) + return fmt.Sprintf("CREATE%s INDEX %v ON %v (%v)", unique, quote(idxName), quote(tableName), quote(strings.Join(index.Cols, quote(",")))) } func (db *Base) DropIndexSql(tableName string, index *Index) string { quote := db.dialect.Quote - //var unique string - var idxName string = index.Name - if !strings.HasPrefix(idxName, "UQE_") && - !strings.HasPrefix(idxName, "IDX_") { - if index.Type == UniqueType { - idxName = fmt.Sprintf("UQE_%v_%v", tableName, index.Name) - } else { - idxName = fmt.Sprintf("IDX_%v_%v", tableName, index.Name) - } + var name string + if index.IsRegular { + name = index.XName(tableName) + } else { + name = index.Name } - return fmt.Sprintf("DROP INDEX %v ON %s", - quote(idxName), quote(tableName)) + return fmt.Sprintf("DROP INDEX %v ON %s", quote(name), quote(tableName)) } func (db *Base) ModifyColumnSql(tableName string, col *Column) string { diff --git a/Godeps/_workspace/src/github.com/go-xorm/core/index.go b/Godeps/_workspace/src/github.com/go-xorm/core/index.go index e8f447d7031..73b95175adc 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/core/index.go +++ b/Godeps/_workspace/src/github.com/go-xorm/core/index.go @@ -1,7 +1,9 @@ package core import ( + "fmt" "sort" + "strings" ) const ( @@ -11,9 +13,21 @@ const ( // database index type Index struct { - Name string - Type int - Cols []string + IsRegular bool + Name string + Type int + Cols []string +} + +func (index *Index) XName(tableName string) string { + if !strings.HasPrefix(index.Name, "UQE_") && + !strings.HasPrefix(index.Name, "IDX_") { + if index.Type == UniqueType { + return fmt.Sprintf("UQE_%v_%v", tableName, index.Name) + } + return fmt.Sprintf("IDX_%v_%v", tableName, index.Name) + } + return index.Name } // add columns which will be composite index @@ -24,6 +38,9 @@ func (index *Index) AddColumn(cols ...string) { } func (index *Index) Equal(dst *Index) bool { + if index.Type != dst.Type { + return false + } if len(index.Cols) != len(dst.Cols) { return false } @@ -40,5 +57,5 @@ func (index *Index) Equal(dst *Index) bool { // new an index func NewIndex(name string, indexType int) *Index { - return &Index{name, indexType, make([]string, 0)} + return &Index{true, name, indexType, make([]string, 0)} } diff --git a/Godeps/_workspace/src/github.com/go-xorm/core/mapper.go b/Godeps/_workspace/src/github.com/go-xorm/core/mapper.go index c00dc395211..bb72a156624 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/core/mapper.go +++ b/Godeps/_workspace/src/github.com/go-xorm/core/mapper.go @@ -9,7 +9,6 @@ import ( type IMapper interface { Obj2Table(string) string Table2Obj(string) string - TableName(string) string } type CacheMapper struct { @@ -56,10 +55,6 @@ func (m *CacheMapper) Table2Obj(t string) string { return o } -func (m *CacheMapper) TableName(t string) string { - return t -} - // SameMapper implements IMapper and provides same name between struct and // database table type SameMapper struct { @@ -73,10 +68,6 @@ func (m SameMapper) Table2Obj(t string) string { return t } -func (m SameMapper) TableName(t string) string { - return t -} - // SnakeMapper implements IMapper and provides name transaltion between // struct and database table type SnakeMapper struct { @@ -97,25 +88,6 @@ func snakeCasedName(name string) string { return string(newstr) } -/*func pascal2Sql(s string) (d string) { - d = "" - lastIdx := 0 - for i := 0; i < len(s); i++ { - if s[i] >= 'A' && s[i] <= 'Z' { - if lastIdx < i { - d += s[lastIdx+1 : i] - } - if i != 0 { - d += "_" - } - d += string(s[i] + 32) - lastIdx = i - } - } - d += s[lastIdx+1:] - return -}*/ - func (mapper SnakeMapper) Obj2Table(name string) string { return snakeCasedName(name) } @@ -148,9 +120,103 @@ func (mapper SnakeMapper) Table2Obj(name string) string { return titleCasedName(name) } -func (mapper SnakeMapper) TableName(t string) string { - return t +// GonicMapper implements IMapper. It will consider initialisms when mapping names. +// E.g. id -> ID, user -> User and to table names: UserID -> user_id, MyUID -> my_uid +type GonicMapper map[string]bool + +func isASCIIUpper(r rune) bool { + return 'A' <= r && r <= 'Z' } + +func toASCIIUpper(r rune) rune { + if 'a' <= r && r <= 'z' { + r -= ('a' - 'A') + } + return r +} + +func gonicCasedName(name string) string { + newstr := make([]rune, 0, len(name)+3) + for idx, chr := range name { + if isASCIIUpper(chr) && idx > 0 { + if !isASCIIUpper(newstr[len(newstr)-1]) { + newstr = append(newstr, '_') + } + } + + if !isASCIIUpper(chr) && idx > 1 { + l := len(newstr) + if isASCIIUpper(newstr[l-1]) && isASCIIUpper(newstr[l-2]) { + newstr = append(newstr, newstr[l-1]) + newstr[l-1] = '_' + } + } + + newstr = append(newstr, chr) + } + return strings.ToLower(string(newstr)) +} + +func (mapper GonicMapper) Obj2Table(name string) string { + return gonicCasedName(name) +} + +func (mapper GonicMapper) Table2Obj(name string) string { + newstr := make([]rune, 0) + + name = strings.ToLower(name) + parts := strings.Split(name, "_") + + for _, p := range parts { + _, isInitialism := mapper[strings.ToUpper(p)] + for i, r := range p { + if i == 0 || isInitialism { + r = toASCIIUpper(r) + } + newstr = append(newstr, r) + } + } + + return string(newstr) +} + +// A GonicMapper that contains a list of common initialisms taken from golang/lint +var LintGonicMapper = GonicMapper{ + "API": true, + "ASCII": true, + "CPU": true, + "CSS": true, + "DNS": true, + "EOF": true, + "GUID": true, + "HTML": true, + "HTTP": true, + "HTTPS": true, + "ID": true, + "IP": true, + "JSON": true, + "LHS": true, + "QPS": true, + "RAM": true, + "RHS": true, + "RPC": true, + "SLA": true, + "SMTP": true, + "SSH": true, + "TLS": true, + "TTL": true, + "UI": true, + "UID": true, + "UUID": true, + "URI": true, + "URL": true, + "UTF8": true, + "VM": true, + "XML": true, + "XSRF": true, + "XSS": true, +} + // provide prefix table name support type PrefixMapper struct { Mapper IMapper @@ -165,10 +231,6 @@ func (mapper PrefixMapper) Table2Obj(name string) string { return mapper.Mapper.Table2Obj(name[len(mapper.Prefix):]) } -func (mapper PrefixMapper) TableName(name string) string { - return mapper.Prefix + name -} - func NewPrefixMapper(mapper IMapper, prefix string) PrefixMapper { return PrefixMapper{mapper, prefix} } @@ -187,10 +249,6 @@ func (mapper SuffixMapper) Table2Obj(name string) string { return mapper.Mapper.Table2Obj(name[:len(name)-len(mapper.Suffix)]) } -func (mapper SuffixMapper) TableName(name string) string { - return name + mapper.Suffix -} - func NewSuffixMapper(mapper IMapper, suffix string) SuffixMapper { return SuffixMapper{mapper, suffix} } diff --git a/Godeps/_workspace/src/github.com/go-xorm/core/mapper_test.go b/Godeps/_workspace/src/github.com/go-xorm/core/mapper_test.go new file mode 100644 index 00000000000..043087a2af1 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-xorm/core/mapper_test.go @@ -0,0 +1,45 @@ +package core + +import ( + "testing" +) + +func TestGonicMapperFromObj(t *testing.T) { + testCases := map[string]string{ + "HTTPLib": "http_lib", + "id": "id", + "ID": "id", + "IDa": "i_da", + "iDa": "i_da", + "IDAa": "id_aa", + "aID": "a_id", + "aaID": "aa_id", + "aaaID": "aaa_id", + "MyREalFunkYLONgNAME": "my_r_eal_funk_ylo_ng_name", + } + + for in, expected := range testCases { + out := gonicCasedName(in) + if out != expected { + t.Errorf("Given %s, expected %s but got %s", in, expected, out) + } + } +} + +func TestGonicMapperToObj(t *testing.T) { + testCases := map[string]string{ + "http_lib": "HTTPLib", + "id": "ID", + "ida": "Ida", + "id_aa": "IDAa", + "aa_id": "AaID", + "my_r_eal_funk_ylo_ng_name": "MyREalFunkYloNgName", + } + + for in, expected := range testCases { + out := LintGonicMapper.Table2Obj(in) + if out != expected { + t.Errorf("Given %s, expected %s but got %s", in, expected, out) + } + } +} diff --git a/Godeps/_workspace/src/github.com/go-xorm/core/pk.go b/Godeps/_workspace/src/github.com/go-xorm/core/pk.go index 61d1371e67c..1810dd944be 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/core/pk.go +++ b/Godeps/_workspace/src/github.com/go-xorm/core/pk.go @@ -1,7 +1,8 @@ package core import ( - "encoding/json" + "bytes" + "encoding/gob" ) type PK []interface{} @@ -12,14 +13,14 @@ func NewPK(pks ...interface{}) *PK { } func (p *PK) ToString() (string, error) { - bs, err := json.Marshal(*p) - if err != nil { - return "", nil - } - - return string(bs), nil + buf := new(bytes.Buffer) + enc := gob.NewEncoder(buf) + err := enc.Encode(*p) + return buf.String(), err } func (p *PK) FromString(content string) error { - return json.Unmarshal([]byte(content), p) + dec := gob.NewDecoder(bytes.NewBufferString(content)) + err := dec.Decode(p) + return err } diff --git a/Godeps/_workspace/src/github.com/go-xorm/core/pk_test.go b/Godeps/_workspace/src/github.com/go-xorm/core/pk_test.go index 5245e574800..05486086e6a 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/core/pk_test.go +++ b/Godeps/_workspace/src/github.com/go-xorm/core/pk_test.go @@ -2,6 +2,7 @@ package core import ( "fmt" + "reflect" "testing" ) @@ -19,4 +20,14 @@ func TestPK(t *testing.T) { t.Error(err) } fmt.Println(s) + + if len(*p) != len(*s) { + t.Fatal("p", *p, "should be equal", *s) + } + + for i, ori := range *p { + if ori != (*s)[i] { + t.Fatal("ori", ori, reflect.ValueOf(ori), "should be equal", (*s)[i], reflect.ValueOf((*s)[i])) + } + } } diff --git a/Godeps/_workspace/src/github.com/go-xorm/core/table.go b/Godeps/_workspace/src/github.com/go-xorm/core/table.go index f7c9d464842..aba1f96e748 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/core/table.go +++ b/Godeps/_workspace/src/github.com/go-xorm/core/table.go @@ -65,13 +65,18 @@ func (table *Table) GetColumnIdx(name string, idx int) *Column { // if has primary key, return column func (table *Table) PKColumns() []*Column { - columns := make([]*Column, 0) - for _, name := range table.PrimaryKeys { - columns = append(columns, table.GetColumn(name)) + columns := make([]*Column, len(table.PrimaryKeys)) + for i, name := range table.PrimaryKeys { + columns[i] = table.GetColumn(name) } return columns } +func (table *Table) ColumnType(name string) reflect.Type { + t, _ := table.Type.FieldByName(name) + return t.Type +} + func (table *Table) AutoIncrColumn() *Column { return table.GetColumn(table.AutoIncrement) } diff --git a/Godeps/_workspace/src/github.com/go-xorm/core/type.go b/Godeps/_workspace/src/github.com/go-xorm/core/type.go index ee7656824c1..73b9921ee63 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/core/type.go +++ b/Godeps/_workspace/src/github.com/go-xorm/core/type.go @@ -70,6 +70,7 @@ var ( NVarchar = "NVARCHAR" TinyText = "TINYTEXT" Text = "TEXT" + Clob = "CLOB" MediumText = "MEDIUMTEXT" LongText = "LONGTEXT" Uuid = "UUID" @@ -120,6 +121,7 @@ var ( MediumText: TEXT_TYPE, LongText: TEXT_TYPE, Uuid: TEXT_TYPE, + Clob: TEXT_TYPE, Date: TIME_TYPE, DateTime: TIME_TYPE, @@ -250,7 +252,7 @@ func Type2SQLType(t reflect.Type) (st SQLType) { case reflect.String: st = SQLType{Varchar, 255, 0} case reflect.Struct: - if t == reflect.TypeOf(c_TIME_DEFAULT) { + if t.ConvertibleTo(reflect.TypeOf(c_TIME_DEFAULT)) { st = SQLType{DateTime, 0, 0} } else { // TODO need to handle association struct @@ -303,7 +305,7 @@ func SQLType2Type(st SQLType) reflect.Type { return reflect.TypeOf(float32(1)) case Double: return reflect.TypeOf(float64(1)) - case Char, Varchar, NVarchar, TinyText, Text, MediumText, LongText, Enum, Set, Uuid: + case Char, Varchar, NVarchar, TinyText, Text, MediumText, LongText, Enum, Set, Uuid, Clob: return reflect.TypeOf("") case TinyBlob, Blob, LongBlob, Bytea, Binary, MediumBlob, VarBinary: return reflect.TypeOf([]byte{}) diff --git a/Godeps/_workspace/src/github.com/go-xorm/xorm/README.md b/Godeps/_workspace/src/github.com/go-xorm/xorm/README.md index 158f5c11dda..fe8aca3c374 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/xorm/README.md +++ b/Godeps/_workspace/src/github.com/go-xorm/xorm/README.md @@ -82,11 +82,13 @@ Or # Cases +* [Wego](http://github.com/go-tango/wego) + * [Docker.cn](https://docker.cn/) * [Gogs](http://try.gogits.org) - [github.com/gogits/gogs](http://github.com/gogits/gogs) -* [Gorevel](http://http://gorevel.cn/) - [github.com/goofcc/gorevel](http://github.com/goofcc/gorevel) +* [Gorevel](http://gorevel.cn/) - [github.com/goofcc/gorevel](http://github.com/goofcc/gorevel) * [Gowalker](http://gowalker.org) - [github.com/Unknwon/gowalker](http://github.com/Unknwon/gowalker) diff --git a/Godeps/_workspace/src/github.com/go-xorm/xorm/README_CN.md b/Godeps/_workspace/src/github.com/go-xorm/xorm/README_CN.md index 5def1c38a57..5a167f9b148 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/xorm/README_CN.md +++ b/Godeps/_workspace/src/github.com/go-xorm/xorm/README_CN.md @@ -44,16 +44,10 @@ xorm是一个简单而强大的Go语言ORM库. 通过它可以使数据库操作 ## 更新日志 -* **v0.4.0 RC1** - 新特性: - * 移动xorm cmd [github.com/go-xorm/cmd](github.com/go-xorm/cmd) - * 在重构一般DB操作核心库 [github.com/go-xorm/core](https://github.com/go-xorm/core) - * 移动测试github.com/复XORM/测试 [github.com/go-xorm/tests](github.com/go-xorm/tests) - - 改进: - * Prepared statement 缓存 - * 添加 Incr API - * 指定时区位置 +* **v0.4.2** + 新特性: + * deleted标记 + * bug fixed [更多更新日志...](https://github.com/go-xorm/manual-zh-CN/tree/master/chapter-16) @@ -78,6 +72,8 @@ xorm是一个简单而强大的Go语言ORM库. 通过它可以使数据库操作 ## 案例 +* [Wego](http://github.com/go-tango/wego) + * [Docker.cn](https://docker.cn/) * [Gogs](http://try.gogits.org) - [github.com/gogits/gogs](http://github.com/gogits/gogs) diff --git a/Godeps/_workspace/src/github.com/go-xorm/xorm/VERSION b/Godeps/_workspace/src/github.com/go-xorm/xorm/VERSION index af81cfc7d96..4e64e0e9e47 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/xorm/VERSION +++ b/Godeps/_workspace/src/github.com/go-xorm/xorm/VERSION @@ -1 +1 @@ -xorm v0.4.1 +xorm v0.4.2.0225 diff --git a/Godeps/_workspace/src/github.com/go-xorm/xorm/doc.go b/Godeps/_workspace/src/github.com/go-xorm/xorm/doc.go index adc1d2d54e1..722088ca775 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/xorm/doc.go +++ b/Godeps/_workspace/src/github.com/go-xorm/xorm/doc.go @@ -63,21 +63,22 @@ There are 7 major ORM methods and many helpful methods to use to operate databas // SELECT * FROM user 4. Query multiple records and record by record handle, there two methods, one is Iterate, -another is Raws +another is Rows err := engine.Iterate(...) // SELECT * FROM user - raws, err := engine.Raws(...) + rows, err := engine.Rows(...) // SELECT * FROM user + defer rows.Close() bean := new(Struct) - for raws.Next() { - err = raws.Scan(bean) + for rows.Next() { + err = rows.Scan(bean) } 5. Update one or more records - affected, err := engine.Update(&user) + affected, err := engine.Id(...).Update(&user) // UPDATE user SET ... 6. Delete one or more records, Delete MUST has conditon @@ -150,6 +151,6 @@ Attention: the above 7 methods should be the last chainable method. engine.Join("LEFT", "userdetail", "user.id=userdetail.id").Find() //SELECT * FROM user LEFT JOIN userdetail ON user.id=userdetail.id -More usage, please visit https://github.com/go-xorm/xorm/blob/master/docs/QuickStartEn.md +More usage, please visit http://xorm.io/docs */ package xorm diff --git a/Godeps/_workspace/src/github.com/go-xorm/xorm/engine.go b/Godeps/_workspace/src/github.com/go-xorm/xorm/engine.go index 700f46a1606..8f0c805dc34 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/xorm/engine.go +++ b/Godeps/_workspace/src/github.com/go-xorm/xorm/engine.go @@ -344,7 +344,7 @@ func (engine *Engine) DBMetas() ([]*core.Table, error) { if col := table.GetColumn(name); col != nil { col.Indexes[index.Name] = true } else { - return nil, fmt.Errorf("Unknown col "+name+" in indexes %v", index) + return nil, fmt.Errorf("Unknown col "+name+" in indexes %v of table", index, table.ColumnsSeq()) } } } @@ -352,6 +352,9 @@ func (engine *Engine) DBMetas() ([]*core.Table, error) { return tables, nil } +/* +dump database all table structs and data to a file +*/ func (engine *Engine) DumpAllToFile(fp string) error { f, err := os.Create(fp) if err != nil { @@ -361,6 +364,9 @@ func (engine *Engine) DumpAllToFile(fp string) error { return engine.DumpAll(f) } +/* +dump database all table structs and data to w +*/ func (engine *Engine) DumpAll(w io.Writer) error { tables, err := engine.DBMetas() if err != nil { @@ -558,6 +564,13 @@ func (engine *Engine) Decr(column string, arg ...interface{}) *Session { return session.Decr(column, arg...) } +// Method SetExpr provides a update string like "column = {expression}" +func (engine *Engine) SetExpr(column string, expression string) *Session { + session := engine.NewSession() + session.IsAutoClose = true + return session.SetExpr(column, expression) +} + // Temporarily change the Get, Find, Update's table func (engine *Engine) Table(tableNameOrBean interface{}) *Session { session := engine.NewSession() @@ -766,7 +779,12 @@ func (engine *Engine) mapType(v reflect.Value) *core.Table { col.IsPrimaryKey = true col.Nullable = false case k == "NULL": - col.Nullable = (strings.ToUpper(tags[j-1]) != "NOT") + if j == 0 { + col.Nullable = true + } else { + col.Nullable = (strings.ToUpper(tags[j-1]) != "NOT") + } + // TODO: for postgres how add autoincr? /*case strings.HasPrefix(k, "AUTOINCR(") && strings.HasSuffix(k, ")"): col.IsAutoIncrement = true @@ -915,7 +933,7 @@ func (engine *Engine) mapType(v reflect.Value) *core.Table { table.AddColumn(col) - if fieldType.Kind() == reflect.Int64 && (col.FieldName == "Id" || strings.HasSuffix(col.FieldName, ".Id")) { + if fieldType.Kind() == reflect.Int64 && (strings.ToUpper(col.FieldName) == "ID" || strings.HasSuffix(strings.ToUpper(col.FieldName), ".ID")) { idFieldColName = col.Name } } // end for @@ -959,40 +977,25 @@ func (engine *Engine) mapping(beans ...interface{}) (e error) { // If a table has any reocrd func (engine *Engine) IsTableEmpty(bean interface{}) (bool, error) { - v := rValue(bean) - t := v.Type() - if t.Kind() != reflect.Struct { - return false, errors.New("bean should be a struct or struct's point") - } - engine.autoMapType(v) session := engine.NewSession() defer session.Close() - rows, err := session.Count(bean) - return rows == 0, err + return session.IsTableEmpty(bean) } // If a table is exist -func (engine *Engine) IsTableExist(bean interface{}) (bool, error) { - v := rValue(bean) - var tableName string - if v.Type().Kind() == reflect.String { - tableName = bean.(string) - } else if v.Type().Kind() == reflect.Struct { - table := engine.autoMapType(v) - tableName = table.Name - } else { - return false, errors.New("bean should be a struct or struct's point") - } - +func (engine *Engine) IsTableExist(beanOrTableName interface{}) (bool, error) { session := engine.NewSession() defer session.Close() - has, err := session.isTableExist(tableName) - return has, err + return session.IsTableExist(beanOrTableName) } func (engine *Engine) IdOf(bean interface{}) core.PK { - table := engine.TableInfo(bean) - v := reflect.Indirect(reflect.ValueOf(bean)) + return engine.IdOfV(reflect.ValueOf(bean)) +} + +func (engine *Engine) IdOfV(rv reflect.Value) core.PK { + v := reflect.Indirect(rv) + table := engine.autoMapType(v) pk := make([]interface{}, len(table.PrimaryKeys)) for i, col := range table.PKColumns() { pkField := v.FieldByName(col.FieldName) @@ -1109,7 +1112,7 @@ func (engine *Engine) Sync(beans ...interface{}) error { session := engine.NewSession() session.Statement.RefTable = table defer session.Close() - isExist, err := session.isColumnExist(table.Name, col) + isExist, err := session.Engine.dialect.IsColumnExist(table.Name, col) if err != nil { return err } @@ -1222,8 +1225,9 @@ func (engine *Engine) CreateTables(beans ...interface{}) error { func (engine *Engine) DropTables(beans ...interface{}) error { session := engine.NewSession() - err := session.Begin() defer session.Close() + + err := session.Begin() if err != nil { return err } @@ -1258,13 +1262,6 @@ func (engine *Engine) Query(sql string, paramStr ...interface{}) (resultsSlice [ return session.Query(sql, paramStr...) } -// Exec a raw sql and return records as []map[string]string -func (engine *Engine) Q(sql string, paramStr ...interface{}) (resultsSlice []map[string]string, err error) { - session := engine.NewSession() - defer session.Close() - return session.Q(sql, paramStr...) -} - // Insert one or more records func (engine *Engine) Insert(beans ...interface{}) (int64, error) { session := engine.NewSession() @@ -1371,18 +1368,11 @@ func (engine *Engine) Import(r io.Reader) ([]sql.Result, error) { scanner.Split(semiColSpliter) - session := engine.NewSession() - defer session.Close() - err := session.newDb() - if err != nil { - return results, err - } - for scanner.Scan() { query := scanner.Text() query = strings.Trim(query, " \t") if len(query) > 0 { - result, err := session.Db.Exec(query) + result, err := engine.DB().Exec(query) results = append(results, result) if err != nil { lastError = err @@ -1409,7 +1399,15 @@ func (engine *Engine) NowTime(sqlTypeName string) interface{} { return engine.FormatTime(sqlTypeName, t) } +func (engine *Engine) NowTime2(sqlTypeName string) (interface{}, time.Time) { + t := time.Now() + return engine.FormatTime(sqlTypeName, t), t +} + func (engine *Engine) FormatTime(sqlTypeName string, t time.Time) (v interface{}) { + if engine.dialect.DBType() == core.ORACLE { + return t + } switch sqlTypeName { case core.Time: s := engine.TZTime(t).Format("2006-01-02 15:04:05") //time.RFC3339 @@ -1419,6 +1417,8 @@ func (engine *Engine) FormatTime(sqlTypeName string, t time.Time) (v interface{} case core.DateTime, core.TimeStamp: if engine.dialect.DBType() == "ql" { v = engine.TZTime(t) + } else if engine.dialect.DBType() == "sqlite3" { + v = engine.TZTime(t).UTC().Format("2006-01-02 15:04:05") } else { v = engine.TZTime(t).Format("2006-01-02 15:04:05") } @@ -1430,6 +1430,8 @@ func (engine *Engine) FormatTime(sqlTypeName string, t time.Time) (v interface{} } else { v = engine.TZTime(t).Format(time.RFC3339Nano) } + case core.BigInt, core.Int: + v = engine.TZTime(t).Unix() default: v = engine.TZTime(t) } diff --git a/Godeps/_workspace/src/github.com/go-xorm/xorm/helpers.go b/Godeps/_workspace/src/github.com/go-xorm/xorm/helpers.go index 4d20141cad3..7eaa1dd1c21 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/xorm/helpers.go +++ b/Godeps/_workspace/src/github.com/go-xorm/xorm/helpers.go @@ -11,6 +11,43 @@ import ( "github.com/go-xorm/core" ) +func isZero(k interface{}) bool { + switch k.(type) { + case int: + return k.(int) == 0 + case int8: + return k.(int8) == 0 + case int16: + return k.(int16) == 0 + case int32: + return k.(int32) == 0 + case int64: + return k.(int64) == 0 + case uint: + return k.(uint) == 0 + case uint8: + return k.(uint8) == 0 + case uint16: + return k.(uint16) == 0 + case uint32: + return k.(uint32) == 0 + case uint64: + return k.(uint64) == 0 + case string: + return k.(string) == "" + } + return false +} + +func isPKZero(pk core.PK) bool { + for _, k := range pk { + if isZero(k) { + return true + } + } + return false +} + func indexNoCase(s, sep string) int { return strings.Index(strings.ToLower(s), strings.ToLower(sep)) } @@ -163,3 +200,182 @@ func rows2maps(rows *core.Rows) (resultsSlice []map[string][]byte, err error) { return resultsSlice, nil } + +func row2map(rows *core.Rows, fields []string) (resultsMap map[string][]byte, err error) { + result := make(map[string][]byte) + scanResultContainers := make([]interface{}, len(fields)) + for i := 0; i < len(fields); i++ { + var scanResultContainer interface{} + scanResultContainers[i] = &scanResultContainer + } + if err := rows.Scan(scanResultContainers...); err != nil { + return nil, err + } + + for ii, key := range fields { + rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[ii])) + //if row is null then ignore + if rawValue.Interface() == nil { + //fmt.Println("ignore ...", key, rawValue) + continue + } + + if data, err := value2Bytes(&rawValue); err == nil { + result[key] = data + } else { + return nil, err // !nashtsai! REVIEW, should return err or just error log? + } + } + return result, nil +} + +func row2mapStr(rows *core.Rows, fields []string) (resultsMap map[string]string, err error) { + result := make(map[string]string) + scanResultContainers := make([]interface{}, len(fields)) + for i := 0; i < len(fields); i++ { + var scanResultContainer interface{} + scanResultContainers[i] = &scanResultContainer + } + if err := rows.Scan(scanResultContainers...); err != nil { + return nil, err + } + + for ii, key := range fields { + rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[ii])) + //if row is null then ignore + if rawValue.Interface() == nil { + //fmt.Println("ignore ...", key, rawValue) + continue + } + + if data, err := value2String(&rawValue); err == nil { + result[key] = data + } else { + return nil, err // !nashtsai! REVIEW, should return err or just error log? + } + } + return result, nil +} + +func txQuery2(tx *core.Tx, sqlStr string, params ...interface{}) (resultsSlice []map[string]string, err error) { + rows, err := tx.Query(sqlStr, params...) + if err != nil { + return nil, err + } + defer rows.Close() + + return rows2Strings(rows) +} + +func query2(db *core.DB, sqlStr string, params ...interface{}) (resultsSlice []map[string]string, err error) { + s, err := db.Prepare(sqlStr) + if err != nil { + return nil, err + } + defer s.Close() + rows, err := s.Query(params...) + if err != nil { + return nil, err + } + defer rows.Close() + return rows2Strings(rows) +} + +func setColumnTime(bean interface{}, col *core.Column, t time.Time) { + v, err := col.ValueOf(bean) + if err != nil { + return + } + if v.CanSet() { + switch v.Type().Kind() { + case reflect.Struct: + v.Set(reflect.ValueOf(t).Convert(v.Type())) + case reflect.Int, reflect.Int64, reflect.Int32: + v.SetInt(t.Unix()) + case reflect.Uint, reflect.Uint64, reflect.Uint32: + v.SetUint(uint64(t.Unix())) + } + } +} + +func genCols(table *core.Table, session *Session, bean interface{}, useCol bool, includeQuote bool) ([]string, []interface{}, error) { + colNames := make([]string, 0) + args := make([]interface{}, 0) + + for _, col := range table.Columns() { + lColName := strings.ToLower(col.Name) + if useCol && !col.IsVersion && !col.IsCreated && !col.IsUpdated { + if _, ok := session.Statement.columnMap[lColName]; !ok { + continue + } + } + if col.MapType == core.ONLYFROMDB { + continue + } + + fieldValuePtr, err := col.ValueOf(bean) + if err != nil { + session.Engine.LogError(err) + continue + } + fieldValue := *fieldValuePtr + + if col.IsAutoIncrement { + switch fieldValue.Type().Kind() { + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int, reflect.Int64: + if fieldValue.Int() == 0 { + continue + } + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint, reflect.Uint64: + if fieldValue.Uint() == 0 { + continue + } + case reflect.String: + if len(fieldValue.String()) == 0 { + continue + } + } + } + + if col.IsDeleted { + continue + } + + if session.Statement.ColumnStr != "" { + if _, ok := session.Statement.columnMap[lColName]; !ok { + continue + } + } + if session.Statement.OmitStr != "" { + if _, ok := session.Statement.columnMap[lColName]; ok { + continue + } + } + + if (col.IsCreated || col.IsUpdated) && session.Statement.UseAutoTime { + val, t := session.Engine.NowTime2(col.SQLType.Name) + args = append(args, val) + + var colName = col.Name + session.afterClosures = append(session.afterClosures, func(bean interface{}) { + col := table.GetColumn(colName) + setColumnTime(bean, col, t) + }) + } else if col.IsVersion && session.Statement.checkVersion { + args = append(args, 1) + } else { + arg, err := session.value2Interface(col, fieldValue) + if err != nil { + return colNames, args, err + } + args = append(args, arg) + } + + if includeQuote { + colNames = append(colNames, session.Engine.Quote(col.Name)+" = ?") + } else { + colNames = append(colNames, col.Name) + } + } + return colNames, args, nil +} diff --git a/Godeps/_workspace/src/github.com/go-xorm/xorm/mssql_dialect.go b/Godeps/_workspace/src/github.com/go-xorm/xorm/mssql_dialect.go index ceb7c5de917..6fe50fc8c0d 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/xorm/mssql_dialect.go +++ b/Godeps/_workspace/src/github.com/go-xorm/xorm/mssql_dialect.go @@ -270,7 +270,7 @@ func (db *mssql) IsReserved(name string) bool { } func (db *mssql) Quote(name string) string { - return "[" + name + "]" + return "\"" + name + "\"" } func (db *mssql) QuoteStr() string { diff --git a/Godeps/_workspace/src/github.com/go-xorm/xorm/mysql_dialect.go b/Godeps/_workspace/src/github.com/go-xorm/xorm/mysql_dialect.go index 4d32186b6ab..602cd0ecff7 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/xorm/mysql_dialect.go +++ b/Godeps/_workspace/src/github.com/go-xorm/xorm/mysql_dialect.go @@ -218,6 +218,9 @@ func (db *mysql) SqlType(c *core.Column) string { res += ")" case core.NVarchar: res = core.Varchar + case core.Uuid: + res = core.Varchar + c.Length = 40 default: res = t } @@ -317,7 +320,6 @@ func (db *mysql) GetColumns(tableName string) ([]string, map[string]*core.Column if err != nil { return nil, nil, err } - //fmt.Println(columnName, isNullable, colType, colKey, extra, colDefault) col.Name = strings.Trim(columnName, "` ") if "YES" == isNullable { col.Nullable = true @@ -467,15 +469,17 @@ func (db *mysql) GetIndexes(tableName string) (map[string]*core.Index, error) { } colName = strings.Trim(colName, "` ") - + var isRegular bool if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) { indexName = indexName[5+len(tableName) : len(indexName)] + isRegular = true } var index *core.Index var ok bool if index, ok = indexes[indexName]; !ok { index = new(core.Index) + index.IsRegular = isRegular index.Type = indexType index.Name = indexName indexes[indexName] = index diff --git a/Godeps/_workspace/src/github.com/go-xorm/xorm/oracle_dialect.go b/Godeps/_workspace/src/github.com/go-xorm/xorm/oracle_dialect.go index f599dce93ed..be71c288d0c 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/xorm/oracle_dialect.go +++ b/Godeps/_workspace/src/github.com/go-xorm/xorm/oracle_dialect.go @@ -509,7 +509,7 @@ func (db *oracle) SqlType(c *core.Column) string { var res string switch t := c.SQLType.Name; t { case core.Bit, core.TinyInt, core.SmallInt, core.MediumInt, core.Int, core.Integer, core.BigInt, core.Bool, core.Serial, core.BigSerial: - return "NUMBER" + res = "NUMBER" case core.Binary, core.VarBinary, core.Blob, core.TinyBlob, core.MediumBlob, core.LongBlob, core.Bytea: return core.Blob case core.Time, core.DateTime, core.TimeStamp: @@ -521,7 +521,7 @@ func (db *oracle) SqlType(c *core.Column) string { case core.Text, core.MediumText, core.LongText: res = "CLOB" case core.Char, core.Varchar, core.TinyText: - return "VARCHAR2" + res = "VARCHAR2" default: res = t } @@ -536,6 +536,10 @@ func (db *oracle) SqlType(c *core.Column) string { return res } +func (db *oracle) AutoIncrStr() string { + return "AUTO_INCREMENT" +} + func (db *oracle) SupportInsertMany() bool { return true } @@ -553,10 +557,6 @@ func (db *oracle) QuoteStr() string { return "\"" } -func (db *oracle) AutoIncrStr() string { - return "" -} - func (db *oracle) SupportEngine() bool { return false } @@ -565,19 +565,94 @@ func (db *oracle) SupportCharset() bool { return false } +func (db *oracle) SupportDropIfExists() bool { + return false +} + func (db *oracle) IndexOnTable() bool { return false } +func (db *oracle) DropTableSql(tableName string) string { + return fmt.Sprintf("DROP TABLE `%s`", tableName) +} + +func (b *oracle) CreateTableSql(table *core.Table, tableName, storeEngine, charset string) string { + var sql string + sql = "CREATE TABLE " + if tableName == "" { + tableName = table.Name + } + + sql += b.Quote(tableName) + " (" + + pkList := table.PrimaryKeys + + for _, colName := range table.ColumnsSeq() { + col := table.GetColumn(colName) + /*if col.IsPrimaryKey && len(pkList) == 1 { + sql += col.String(b.dialect) + } else {*/ + sql += col.StringNoPk(b) + //} + sql = strings.TrimSpace(sql) + sql += ", " + } + + if len(pkList) > 0 { + sql += "PRIMARY KEY ( " + sql += b.Quote(strings.Join(pkList, b.Quote(","))) + sql += " ), " + } + + sql = sql[:len(sql)-2] + ")" + if b.SupportEngine() && storeEngine != "" { + sql += " ENGINE=" + storeEngine + } + if b.SupportCharset() { + if len(charset) == 0 { + charset = b.URI().Charset + } + if len(charset) > 0 { + sql += " DEFAULT CHARSET " + charset + } + } + return sql +} + func (db *oracle) IndexCheckSql(tableName, idxName string) (string, []interface{}) { - args := []interface{}{strings.ToUpper(tableName), strings.ToUpper(idxName)} + args := []interface{}{tableName, idxName} return `SELECT INDEX_NAME FROM USER_INDEXES ` + - `WHERE TABLE_NAME = ? AND INDEX_NAME = ?`, args + `WHERE TABLE_NAME = :1 AND INDEX_NAME = :2`, args } func (db *oracle) TableCheckSql(tableName string) (string, []interface{}) { - args := []interface{}{strings.ToUpper(tableName)} - return `SELECT table_name FROM user_tables WHERE table_name = ?`, args + args := []interface{}{tableName} + return `SELECT table_name FROM user_tables WHERE table_name = :1`, args +} + +func (db *oracle) MustDropTable(tableName string) error { + sql, args := db.TableCheckSql(tableName) + if db.Logger != nil { + db.Logger.Info("[sql]", sql, args) + } + + rows, err := db.DB().Query(sql, args...) + if err != nil { + return err + } + defer rows.Close() + + if !rows.Next() { + return nil + } + + sql = "Drop Table \"" + tableName + "\"" + if db.Logger != nil { + db.Logger.Info("[sql]", sql) + } + _, err = db.DB().Exec(sql) + return err } /*func (db *oracle) ColumnCheckSql(tableName, colName string) (string, []interface{}) { @@ -587,9 +662,9 @@ func (db *oracle) TableCheckSql(tableName string) (string, []interface{}) { }*/ func (db *oracle) IsColumnExist(tableName string, col *core.Column) (bool, error) { - args := []interface{}{strings.ToUpper(tableName), strings.ToUpper(col.Name)} - query := "SELECT column_name FROM USER_TAB_COLUMNS WHERE table_name = ?" + - " AND column_name = ?" + args := []interface{}{tableName, col.Name} + query := "SELECT column_name FROM USER_TAB_COLUMNS WHERE table_name = :1" + + " AND column_name = :2" rows, err := db.DB().Query(query, args...) if db.Logger != nil { db.Logger.Info("[sql]", query, args) @@ -606,7 +681,7 @@ func (db *oracle) IsColumnExist(tableName string, col *core.Column) (bool, error } func (db *oracle) GetColumns(tableName string) ([]string, map[string]*core.Column, error) { - args := []interface{}{strings.ToUpper(tableName)} + args := []interface{}{tableName} s := "SELECT column_name,data_default,data_type,data_length,data_precision,data_scale," + "nullable FROM USER_TAB_COLUMNS WHERE table_name = :1" @@ -625,7 +700,7 @@ func (db *oracle) GetColumns(tableName string) ([]string, map[string]*core.Colum col := new(core.Column) col.Indexes = make(map[string]bool) - var colName, colDefault, nullable, dataType, dataPrecision, dataScale string + var colName, colDefault, nullable, dataType, dataPrecision, dataScale *string var dataLen int err = rows.Scan(&colName, &colDefault, &dataType, &dataLen, &dataPrecision, @@ -634,36 +709,66 @@ func (db *oracle) GetColumns(tableName string) ([]string, map[string]*core.Colum return nil, nil, err } - col.Name = strings.Trim(colName, `" `) - col.Default = colDefault + col.Name = strings.Trim(*colName, `" `) + if colDefault != nil { + col.Default = *colDefault + col.DefaultIsEmpty = false + } - if nullable == "Y" { + if *nullable == "Y" { col.Nullable = true } else { col.Nullable = false } - switch dataType { + var ignore bool + + var dt string + var len1, len2 int + dts := strings.Split(*dataType, "(") + dt = dts[0] + if len(dts) > 1 { + lens := strings.Split(dts[1][:len(dts[1])-1], ",") + if len(lens) > 1 { + len1, _ = strconv.Atoi(lens[0]) + len2, _ = strconv.Atoi(lens[1]) + } else { + len1, _ = strconv.Atoi(lens[0]) + } + } + + switch dt { case "VARCHAR2": - col.SQLType = core.SQLType{core.Varchar, 0, 0} + col.SQLType = core.SQLType{core.Varchar, len1, len2} case "TIMESTAMP WITH TIME ZONE": col.SQLType = core.SQLType{core.TimeStampz, 0, 0} + case "NUMBER": + col.SQLType = core.SQLType{core.Double, len1, len2} + case "LONG", "LONG RAW": + col.SQLType = core.SQLType{core.Text, 0, 0} + case "RAW": + col.SQLType = core.SQLType{core.Binary, 0, 0} + case "ROWID": + col.SQLType = core.SQLType{core.Varchar, 18, 0} + case "AQ$_SUBSCRIBERS": + ignore = true default: - col.SQLType = core.SQLType{strings.ToUpper(dataType), 0, 0} + col.SQLType = core.SQLType{strings.ToUpper(dt), len1, len2} } + + if ignore { + continue + } + if _, ok := core.SqlTypes[col.SQLType.Name]; !ok { - return nil, nil, errors.New(fmt.Sprintf("unkonw colType %v", dataType)) + return nil, nil, errors.New(fmt.Sprintf("unkonw colType %v %v", *dataType, col.SQLType)) } col.Length = dataLen if col.SQLType.IsText() || col.SQLType.IsTime() { - if col.Default != "" { + if !col.DefaultIsEmpty { col.Default = "'" + col.Default + "'" - } else { - if col.DefaultIsEmpty { - col.Default = "''" - } } } cols[col.Name] = col diff --git a/Godeps/_workspace/src/github.com/go-xorm/xorm/rows.go b/Godeps/_workspace/src/github.com/go-xorm/xorm/rows.go index c566b125bbc..0def55757c8 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/xorm/rows.go +++ b/Godeps/_workspace/src/github.com/go-xorm/xorm/rows.go @@ -25,11 +25,6 @@ func newRows(session *Session, bean interface{}) (*Rows, error) { rows.session = session rows.beanType = reflect.Indirect(reflect.ValueOf(bean)).Type() - err := rows.session.newDb() - if err != nil { - return nil, err - } - defer rows.session.Statement.Init() var sqlStr string @@ -47,8 +42,8 @@ func newRows(session *Session, bean interface{}) (*Rows, error) { } rows.session.Engine.logSQL(sqlStr, args) - - rows.stmt, err = rows.session.Db.Prepare(sqlStr) + var err error + rows.stmt, err = rows.session.DB().Prepare(sqlStr) if err != nil { rows.lastError = err defer rows.Close() diff --git a/Godeps/_workspace/src/github.com/go-xorm/xorm/session.go b/Godeps/_workspace/src/github.com/go-xorm/xorm/session.go index e5ec7fd0701..0d11d99fd0f 100644 --- a/Godeps/_workspace/src/github.com/go-xorm/xorm/session.go +++ b/Godeps/_workspace/src/github.com/go-xorm/xorm/session.go @@ -17,7 +17,7 @@ import ( // Struct Session keep a pointer to sql.DB and provides all execution of all // kind of database operations. type Session struct { - Db *core.DB + db *core.DB Engine *Engine Tx *core.Tx Statement Statement @@ -66,9 +66,9 @@ func (session *Session) Close() { v.Close() } - if session.Db != nil { + if session.db != nil { //session.Engine.Pool.ReleaseDB(session.Engine, session.Db) - session.Db = nil + session.db = nil session.Tx = nil session.stmtCache = nil session.Init() @@ -158,6 +158,12 @@ func (session *Session) Decr(column string, arg ...interface{}) *Session { return session } +// Method SetExpr provides a query string like "column = {expression}" +func (session *Session) SetExpr(column string, expression string) *Session { + session.Statement.SetExpr(column, expression) + return session +} + // Method Cols provides some columns to special func (session *Session) Cols(columns ...string) *Session { session.Statement.Cols(columns...) @@ -280,26 +286,18 @@ func (session *Session) Having(conditions string) *Session { return session } -func (session *Session) newDb() error { - if session.Db == nil { - /*db, err := session.Engine.Pool.RetrieveDB(session.Engine) - if err != nil { - return err - }*/ - session.Db = session.Engine.db +func (session *Session) DB() *core.DB { + if session.db == nil { + session.db = session.Engine.db session.stmtCache = make(map[uint32]*core.Stmt, 0) } - return nil + return session.db } // Begin a transaction func (session *Session) Begin() error { - err := session.newDb() - if err != nil { - return err - } if session.IsAutoCommit { - tx, err := session.Db.Begin() + tx, err := session.DB().Begin() if err != nil { return err } @@ -450,6 +448,13 @@ func (session *Session) exec(sqlStr string, args ...interface{}) (sql.Result, er return session.Engine.LogSQLExecutionTime(sqlStr, args, func() (sql.Result, error) { if session.IsAutoCommit { + //oci8 can not auto commit (github.com/mattn/go-oci8) + if session.Engine.dialect.DBType() == core.ORACLE { + session.Begin() + r, err := session.Tx.Exec(sqlStr, args...) + session.Commit() + return r, err + } return session.innerExec(sqlStr, args...) } return session.Tx.Exec(sqlStr, args...) @@ -458,10 +463,6 @@ func (session *Session) exec(sqlStr string, args ...interface{}) (sql.Result, er // Exec raw sql func (session *Session) Exec(sqlStr string, args ...interface{}) (sql.Result, error) { - err := session.newDb() - if err != nil { - return nil, err - } defer session.resetStatement() if session.IsAutoClose { defer session.Close() @@ -474,10 +475,6 @@ func (session *Session) Exec(sqlStr string, args ...interface{}) (sql.Result, er func (session *Session) CreateTable(bean interface{}) error { session.Statement.RefTable = session.Engine.TableInfo(bean) - err := session.newDb() - if err != nil { - return err - } defer session.resetStatement() if session.IsAutoClose { defer session.Close() @@ -490,10 +487,6 @@ func (session *Session) CreateTable(bean interface{}) error { func (session *Session) CreateIndexes(bean interface{}) error { session.Statement.RefTable = session.Engine.TableInfo(bean) - err := session.newDb() - if err != nil { - return err - } defer session.resetStatement() if session.IsAutoClose { defer session.Close() @@ -501,7 +494,7 @@ func (session *Session) CreateIndexes(bean interface{}) error { sqls := session.Statement.genIndexSQL() for _, sqlStr := range sqls { - _, err = session.exec(sqlStr) + _, err := session.exec(sqlStr) if err != nil { return err } @@ -513,10 +506,6 @@ func (session *Session) CreateIndexes(bean interface{}) error { func (session *Session) CreateUniques(bean interface{}) error { session.Statement.RefTable = session.Engine.TableInfo(bean) - err := session.newDb() - if err != nil { - return err - } defer session.resetStatement() if session.IsAutoClose { defer session.Close() @@ -524,7 +513,7 @@ func (session *Session) CreateUniques(bean interface{}) error { sqls := session.Statement.genUniqueSQL() for _, sqlStr := range sqls { - _, err = session.exec(sqlStr) + _, err := session.exec(sqlStr) if err != nil { return err } @@ -541,10 +530,6 @@ func (session *Session) createOneTable() error { // to be deleted func (session *Session) createAll() error { - err := session.newDb() - if err != nil { - return err - } defer session.resetStatement() if session.IsAutoClose { defer session.Close() @@ -562,10 +547,6 @@ func (session *Session) createAll() error { // drop indexes func (session *Session) DropIndexes(bean interface{}) error { - err := session.newDb() - if err != nil { - return err - } defer session.resetStatement() if session.IsAutoClose { defer session.Close() @@ -573,7 +554,7 @@ func (session *Session) DropIndexes(bean interface{}) error { sqls := session.Statement.genDelIndexSQL() for _, sqlStr := range sqls { - _, err = session.exec(sqlStr) + _, err := session.exec(sqlStr) if err != nil { return err } @@ -581,31 +562,29 @@ func (session *Session) DropIndexes(bean interface{}) error { return nil } -// DropTable drop a table and all indexes of the table -func (session *Session) DropTable(bean interface{}) error { - err := session.newDb() +// drop table will drop table if exist, if drop failed, it will return error +func (session *Session) DropTable(beanOrTableName interface{}) error { + tableName, err := session.Engine.tableName(beanOrTableName) if err != nil { return err } - defer session.resetStatement() - if session.IsAutoClose { - defer session.Close() + var needDrop = true + if !session.Engine.dialect.SupportDropIfExists() { + sqlStr, args := session.Engine.dialect.TableCheckSql(tableName) + results, err := session.query(sqlStr, args...) + if err != nil { + return err + } + needDrop = len(results) > 0 } - t := reflect.Indirect(reflect.ValueOf(bean)).Type() - defer session.resetStatement() - if t.Kind() == reflect.String { - session.Statement.AltTableName = bean.(string) - } else if t.Kind() == reflect.Struct { - session.Statement.RefTable = session.Engine.TableInfo(bean) - } else { - return errors.New("Unsupported type") + if needDrop { + sqlStr := session.Engine.Dialect().DropTableSql(tableName) + _, err = session.exec(sqlStr) + return err } - - sqlStr := session.Statement.genDropSQL() - _, err = session.exec(sqlStr) - return err + return nil } func (statement *Statement) JoinColumns(cols []*core.Column) string { @@ -642,11 +621,6 @@ func (session *Session) cacheGet(bean interface{}, sqlStr string, args ...interf return false, ErrCacheFailed } - // TODO: remove this after support multi pk cache - /*if len(session.Statement.RefTable.PrimaryKeys) != 1 { - return false, ErrCacheFailed - }*/ - for _, filter := range session.Engine.dialect.Filters() { sqlStr = filter.Do(sqlStr, session.Engine.dialect, session.Statement.RefTable) } @@ -662,7 +636,7 @@ func (session *Session) cacheGet(bean interface{}, sqlStr string, args ...interf table := session.Statement.RefTable if err != nil { var res = make([]string, len(table.PrimaryKeys)) - rows, err := session.Db.Query(newsql, args...) + rows, err := session.DB().Query(newsql, args...) if err != nil { return false, err } @@ -747,11 +721,6 @@ func (session *Session) cacheFind(t reflect.Type, sqlStr string, rowsSlicePtr in return ErrCacheFailed } - // TODO: remove this after multi pk supported - /*if len(session.Statement.RefTable.PrimaryKeys) != 1 { - return ErrCacheFailed - }*/ - for _, filter := range session.Engine.dialect.Filters() { sqlStr = filter.Do(sqlStr, session.Engine.dialect, session.Statement.RefTable) } @@ -765,7 +734,7 @@ func (session *Session) cacheFind(t reflect.Type, sqlStr string, rowsSlicePtr in cacher := session.Engine.getCacher2(table) ids, err := core.GetCacheSql(cacher, session.Statement.TableName(), newsql, args) if err != nil { - rows, err := session.Db.Query(newsql, args...) + rows, err := session.DB().Query(newsql, args...) if err != nil { return err } @@ -909,32 +878,27 @@ func (session *Session) cacheFind(t reflect.Type, sqlStr string, rowsSlicePtr in sliceValue.Set(reflect.Append(sliceValue, reflect.Indirect(reflect.ValueOf(bean)))) } } else if sliceValue.Kind() == reflect.Map { - var key core.PK - if table.PrimaryKeys[0] != "" { - key = ids[j] - } - + var key core.PK = ids[j] + keyType := sliceValue.Type().Key() + var ikey interface{} if len(key) == 1 { - ikey, err := strconv.ParseInt(fmt.Sprintf("%v", key[0]), 10, 64) + ikey, err = Atot(fmt.Sprintf("%v", key[0]), keyType) if err != nil { return err } - if t.Kind() == reflect.Ptr { - sliceValue.SetMapIndex(reflect.ValueOf(ikey), reflect.ValueOf(bean)) - } else { - sliceValue.SetMapIndex(reflect.ValueOf(ikey), reflect.Indirect(reflect.ValueOf(bean))) - } } else { - return errors.New("table have multiple primary keys") + if keyType.Kind() != reflect.Slice { + return errors.New("table have multiple primary keys, key is not core.PK or slice") + } + ikey = key + } + + if t.Kind() == reflect.Ptr { + sliceValue.SetMapIndex(reflect.ValueOf(ikey), reflect.ValueOf(bean)) + } else { + sliceValue.SetMapIndex(reflect.ValueOf(ikey), reflect.Indirect(reflect.ValueOf(bean))) } } - /*} else { - session.Engine.LogDebug("[xorm:cacheFind] cache delete:", tableName, ides[j]) - cacher.DelBean(tableName, ids[j]) - - session.Engine.LogDebug("[xorm:cacheFind] cache clear:", tableName) - cacher.ClearIds(tableName) - }*/ } return nil @@ -981,7 +945,7 @@ func (session *Session) doPrepare(sqlStr string) (stmt *core.Stmt, err error) { var has bool stmt, has = session.stmtCache[crc] if !has { - stmt, err = session.Db.Prepare(sqlStr) + stmt, err = session.DB().Prepare(sqlStr) if err != nil { return nil, err } @@ -993,11 +957,6 @@ func (session *Session) doPrepare(sqlStr string) (stmt *core.Stmt, err error) { // get retrieve one record from database, bean's non-empty fields // will be as conditions func (session *Session) Get(bean interface{}) (bool, error) { - err := session.newDb() - if err != nil { - return false, err - } - defer session.resetStatement() if session.IsAutoClose { defer session.Close() @@ -1030,6 +989,7 @@ func (session *Session) Get(bean interface{}) (bool, error) { } var rawRows *core.Rows + var err error session.queryPreprocess(&sqlStr, args...) if session.IsAutoCommit { stmt, err := session.doPrepare(sqlStr) @@ -1059,11 +1019,6 @@ func (session *Session) Get(bean interface{}) (bool, error) { // Count counts the records. bean's non-empty fields // are conditions. func (session *Session) Count(bean interface{}) (int64, error) { - err := session.newDb() - if err != nil { - return 0, err - } - defer session.resetStatement() if session.IsAutoClose { defer session.Close() @@ -1095,14 +1050,79 @@ func (session *Session) Count(bean interface{}) (int64, error) { return int64(total), err } +func Atot(s string, tp reflect.Type) (interface{}, error) { + var err error + var result interface{} + switch tp.Kind() { + case reflect.Int: + result, err = strconv.Atoi(s) + if err != nil { + return nil, errors.New("convert " + s + " as int: " + err.Error()) + } + case reflect.Int8: + x, err := strconv.Atoi(s) + if err != nil { + return nil, errors.New("convert " + s + " as int16: " + err.Error()) + } + result = int8(x) + case reflect.Int16: + x, err := strconv.Atoi(s) + if err != nil { + return nil, errors.New("convert " + s + " as int16: " + err.Error()) + } + result = int16(x) + case reflect.Int32: + x, err := strconv.Atoi(s) + if err != nil { + return nil, errors.New("convert " + s + " as int32: " + err.Error()) + } + result = int32(x) + case reflect.Int64: + result, err = strconv.ParseInt(s, 10, 64) + if err != nil { + return nil, errors.New("convert " + s + " as int64: " + err.Error()) + } + case reflect.Uint: + x, err := strconv.ParseUint(s, 10, 64) + if err != nil { + return nil, errors.New("convert " + s + " as uint: " + err.Error()) + } + result = uint(x) + case reflect.Uint8: + x, err := strconv.ParseUint(s, 10, 64) + if err != nil { + return nil, errors.New("convert " + s + " as uint8: " + err.Error()) + } + result = uint8(x) + case reflect.Uint16: + x, err := strconv.ParseUint(s, 10, 64) + if err != nil { + return nil, errors.New("convert " + s + " as uint16: " + err.Error()) + } + result = uint16(x) + case reflect.Uint32: + x, err := strconv.ParseUint(s, 10, 64) + if err != nil { + return nil, errors.New("convert " + s + " as uint32: " + err.Error()) + } + result = uint32(x) + case reflect.Uint64: + result, err = strconv.ParseUint(s, 10, 64) + if err != nil { + return nil, errors.New("convert " + s + " as uint64: " + err.Error()) + } + case reflect.String: + result = s + default: + panic("unsupported convert type") + } + return result, nil +} + // Find retrieve records from table, condiBeans's non-empty fields // are conditions. beans could be []Struct, []*Struct, map[int64]Struct // map[int64]*Struct func (session *Session) Find(rowsSlicePtr interface{}, condiBean ...interface{}) error { - err := session.newDb() - if err != nil { - return err - } defer session.resetStatement() if session.IsAutoClose { defer session.Close() @@ -1143,10 +1163,9 @@ func (session *Session) Find(rowsSlicePtr interface{}, condiBean ...interface{}) } else { // !oinume! Add "
+
+### Dashboard header
+
+
+1. Side menu toggle
+2. Dashboard title & Search dropdown (also includes access to New dashboard, Import & Playlist)
+3. Star/unstar current dashboard
+4. Share current dashboard (Make sure the dashboard is saved before)
+5. Save current dashboard
+6. Settings dropdown (dashboard settings, annotations, templating, etc)
+
+
## New dashboard

diff --git a/docs/sources/guides/changes_in_v2.md b/docs/sources/guides/whats-new-in-v2.md
similarity index 65%
rename from docs/sources/guides/changes_in_v2.md
rename to docs/sources/guides/whats-new-in-v2.md
index c9d08f046bd..bb5c4c15c7d 100644
--- a/docs/sources/guides/changes_in_v2.md
+++ b/docs/sources/guides/whats-new-in-v2.md
@@ -1,37 +1,41 @@
---
-page_title: Changes and new features in Grafana v2.0
-page_description: Changes and new features in Grafana v2.0
-page_keywords: grafana, changes, features, documentation
+page_title: What's New in Grafana v2.0
+page_description: What's new in Grafana v2.0
+page_keywords: grafana, new, changes, features, documentation
---
-# Changes and new features in v2.0
-
-This is a guide that descriptes some of changes and new features that can be found in Grafana v2.0.
+# What's New in Grafana v2.0
+This is a guide that describes some of changes and new features that can be found in Grafana v2.0.
## New dashboard top header
1. Side menu toggle
-2. Dashboard search (also includes access to New dashboard, Import & Playlist)
-3. Dashboard title
-4. Star/unstar current dashboard
-5. Share current dashboard (Make sure the dashboard is saved before)
-6. Save current dashboard
-7. Settings dropdown
- - Dashboard settings
- - Annotations
- - Templating
- - Export (exports current dashboard to json file)
- - View JSON (view current dashboard json model)
- - Save As... (Copy & Save current dashboard under a new name)
- - Delete dashboard
+2. Dashboard title & Search dropdown (also includes access to New dashboard, Import & Playlist)
+3. Star/unstar current dashboard
+4. Share current dashboard (Make sure the dashboard is saved before)
+5. Save current dashboard
+6. Settings dropdown (dashboard settings, annotations, templating, etc)
> **Note** In Grafana v2.0 when you change the title of a dashboard and then save it it will no
> longer create a new dashboard. It will just change the name for the current dashboard.
> To change name and create a new dashboard use the `Save As...` menu option
+## Dashboard Snapshot sharing
+A dashboard snapshot is an instant way to share an interactive dashboard publicly. When created, we strip sensitive data like queries
+(metric, template and annotation) and panel links, leaving only the visible metric data and series names embedded into your dashboard. Dashboard
+snapshots can be accessed by anyone who has the link and can reach the URL.
+
+
+
+### Publish snapshots
+You can publish snapshots to you local instance or to [snapshot.raintank.io](http://snapshot.raintank.io). The later is a free service
+that is provided by [Raintank](http://raintank.io) that allows you to publish dashboard snapshots to an external grafana instance.
+The same rules still apply, anyone with the link can view it. You can set an expiration time if you want the snapshot to be removed
+after a certain time period.
+
## Panel time overrides & timeshift
In Grafana v2.x you can now override the relative time range for individual panels. You can also add a
@@ -59,6 +63,14 @@ upper right of a panel when overriden time range options.
The dashboard search view has received a big UI update and polish. You can now see and filter by which dashboard
you have personally starred.
+## Logarithmic scale
+
+The Graph panel now supports 3 logarithmic scales, `log base 10`, `log base 32`, `log base 1024`. Logarithmic y-axis
+scales are very useful when rendering many series of different order of magnitude on the same scale. For example
+latency, network traffic or storage.
+
+
+
## Dashlist panel

@@ -118,3 +130,10 @@ Organizations via a role. That role can be:
> per series permissions in Graphite, InfluxDB or OpenTSDB.
There are currently no permissions on individual dashboards.
+
+## Panel IFrame embedding
+
+You can embed a single panel on another web page using the panel share dialog. Below you should see an iframe
+with a graph panel (taken from dashoard snapshot at [snapshot.raintank.io](snapshot.raintank.io).
+
+
diff --git a/docs/sources/installation/configuration.md b/docs/sources/installation/configuration.md
index 048301a7714..a442ee58dc3 100644
--- a/docs/sources/installation/configuration.md
+++ b/docs/sources/installation/configuration.md
@@ -184,7 +184,7 @@ Valid values are "memory", "file", "mysql", 'postgres'. Default is "memory".
This option should be configured differently depending on what type of session provider you have configured.
- **file:** session file path, e.g. `data/sessions`
-- **mysql:** go-sql-driver/mysql dsn config string, e.g. `root:password@/session_table`
+- **mysql:** go-sql-driver/mysql dsn config string, e.g. `user:password@tcp(127.0.0.1)/database_name`
if you use mysql or postgres as session store you need to create the session table manually.
Mysql Example:
diff --git a/docs/sources/installation/performance.md b/docs/sources/installation/performance.md
index 535cf72a228..ce41e7a0548 100644
--- a/docs/sources/installation/performance.md
+++ b/docs/sources/installation/performance.md
@@ -11,6 +11,6 @@ page_keywords: grafana, performance, documentation
Graphite 0.9.13 adds a much needed feature to the json rendering API that is very important for Grafana. If you are experiance slow
load & rendering times for large time ranges then it is most likely caused by running Graphite 0.9.12 or lower. The latest version
of Graphite adds a maxDataPoints parameter to the json render API, without this feature Graphite can return hundreds of thousands of data points per graph, which
-can hang your browser. Be sue to upgrade to [0.9.13](http://graphite.readthedocs.org/en/latest/releases/0_9_13.html).
+can hang your browser. Be sure to upgrade to [0.9.13](http://graphite.readthedocs.org/en/latest/releases/0_9_13.html).
diff --git a/docs/sources/reference/sharing.md b/docs/sources/reference/sharing.md
new file mode 100644
index 00000000000..1d613aaddf5
--- /dev/null
+++ b/docs/sources/reference/sharing.md
@@ -0,0 +1,44 @@
+----
+page_title: Sharing
+page_description: Sharing
+page_keywords: grafana, sharing, guide, documentation
+---
+
+# Sharing features
+Grafana provides a number of ways to share a dashboard or a specfic panel to other users within your
+organization. It also provides ways to publish interactive snapshots that can be accessed by external partners.
+
+## Share dashboard
+Share a dashboard via the share icon in the top nav. This opens the share dialog where you
+can get a link to the current dashboard with the current selected time range and template variables. If you have
+made changes to the dashboard, make sure those are saved before sending the link.
+
+### Dashboard snapshot
+
+A dashboard snapshot is an instant way to share an interactive dashboard publicly. When created, we strip sensitive data like queries
+(metric, template and annotation) and panel links, leaving only the visible metric data and series names embedded into your dashboard. Dashboard
+snapshots can be accessed by anyone who has the link and can reach the URL.
+
+
+
+### Publish snapshots
+You can publish snapshots to you local instance or to [snapshot.raintank.io](http://snapshot.raintank.io). The later is a free service
+that is provided by [Raintank](http://raintank.io) that allows you to publish dashboard snapshots to an external grafana instance.
+The same rules still apply, anyone with the link can view it. You can set an expiration time if you want the snapshot to be removed
+after a certain time period.
+
+## Share Panel
+Click a panel title to open the panel menu, then click share in the panel menu to open the Share Panel dialog. Here you
+have access to a link that will take you to exactly this panel with the current time range and selected template variables.
+You also get a link to service side rendered PNG of the panel. Useful if you want to shara image of the panel.
+
+### Embed Panel
+You can embed a panel using an iframe on another web site. This tab will show you the html that you need to use.
+
+Example:
+
+```html
+
+```
+Below there should be an interactive Grafana graph embedded in an iframe:
+
diff --git a/latest.json b/latest.json
index 90189fabeca..1ca0904fd94 100644
--- a/latest.json
+++ b/latest.json
@@ -1,4 +1,4 @@
{
"version": "1.9.1",
- "url": "http://grafanarel.s3.amazonaws.com/grafana-1.9.1.tar.gz"
+ "url": "https://grafanarel.s3.amazonaws.com/grafana-1.9.1.tar.gz"
}
diff --git a/main.go b/main.go
index f23a544e1e9..3b25b73039d 100644
--- a/main.go
+++ b/main.go
@@ -39,17 +39,7 @@ func main() {
app.Name = "Grafana Backend"
app.Usage = "grafana web"
app.Version = version
- app.Commands = []cli.Command{
- cmd.ListOrgs,
- cmd.CreateOrg,
- cmd.DeleteOrg,
- cmd.ExportDashboard,
- cmd.ImportDashboard,
- cmd.ListDataSources,
- cmd.CreateDataSource,
- cmd.DescribeDataSource,
- cmd.DeleteDataSource,
- cmd.Web}
+ app.Commands = []cli.Command{cmd.ImportDashboard, cmd.Web}
app.Flags = append(app.Flags, []cli.Flag{
cli.StringFlag{
Name: "config",
diff --git a/package.json b/package.json
index dfaa81c7eb9..926fbf6d5ae 100644
--- a/package.json
+++ b/package.json
@@ -62,7 +62,7 @@
},
"license": "Apache License",
"dependencies": {
- "grunt-jscs": "^0.8.1",
+ "grunt-jscs": "~1.5.x",
"karma-sinon": "^1.0.3",
"lodash": "^2.4.1",
"sinon": "^1.10.3"
diff --git a/pkg/api/admin_users.go b/pkg/api/admin_users.go
index d3fa111d333..f7e8fca2b5e 100644
--- a/pkg/api/admin_users.go
+++ b/pkg/api/admin_users.go
@@ -3,6 +3,7 @@ package api
import (
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
+ "github.com/grafana/grafana/pkg/metrics"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/util"
@@ -64,6 +65,8 @@ func AdminCreateUser(c *middleware.Context, form dtos.AdminCreateUserForm) {
return
}
+ metrics.M_Api_Admin_User_Create.Inc(1)
+
c.JsonOK("User created")
}
diff --git a/pkg/api/api.go b/pkg/api/api.go
index 8f069c69940..88f1a7a37ee 100644
--- a/pkg/api/api.go
+++ b/pkg/api/api.go
@@ -41,6 +41,13 @@ func Register(r *macaron.Macaron) {
r.Get("/signup", Index)
r.Post("/api/user/signup", bind(m.CreateUserCommand{}), SignUp)
+ // dashboard snapshots
+ r.Post("/api/snapshots/", bind(m.CreateDashboardSnapshotCommand{}), CreateDashboardSnapshot)
+ r.Get("/dashboard/snapshots/*", Index)
+
+ r.Get("/api/snapshots/:key", GetDashboardSnapshot)
+ r.Get("/api/snapshots-delete/:key", DeleteDashboardSnapshot)
+
// authed api
r.Group("/api", func() {
// user
diff --git a/pkg/api/dashboard.go b/pkg/api/dashboard.go
index 8cde5a8bc8a..278264f22d7 100644
--- a/pkg/api/dashboard.go
+++ b/pkg/api/dashboard.go
@@ -7,6 +7,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
+ "github.com/grafana/grafana/pkg/metrics"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
@@ -27,6 +28,8 @@ func isDasboardStarredByUser(c *middleware.Context, dashId int64) (bool, error)
}
func GetDashboard(c *middleware.Context) {
+ metrics.M_Api_Dashboard_Get.Inc(1)
+
slug := c.Params(":slug")
query := m.GetDashboardQuery{Slug: slug, OrgId: c.OrgId}
@@ -88,6 +91,8 @@ func PostDashboard(c *middleware.Context, cmd m.SaveDashboardCommand) {
return
}
+ metrics.M_Api_Dashboard_Post.Inc(1)
+
c.JSON(200, util.DynMap{"status": "success", "slug": cmd.Result.Slug, "version": cmd.Result.Version})
}
diff --git a/pkg/api/dashboard_snapshot.go b/pkg/api/dashboard_snapshot.go
new file mode 100644
index 00000000000..8de96ec9f21
--- /dev/null
+++ b/pkg/api/dashboard_snapshot.go
@@ -0,0 +1,87 @@
+package api
+
+import (
+ "time"
+
+ "github.com/grafana/grafana/pkg/api/dtos"
+ "github.com/grafana/grafana/pkg/bus"
+ "github.com/grafana/grafana/pkg/metrics"
+ "github.com/grafana/grafana/pkg/middleware"
+ m "github.com/grafana/grafana/pkg/models"
+ "github.com/grafana/grafana/pkg/setting"
+ "github.com/grafana/grafana/pkg/util"
+)
+
+func CreateDashboardSnapshot(c *middleware.Context, cmd m.CreateDashboardSnapshotCommand) {
+ if cmd.External {
+ // external snapshot ref requires key and delete key
+ if cmd.Key == "" || cmd.DeleteKey == "" {
+ c.JsonApiErr(400, "Missing key and delete key for external snapshot", nil)
+ return
+ }
+
+ cmd.OrgId = -1
+ cmd.UserId = -1
+ metrics.M_Api_Dashboard_Snapshot_External.Inc(1)
+ } else {
+ cmd.Key = util.GetRandomString(32)
+ cmd.DeleteKey = util.GetRandomString(32)
+ cmd.OrgId = c.OrgId
+ cmd.UserId = c.UserId
+ metrics.M_Api_Dashboard_Snapshot_Create.Inc(1)
+ }
+
+ if err := bus.Dispatch(&cmd); err != nil {
+ c.JsonApiErr(500, "Failed to create snaphost", err)
+ return
+ }
+
+ c.JSON(200, util.DynMap{
+ "key": cmd.Key,
+ "deleteKey": cmd.DeleteKey,
+ "url": setting.ToAbsUrl("dashboard/snapshot/" + cmd.Key),
+ "deleteUrl": setting.ToAbsUrl("api/snapshots-delete/" + cmd.DeleteKey),
+ })
+}
+
+func GetDashboardSnapshot(c *middleware.Context) {
+ key := c.Params(":key")
+
+ query := &m.GetDashboardSnapshotQuery{Key: key}
+
+ err := bus.Dispatch(query)
+ if err != nil {
+ c.JsonApiErr(500, "Failed to get dashboard snapshot", err)
+ return
+ }
+
+ snapshot := query.Result
+
+ // expired snapshots should also be removed from db
+ if snapshot.Expires.Before(time.Now()) {
+ c.JsonApiErr(404, "Snapshot not found", err)
+ return
+ }
+
+ dto := dtos.Dashboard{
+ Model: snapshot.Dashboard,
+ Meta: dtos.DashboardMeta{IsSnapshot: true},
+ }
+
+ metrics.M_Api_Dashboard_Snapshot_Get.Inc(1)
+
+ c.Resp.Header().Set("Cache-Control", "public, max-age=3600")
+ c.JSON(200, dto)
+}
+
+func DeleteDashboardSnapshot(c *middleware.Context) {
+ key := c.Params(":key")
+ cmd := &m.DeleteDashboardSnapshotCommand{DeleteKey: key}
+
+ if err := bus.Dispatch(cmd); err != nil {
+ c.JsonApiErr(500, "Failed to delete dashboard snapshot", err)
+ return
+ }
+
+ c.JSON(200, util.DynMap{"message": "Snapshot deleted. It might take an hour before it's cleared from a CDN cache."})
+}
diff --git a/pkg/api/dtos/models.go b/pkg/api/dtos/models.go
index c225c6a5bbb..2cb9da0189f 100644
--- a/pkg/api/dtos/models.go
+++ b/pkg/api/dtos/models.go
@@ -27,9 +27,10 @@ type CurrentUser struct {
}
type DashboardMeta struct {
- IsStarred bool `json:"isStarred"`
- IsHome bool `json:"isHome"`
- Slug string `json:"slug"`
+ IsStarred bool `json:"isStarred"`
+ IsHome bool `json:"isHome"`
+ IsSnapshot bool `json:"isSnapshot"`
+ Slug string `json:"slug"`
}
type Dashboard struct {
diff --git a/pkg/api/index.go b/pkg/api/index.go
index 3006c54e8ab..4af66f18133 100644
--- a/pkg/api/index.go
+++ b/pkg/api/index.go
@@ -47,7 +47,7 @@ func Index(c *middleware.Context) {
func NotFound(c *middleware.Context) {
if c.IsApiRequest() {
- c.JsonApiErr(200, "Not found", nil)
+ c.JsonApiErr(404, "Not found", nil)
return
}
diff --git a/pkg/api/login.go b/pkg/api/login.go
index e7707c53138..56a61697cb9 100644
--- a/pkg/api/login.go
+++ b/pkg/api/login.go
@@ -6,6 +6,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/log"
+ "github.com/grafana/grafana/pkg/metrics"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
@@ -75,7 +76,6 @@ func LoginView(c *middleware.Context) {
}
func LoginPost(c *middleware.Context, cmd dtos.LoginCommand) {
-
userQuery := m.GetUserByLoginQuery{LoginOrEmail: cmd.User}
err := bus.Dispatch(&userQuery)
@@ -112,6 +112,8 @@ func LoginPost(c *middleware.Context, cmd dtos.LoginCommand) {
c.SetCookie("redirect_to", "", -1, setting.AppSubUrl+"/")
}
+ metrics.M_Api_Login_Post.Inc(1)
+
c.JSON(200, result)
}
diff --git a/pkg/api/login_oauth.go b/pkg/api/login_oauth.go
index 9ccb8f0b60d..a234ef02bf3 100644
--- a/pkg/api/login_oauth.go
+++ b/pkg/api/login_oauth.go
@@ -8,6 +8,7 @@ import (
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/log"
+ "github.com/grafana/grafana/pkg/metrics"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
@@ -81,5 +82,7 @@ func OAuthLogin(ctx *middleware.Context) {
// login
loginUserWithUser(userQuery.Result, ctx)
+ metrics.M_Api_Login_OAuth.Inc(1)
+
ctx.Redirect(setting.AppSubUrl + "/")
}
diff --git a/pkg/api/org.go b/pkg/api/org.go
index 8b41b0e3f5f..ed180b1af77 100644
--- a/pkg/api/org.go
+++ b/pkg/api/org.go
@@ -2,6 +2,7 @@ package api
import (
"github.com/grafana/grafana/pkg/bus"
+ "github.com/grafana/grafana/pkg/metrics"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
)
@@ -35,6 +36,8 @@ func CreateOrg(c *middleware.Context, cmd m.CreateOrgCommand) {
return
}
+ metrics.M_Api_Org_Create.Inc(1)
+
c.JsonOK("Organization created")
}
diff --git a/pkg/api/signup.go b/pkg/api/signup.go
index 74f00509b98..63bb34c72ac 100644
--- a/pkg/api/signup.go
+++ b/pkg/api/signup.go
@@ -2,6 +2,7 @@ package api
import (
"github.com/grafana/grafana/pkg/bus"
+ "github.com/grafana/grafana/pkg/metrics"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
@@ -26,4 +27,6 @@ func SignUp(c *middleware.Context, cmd m.CreateUserCommand) {
loginUserWithUser(&user, c)
c.JsonOK("User created and logged in")
+
+ metrics.M_Api_User_SignUp.Inc(1)
}
diff --git a/pkg/api/static/static.go b/pkg/api/static/static.go
new file mode 100644
index 00000000000..43ba6a32b20
--- /dev/null
+++ b/pkg/api/static/static.go
@@ -0,0 +1,218 @@
+// Copyright 2013 Martini Authors
+// Copyright 2014 Unknwon
+//
+// Licensed under the Apache License, Version 2.0 (the "License"): you may
+// not use this file except in compliance with the License. You may obtain
+// a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+
+package httpstatic
+
+import (
+ "log"
+ "net/http"
+ "os"
+ "path"
+ "path/filepath"
+ "strings"
+ "sync"
+
+ "github.com/Unknwon/macaron"
+)
+
+var Root string
+
+func init() {
+ var err error
+ Root, err = os.Getwd()
+ if err != nil {
+ panic("error getting work directory: " + err.Error())
+ }
+}
+
+// StaticOptions is a struct for specifying configuration options for the macaron.Static middleware.
+type StaticOptions struct {
+ // Prefix is the optional prefix used to serve the static directory content
+ Prefix string
+ // SkipLogging will disable [Static] log messages when a static file is served.
+ SkipLogging bool
+ // IndexFile defines which file to serve as index if it exists.
+ IndexFile string
+ // Expires defines which user-defined function to use for producing a HTTP Expires Header
+ // https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
+ AddHeaders func(ctx *macaron.Context)
+ // FileSystem is the interface for supporting any implmentation of file system.
+ FileSystem http.FileSystem
+}
+
+// FIXME: to be deleted.
+type staticMap struct {
+ lock sync.RWMutex
+ data map[string]*http.Dir
+}
+
+func (sm *staticMap) Set(dir *http.Dir) {
+ sm.lock.Lock()
+ defer sm.lock.Unlock()
+
+ sm.data[string(*dir)] = dir
+}
+
+func (sm *staticMap) Get(name string) *http.Dir {
+ sm.lock.RLock()
+ defer sm.lock.RUnlock()
+
+ return sm.data[name]
+}
+
+func (sm *staticMap) Delete(name string) {
+ sm.lock.Lock()
+ defer sm.lock.Unlock()
+
+ delete(sm.data, name)
+}
+
+var statics = staticMap{sync.RWMutex{}, map[string]*http.Dir{}}
+
+// staticFileSystem implements http.FileSystem interface.
+type staticFileSystem struct {
+ dir *http.Dir
+}
+
+func newStaticFileSystem(directory string) staticFileSystem {
+ if !filepath.IsAbs(directory) {
+ directory = filepath.Join(Root, directory)
+ }
+ dir := http.Dir(directory)
+ statics.Set(&dir)
+ return staticFileSystem{&dir}
+}
+
+func (fs staticFileSystem) Open(name string) (http.File, error) {
+ return fs.dir.Open(name)
+}
+
+func prepareStaticOption(dir string, opt StaticOptions) StaticOptions {
+ // Defaults
+ if len(opt.IndexFile) == 0 {
+ opt.IndexFile = "index.html"
+ }
+ // Normalize the prefix if provided
+ if opt.Prefix != "" {
+ // Ensure we have a leading '/'
+ if opt.Prefix[0] != '/' {
+ opt.Prefix = "/" + opt.Prefix
+ }
+ // Remove any trailing '/'
+ opt.Prefix = strings.TrimRight(opt.Prefix, "/")
+ }
+ if opt.FileSystem == nil {
+ opt.FileSystem = newStaticFileSystem(dir)
+ }
+ return opt
+}
+
+func prepareStaticOptions(dir string, options []StaticOptions) StaticOptions {
+ var opt StaticOptions
+ if len(options) > 0 {
+ opt = options[0]
+ }
+ return prepareStaticOption(dir, opt)
+}
+
+func staticHandler(ctx *macaron.Context, log *log.Logger, opt StaticOptions) bool {
+ if ctx.Req.Method != "GET" && ctx.Req.Method != "HEAD" {
+ return false
+ }
+
+ file := ctx.Req.URL.Path
+ // if we have a prefix, filter requests by stripping the prefix
+ if opt.Prefix != "" {
+ if !strings.HasPrefix(file, opt.Prefix) {
+ return false
+ }
+ file = file[len(opt.Prefix):]
+ if file != "" && file[0] != '/' {
+ return false
+ }
+ }
+
+ f, err := opt.FileSystem.Open(file)
+ if err != nil {
+ return false
+ }
+ defer f.Close()
+
+ fi, err := f.Stat()
+ if err != nil {
+ return true // File exists but fail to open.
+ }
+
+ // Try to serve index file
+ if fi.IsDir() {
+ // Redirect if missing trailing slash.
+ if !strings.HasSuffix(ctx.Req.URL.Path, "/") {
+ http.Redirect(ctx.Resp, ctx.Req.Request, ctx.Req.URL.Path+"/", http.StatusFound)
+ return true
+ }
+
+ file = path.Join(file, opt.IndexFile)
+ f, err = opt.FileSystem.Open(file)
+ if err != nil {
+ return false // Discard error.
+ }
+ defer f.Close()
+
+ fi, err = f.Stat()
+ if err != nil || fi.IsDir() {
+ return true
+ }
+ }
+
+ if !opt.SkipLogging {
+ log.Println("[Static] Serving " + file)
+ }
+
+ // Add an Expires header to the static content
+ if opt.AddHeaders != nil {
+ opt.AddHeaders(ctx)
+ }
+
+ http.ServeContent(ctx.Resp, ctx.Req.Request, file, fi.ModTime(), f)
+ return true
+}
+
+// Static returns a middleware handler that serves static files in the given directory.
+func Static(directory string, staticOpt ...StaticOptions) macaron.Handler {
+ opt := prepareStaticOptions(directory, staticOpt)
+
+ return func(ctx *macaron.Context, log *log.Logger) {
+ staticHandler(ctx, log, opt)
+ }
+}
+
+// Statics registers multiple static middleware handlers all at once.
+func Statics(opt StaticOptions, dirs ...string) macaron.Handler {
+ if len(dirs) == 0 {
+ panic("no static directory is given")
+ }
+ opts := make([]StaticOptions, len(dirs))
+ for i := range dirs {
+ opts[i] = prepareStaticOption(dirs[i], opt)
+ }
+
+ return func(ctx *macaron.Context, log *log.Logger) {
+ for i := range opts {
+ if staticHandler(ctx, log, opts[i]) {
+ return
+ }
+ }
+ }
+}
diff --git a/pkg/cmd/web.go b/pkg/cmd/web.go
index 6619e5b1e0e..1fc6e8a999c 100644
--- a/pkg/cmd/web.go
+++ b/pkg/cmd/web.go
@@ -11,7 +11,6 @@ import (
"path"
"path/filepath"
"strconv"
- "time"
"github.com/Unknwon/macaron"
"github.com/codegangsta/cli"
@@ -20,7 +19,9 @@ import (
_ "github.com/macaron-contrib/session/postgres"
"github.com/grafana/grafana/pkg/api"
+ "github.com/grafana/grafana/pkg/api/static"
"github.com/grafana/grafana/pkg/log"
+ "github.com/grafana/grafana/pkg/metrics"
"github.com/grafana/grafana/pkg/middleware"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/services/eventpublisher"
@@ -64,14 +65,22 @@ func newMacaron() *macaron.Macaron {
}
func mapStatic(m *macaron.Macaron, dir string, prefix string) {
- m.Use(macaron.Static(
+ headers := func(c *macaron.Context) {
+ c.Resp.Header().Set("Cache-Control", "public, max-age=3600")
+ }
+
+ if setting.Env == setting.DEV {
+ headers = func(c *macaron.Context) {
+ c.Resp.Header().Set("Cache-Control", "max-age=0, must-revalidate, no-cache")
+ }
+ }
+
+ m.Use(httpstatic.Static(
path.Join(setting.StaticRootPath, dir),
- macaron.StaticOptions{
+ httpstatic.StaticOptions{
SkipLogging: true,
Prefix: prefix,
- Expires: func() string {
- return time.Now().UTC().Format(http.TimeFormat)
- },
+ AddHeaders: headers,
},
))
}
@@ -88,6 +97,10 @@ func runWeb(c *cli.Context) {
m := newMacaron()
api.Register(m)
+ if setting.ReportingEnabled {
+ go metrics.StartUsageReportLoop()
+ }
+
listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
switch setting.Protocol {
diff --git a/pkg/metrics/counter.go b/pkg/metrics/counter.go
new file mode 100644
index 00000000000..1a4a88be37b
--- /dev/null
+++ b/pkg/metrics/counter.go
@@ -0,0 +1,72 @@
+package metrics
+
+import "sync/atomic"
+
+// Counters hold an int64 value that can be incremented and decremented.
+type Counter interface {
+ Clear()
+ Count() int64
+ Dec(int64)
+ Inc(int64)
+ Snapshot() Counter
+}
+
+// NewCounter constructs a new StandardCounter.
+func NewCounter() Counter {
+ return &StandardCounter{0}
+}
+
+// CounterSnapshot is a read-only copy of another Counter.
+type CounterSnapshot int64
+
+// Clear panics.
+func (CounterSnapshot) Clear() {
+ panic("Clear called on a CounterSnapshot")
+}
+
+// Count returns the count at the time the snapshot was taken.
+func (c CounterSnapshot) Count() int64 { return int64(c) }
+
+// Dec panics.
+func (CounterSnapshot) Dec(int64) {
+ panic("Dec called on a CounterSnapshot")
+}
+
+// Inc panics.
+func (CounterSnapshot) Inc(int64) {
+ panic("Inc called on a CounterSnapshot")
+}
+
+// Snapshot returns the snapshot.
+func (c CounterSnapshot) Snapshot() Counter { return c }
+
+// StandardCounter is the standard implementation of a Counter and uses the
+// sync/atomic package to manage a single int64 value.
+type StandardCounter struct {
+ count int64
+}
+
+// Clear sets the counter to zero.
+func (c *StandardCounter) Clear() {
+ atomic.StoreInt64(&c.count, 0)
+}
+
+// Count returns the current count.
+func (c *StandardCounter) Count() int64 {
+ return atomic.LoadInt64(&c.count)
+}
+
+// Dec decrements the counter by the given amount.
+func (c *StandardCounter) Dec(i int64) {
+ atomic.AddInt64(&c.count, -i)
+}
+
+// Inc increments the counter by the given amount.
+func (c *StandardCounter) Inc(i int64) {
+ atomic.AddInt64(&c.count, i)
+}
+
+// Snapshot returns a read-only copy of the counter.
+func (c *StandardCounter) Snapshot() Counter {
+ return CounterSnapshot(c.Count())
+}
diff --git a/pkg/metrics/metric_ref.go b/pkg/metrics/metric_ref.go
new file mode 100644
index 00000000000..f9e5d693d4c
--- /dev/null
+++ b/pkg/metrics/metric_ref.go
@@ -0,0 +1,39 @@
+package metrics
+
+type comboCounterRef struct {
+ usageCounter Counter
+ metricCounter Counter
+}
+
+func NewComboCounterRef(name string) Counter {
+ cr := &comboCounterRef{}
+ cr.usageCounter = UsageStats.GetOrRegister(name, NewCounter).(Counter)
+ cr.metricCounter = MetricStats.GetOrRegister(name, NewCounter).(Counter)
+ return cr
+}
+
+func (c comboCounterRef) Clear() {
+ c.usageCounter.Clear()
+ c.metricCounter.Clear()
+}
+
+func (c comboCounterRef) Count() int64 {
+ panic("Count called on a combocounter ref")
+}
+
+// Dec panics.
+func (c comboCounterRef) Dec(i int64) {
+ c.usageCounter.Dec(i)
+ c.metricCounter.Dec(i)
+}
+
+// Inc panics.
+func (c comboCounterRef) Inc(i int64) {
+ c.usageCounter.Inc(i)
+ c.metricCounter.Inc(i)
+}
+
+// Snapshot returns the snapshot.
+func (c comboCounterRef) Snapshot() Counter {
+ panic("snapshot called on a combocounter ref")
+}
diff --git a/pkg/metrics/metrics.go b/pkg/metrics/metrics.go
new file mode 100644
index 00000000000..f6dab8c8043
--- /dev/null
+++ b/pkg/metrics/metrics.go
@@ -0,0 +1,29 @@
+package metrics
+
+var UsageStats = NewRegistry()
+var MetricStats = NewRegistry()
+
+var (
+ M_Instance_Start = NewComboCounterRef("instance.start")
+
+ M_Page_Status_200 = NewComboCounterRef("page.status.200")
+ M_Page_Status_500 = NewComboCounterRef("page.status.500")
+ M_Page_Status_404 = NewComboCounterRef("page.status.404")
+
+ M_Api_Status_500 = NewComboCounterRef("api.status.500")
+ M_Api_Status_404 = NewComboCounterRef("api.status.404")
+
+ M_Api_User_SignUp = NewComboCounterRef("api.user.signup")
+ M_Api_Dashboard_Get = NewComboCounterRef("api.dashboard.get")
+ M_Api_Dashboard_Post = NewComboCounterRef("api.dashboard.post")
+ M_Api_Admin_User_Create = NewComboCounterRef("api.admin.user_create")
+ M_Api_Login_Post = NewComboCounterRef("api.login.post")
+ M_Api_Login_OAuth = NewComboCounterRef("api.login.oauth")
+ M_Api_Org_Create = NewComboCounterRef("api.org.create")
+
+ M_Api_Dashboard_Snapshot_Create = NewComboCounterRef("api.dashboard_snapshot.create")
+ M_Api_Dashboard_Snapshot_External = NewComboCounterRef("api.dashboard_snapshot.external")
+ M_Api_Dashboard_Snapshot_Get = NewComboCounterRef("api.dashboard_snapshot.get")
+
+ M_Models_Dashboard_Insert = NewComboCounterRef("models.dashboard.insert")
+)
diff --git a/pkg/metrics/registry.go b/pkg/metrics/registry.go
new file mode 100644
index 00000000000..9e1618f3691
--- /dev/null
+++ b/pkg/metrics/registry.go
@@ -0,0 +1,102 @@
+package metrics
+
+import (
+ "fmt"
+ "reflect"
+ "sync"
+)
+
+// DuplicateMetric is the error returned by Registry.Register when a metric
+// already exists. If you mean to Register that metric you must first
+// Unregister the existing metric.
+type DuplicateMetric string
+
+func (err DuplicateMetric) Error() string {
+ return fmt.Sprintf("duplicate metric: %s", string(err))
+}
+
+type Registry interface {
+ // Call the given function for each registered metric.
+ Each(func(string, interface{}))
+
+ // Get the metric by the given name or nil if none is registered.
+ Get(string) interface{}
+
+ // Gets an existing metric or registers the given one.
+ // The interface can be the metric to register if not found in registry,
+ // or a function returning the metric for lazy instantiation.
+ GetOrRegister(string, interface{}) interface{}
+
+ // Register the given metric under the given name.
+ Register(string, interface{}) error
+}
+
+// The standard implementation of a Registry is a mutex-protected map
+// of names to metrics.
+type StandardRegistry struct {
+ metrics map[string]interface{}
+ mutex sync.Mutex
+}
+
+// Create a new registry.
+func NewRegistry() Registry {
+ return &StandardRegistry{metrics: make(map[string]interface{})}
+}
+
+// Call the given function for each registered metric.
+func (r *StandardRegistry) Each(f func(string, interface{})) {
+ for name, i := range r.registered() {
+ f(name, i)
+ }
+}
+
+// Get the metric by the given name or nil if none is registered.
+func (r *StandardRegistry) Get(name string) interface{} {
+ r.mutex.Lock()
+ defer r.mutex.Unlock()
+ return r.metrics[name]
+}
+
+// Gets an existing metric or creates and registers a new one. Threadsafe
+// alternative to calling Get and Register on failure.
+// The interface can be the metric to register if not found in registry,
+// or a function returning the metric for lazy instantiation.
+func (r *StandardRegistry) GetOrRegister(name string, i interface{}) interface{} {
+ r.mutex.Lock()
+ defer r.mutex.Unlock()
+ if metric, ok := r.metrics[name]; ok {
+ return metric
+ }
+ if v := reflect.ValueOf(i); v.Kind() == reflect.Func {
+ i = v.Call(nil)[0].Interface()
+ }
+ r.register(name, i)
+ return i
+}
+
+// Register the given metric under the given name. Returns a DuplicateMetric
+// if a metric by the given name is already registered.
+func (r *StandardRegistry) Register(name string, i interface{}) error {
+ r.mutex.Lock()
+ defer r.mutex.Unlock()
+ return r.register(name, i)
+}
+
+func (r *StandardRegistry) register(name string, i interface{}) error {
+ if _, ok := r.metrics[name]; ok {
+ return DuplicateMetric(name)
+ }
+
+ r.metrics[name] = i
+ return nil
+}
+
+func (r *StandardRegistry) registered() map[string]interface{} {
+ metrics := make(map[string]interface{}, len(r.metrics))
+ r.mutex.Lock()
+ defer r.mutex.Unlock()
+ for name, i := range r.metrics {
+ metrics[name] = i
+ }
+ return metrics
+}
diff --git a/pkg/metrics/report_usage.go b/pkg/metrics/report_usage.go
new file mode 100644
index 00000000000..c8848fb5371
--- /dev/null
+++ b/pkg/metrics/report_usage.go
@@ -0,0 +1,64 @@
+package metrics
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/grafana/grafana/pkg/bus"
+ "github.com/grafana/grafana/pkg/log"
+ m "github.com/grafana/grafana/pkg/models"
+ "github.com/grafana/grafana/pkg/setting"
+)
+
+func StartUsageReportLoop() chan struct{} {
+ M_Instance_Start.Inc(1)
+
+ ticker := time.NewTicker(time.Hour * 24)
+ for {
+ select {
+ case <-ticker.C:
+ sendUsageStats()
+ }
+ }
+}
+
+func sendUsageStats() {
+ log.Trace("Sending anonymous usage stats to stats.grafana.org")
+
+ version := strings.Replace(setting.BuildVersion, ".", "_", -1)
+
+ metrics := map[string]interface{}{}
+ report := map[string]interface{}{
+ "version": version,
+ "metrics": metrics,
+ }
+
+ statsQuery := m.GetSystemStatsQuery{}
+ if err := bus.Dispatch(&statsQuery); err != nil {
+ log.Error(3, "Failed to get system stats", err)
+ return
+ }
+
+ UsageStats.Each(func(name string, i interface{}) {
+ switch metric := i.(type) {
+ case Counter:
+ if metric.Count() > 0 {
+ metrics[name+".count"] = metric.Count()
+ metric.Clear()
+ }
+ }
+ })
+
+ metrics["stats.dashboards.count"] = statsQuery.Result.DashboardCount
+ metrics["stats.users.count"] = statsQuery.Result.UserCount
+ metrics["stats.orgs.count"] = statsQuery.Result.OrgCount
+
+ out, _ := json.Marshal(report)
+ data := bytes.NewBuffer(out)
+
+ client := http.Client{Timeout: time.Duration(5 * time.Second)}
+ go client.Post("https://stats.grafana.org/grafana-usage-report", "application/json", data)
+}
diff --git a/pkg/middleware/middleware.go b/pkg/middleware/middleware.go
index a15fd075fca..20e1eb196e5 100644
--- a/pkg/middleware/middleware.go
+++ b/pkg/middleware/middleware.go
@@ -10,6 +10,7 @@ import (
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/apikeygen"
"github.com/grafana/grafana/pkg/log"
+ "github.com/grafana/grafana/pkg/metrics"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
)
@@ -99,6 +100,15 @@ func (ctx *Context) Handle(status int, title string, err error) {
}
}
+ switch status {
+ case 200:
+ metrics.M_Page_Status_200.Inc(1)
+ case 404:
+ metrics.M_Page_Status_404.Inc(1)
+ case 500:
+ metrics.M_Page_Status_500.Inc(1)
+ }
+
ctx.Data["Title"] = title
ctx.HTML(status, strconv.Itoa(status))
}
@@ -128,7 +138,9 @@ func (ctx *Context) JsonApiErr(status int, message string, err error) {
switch status {
case 404:
resp["message"] = "Not Found"
+ metrics.M_Api_Status_500.Inc(1)
case 500:
+ metrics.M_Api_Status_404.Inc(1)
resp["message"] = "Internal Server Error"
}
diff --git a/pkg/models/dashboard_snapshot.go b/pkg/models/dashboard_snapshot.go
new file mode 100644
index 00000000000..e8f37e2a236
--- /dev/null
+++ b/pkg/models/dashboard_snapshot.go
@@ -0,0 +1,49 @@
+package models
+
+import "time"
+
+// DashboardSnapshot model
+type DashboardSnapshot struct {
+ Id int64
+ Name string
+ Key string
+ DeleteKey string
+ OrgId int64
+ UserId int64
+ External bool
+ ExternalUrl string
+
+ Expires time.Time
+ Created time.Time
+ Updated time.Time
+
+ Dashboard map[string]interface{}
+}
+
+// -----------------
+// COMMANDS
+
+type CreateDashboardSnapshotCommand struct {
+ Dashboard map[string]interface{} `json:"dashboard" binding:"Required"`
+ Expires int64 `json:"expires"`
+
+ // these are passed when storing an external snapshot ref
+ External bool `json:"external"`
+ Key string `json:"key"`
+ DeleteKey string `json:"deleteKey"`
+
+ OrgId int64 `json:"-"`
+ UserId int64 `json:"-"`
+
+ Result *DashboardSnapshot
+}
+
+type DeleteDashboardSnapshotCommand struct {
+ DeleteKey string `json:"-"`
+}
+
+type GetDashboardSnapshotQuery struct {
+ Key string
+
+ Result *DashboardSnapshot
+}
diff --git a/pkg/models/models.go b/pkg/models/models.go
index 189e594576b..c38f0c5a391 100644
--- a/pkg/models/models.go
+++ b/pkg/models/models.go
@@ -1,5 +1,7 @@
package models
+import "errors"
+
type OAuthType int
const (
@@ -7,3 +9,5 @@ const (
GOOGLE
TWITTER
)
+
+var ErrNotFound = errors.New("Not found")
diff --git a/pkg/models/stats.go b/pkg/models/stats.go
new file mode 100644
index 00000000000..0d83882e666
--- /dev/null
+++ b/pkg/models/stats.go
@@ -0,0 +1,11 @@
+package models
+
+type SystemStats struct {
+ DashboardCount int
+ UserCount int
+ OrgCount int
+}
+
+type GetSystemStatsQuery struct {
+ Result *SystemStats
+}
diff --git a/pkg/services/sqlstore/apikey_test.go b/pkg/services/sqlstore/apikey_test.go
index e86a1c0db33..790c8837def 100644
--- a/pkg/services/sqlstore/apikey_test.go
+++ b/pkg/services/sqlstore/apikey_test.go
@@ -21,8 +21,8 @@ func TestApiKeyDataAccess(t *testing.T) {
Convey("Should be able to get key by name", func() {
query := m.GetApiKeyByNameQuery{KeyName: "hello", OrgId: 1}
err = GetApiKeyByName(&query)
- So(err, ShouldBeNil)
+ So(err, ShouldBeNil)
So(query.Result, ShouldNotBeNil)
})
diff --git a/pkg/services/sqlstore/dashboard.go b/pkg/services/sqlstore/dashboard.go
index bf748b600f4..0384a5bb6e6 100644
--- a/pkg/services/sqlstore/dashboard.go
+++ b/pkg/services/sqlstore/dashboard.go
@@ -6,6 +6,7 @@ import (
"github.com/go-xorm/xorm"
"github.com/grafana/grafana/pkg/bus"
+ "github.com/grafana/grafana/pkg/metrics"
m "github.com/grafana/grafana/pkg/models"
)
@@ -48,6 +49,7 @@ func SaveDashboard(cmd *m.SaveDashboardCommand) error {
}
if dash.Id == 0 {
+ metrics.M_Models_Dashboard_Insert.Inc(1)
_, err = sess.Insert(dash)
} else {
dash.Version += 1
diff --git a/pkg/services/sqlstore/dashboard_snapshot.go b/pkg/services/sqlstore/dashboard_snapshot.go
new file mode 100644
index 00000000000..0bbb01ed6bd
--- /dev/null
+++ b/pkg/services/sqlstore/dashboard_snapshot.go
@@ -0,0 +1,65 @@
+package sqlstore
+
+import (
+ "time"
+
+ "github.com/go-xorm/xorm"
+ "github.com/grafana/grafana/pkg/bus"
+ m "github.com/grafana/grafana/pkg/models"
+)
+
+func init() {
+ bus.AddHandler("sql", CreateDashboardSnapshot)
+ bus.AddHandler("sql", GetDashboardSnapshot)
+ bus.AddHandler("sql", DeleteDashboardSnapshot)
+}
+
+func CreateDashboardSnapshot(cmd *m.CreateDashboardSnapshotCommand) error {
+ return inTransaction(func(sess *xorm.Session) error {
+
+ // never
+ var expires = time.Now().Add(time.Hour * 24 * 365 * 50)
+ if cmd.Expires > 0 {
+ expires = time.Now().Add(time.Second * time.Duration(cmd.Expires))
+ }
+
+ snapshot := &m.DashboardSnapshot{
+ Key: cmd.Key,
+ DeleteKey: cmd.DeleteKey,
+ OrgId: cmd.OrgId,
+ UserId: cmd.UserId,
+ External: cmd.External,
+ Dashboard: cmd.Dashboard,
+ Expires: expires,
+ Created: time.Now(),
+ Updated: time.Now(),
+ }
+
+ _, err := sess.Insert(snapshot)
+ cmd.Result = snapshot
+
+ return err
+ })
+}
+
+func DeleteDashboardSnapshot(cmd *m.DeleteDashboardSnapshotCommand) error {
+ return inTransaction(func(sess *xorm.Session) error {
+ var rawSql = "DELETE FROM dashboard_snapshot WHERE delete_key=?"
+ _, err := sess.Exec(rawSql, cmd.DeleteKey)
+ return err
+ })
+}
+
+func GetDashboardSnapshot(query *m.GetDashboardSnapshotQuery) error {
+ snapshot := m.DashboardSnapshot{Key: query.Key}
+ has, err := x.Get(&snapshot)
+
+ if err != nil {
+ return err
+ } else if has == false {
+ return m.ErrNotFound
+ }
+
+ query.Result = &snapshot
+ return nil
+}
diff --git a/pkg/services/sqlstore/dashboard_snapshot_test.go b/pkg/services/sqlstore/dashboard_snapshot_test.go
new file mode 100644
index 00000000000..5301f0f1cc9
--- /dev/null
+++ b/pkg/services/sqlstore/dashboard_snapshot_test.go
@@ -0,0 +1,37 @@
+package sqlstore
+
+import (
+ "testing"
+
+ . "github.com/smartystreets/goconvey/convey"
+
+ m "github.com/grafana/grafana/pkg/models"
+)
+
+func TestDashboardSnapshotDBAccess(t *testing.T) {
+
+ Convey("Testing DashboardSnapshot data access", t, func() {
+ InitTestDB(t)
+
+ Convey("Given saved snaphot", func() {
+ cmd := m.CreateDashboardSnapshotCommand{
+ Key: "hej",
+ Dashboard: map[string]interface{}{
+ "hello": "mupp",
+ },
+ }
+ err := CreateDashboardSnapshot(&cmd)
+ So(err, ShouldBeNil)
+
+ Convey("Should be able to get snaphot by key", func() {
+ query := m.GetDashboardSnapshotQuery{Key: "hej"}
+ err = GetDashboardSnapshot(&query)
+ So(err, ShouldBeNil)
+
+ So(query.Result, ShouldNotBeNil)
+ So(query.Result.Dashboard["hello"], ShouldEqual, "mupp")
+ })
+
+ })
+ })
+}
diff --git a/pkg/services/sqlstore/migrations/dashboard_snapshot_mig.go b/pkg/services/sqlstore/migrations/dashboard_snapshot_mig.go
new file mode 100644
index 00000000000..4d83dfd5bc6
--- /dev/null
+++ b/pkg/services/sqlstore/migrations/dashboard_snapshot_mig.go
@@ -0,0 +1,51 @@
+package migrations
+
+import . "github.com/grafana/grafana/pkg/services/sqlstore/migrator"
+
+func addDashboardSnapshotMigrations(mg *Migrator) {
+ snapshotV4 := Table{
+ Name: "dashboard_snapshot",
+ Columns: []*Column{
+ {Name: "id", Type: DB_BigInt, IsPrimaryKey: true, IsAutoIncrement: true},
+ {Name: "name", Type: DB_NVarchar, Length: 255, Nullable: false},
+ {Name: "key", Type: DB_NVarchar, Length: 255, Nullable: false},
+ {Name: "dashboard", Type: DB_Text, Nullable: false},
+ {Name: "expires", Type: DB_DateTime, Nullable: false},
+ {Name: "created", Type: DB_DateTime, Nullable: false},
+ {Name: "updated", Type: DB_DateTime, Nullable: false},
+ },
+ Indices: []*Index{
+ {Cols: []string{"key"}, Type: UniqueIndex},
+ },
+ }
+
+ // add v4
+ mg.AddMigration("create dashboard_snapshot table v4", NewAddTableMigration(snapshotV4))
+ mg.AddMigration("drop table dashboard_snapshot_v4 #1", NewDropTableMigration("dashboard_snapshot"))
+
+ snapshotV5 := Table{
+ Name: "dashboard_snapshot",
+ Columns: []*Column{
+ {Name: "id", Type: DB_BigInt, IsPrimaryKey: true, IsAutoIncrement: true},
+ {Name: "name", Type: DB_NVarchar, Length: 255, Nullable: false},
+ {Name: "key", Type: DB_NVarchar, Length: 255, Nullable: false},
+ {Name: "delete_key", Type: DB_NVarchar, Length: 255, Nullable: false},
+ {Name: "org_id", Type: DB_BigInt, Nullable: false},
+ {Name: "user_id", Type: DB_BigInt, Nullable: false},
+ {Name: "external", Type: DB_Bool, Nullable: false},
+ {Name: "external_url", Type: DB_NVarchar, Length: 255, Nullable: false},
+ {Name: "dashboard", Type: DB_Text, Nullable: false},
+ {Name: "expires", Type: DB_DateTime, Nullable: false},
+ {Name: "created", Type: DB_DateTime, Nullable: false},
+ {Name: "updated", Type: DB_DateTime, Nullable: false},
+ },
+ Indices: []*Index{
+ {Cols: []string{"key"}, Type: UniqueIndex},
+ {Cols: []string{"delete_key"}, Type: UniqueIndex},
+ {Cols: []string{"user_id"}},
+ },
+ }
+
+ mg.AddMigration("create dashboard_snapshot table v5 #2", NewAddTableMigration(snapshotV5))
+ addTableIndicesMigrations(mg, "v5", snapshotV5)
+}
diff --git a/pkg/services/sqlstore/migrations/datasource_mig.go b/pkg/services/sqlstore/migrations/datasource_mig.go
index 924e1a16189..4f046b1f8e9 100644
--- a/pkg/services/sqlstore/migrations/datasource_mig.go
+++ b/pkg/services/sqlstore/migrations/datasource_mig.go
@@ -95,5 +95,5 @@ func addDataSourceMigration(mg *Migrator) {
"updated": "updated",
}))
- mg.AddMigration("Drop old table data_source_v1", NewDropTableMigration("data_source_old"))
+ mg.AddMigration("Drop old table data_source_v1 #2", NewDropTableMigration("data_source_v1"))
}
diff --git a/pkg/services/sqlstore/migrations/migrations.go b/pkg/services/sqlstore/migrations/migrations.go
index c48167d97e5..329c6187c9d 100644
--- a/pkg/services/sqlstore/migrations/migrations.go
+++ b/pkg/services/sqlstore/migrations/migrations.go
@@ -15,6 +15,7 @@ func AddMigrations(mg *Migrator) {
addDashboardMigration(mg)
addDataSourceMigration(mg)
addApiKeyMigrations(mg)
+ addDashboardSnapshotMigrations(mg)
}
func addMigrationLogMigrations(mg *Migrator) {
diff --git a/pkg/services/sqlstore/sqlstore.go b/pkg/services/sqlstore/sqlstore.go
index 218f24f0142..757953f5b4e 100644
--- a/pkg/services/sqlstore/sqlstore.go
+++ b/pkg/services/sqlstore/sqlstore.go
@@ -22,7 +22,6 @@ import (
var (
x *xorm.Engine
dialect migrator.Dialect
- tables []interface{}
HasEngine bool
@@ -80,10 +79,6 @@ func SetEngine(engine *xorm.Engine, enableLog bool) (err error) {
return fmt.Errorf("Sqlstore::Migration failed err: %v\n", err)
}
- if err := x.Sync2(tables...); err != nil {
- return fmt.Errorf("sync database struct error: %v\n", err)
- }
-
if enableLog {
logPath := path.Join(setting.LogRootPath, "xorm.log")
os.MkdirAll(path.Dir(logPath), os.ModePerm)
@@ -94,11 +89,13 @@ func SetEngine(engine *xorm.Engine, enableLog bool) (err error) {
}
x.Logger = xorm.NewSimpleLogger(f)
- x.ShowSQL = true
- x.ShowInfo = true
- x.ShowDebug = true
- x.ShowErr = true
- x.ShowWarn = true
+ if setting.Env == setting.DEV {
+ x.ShowSQL = false
+ x.ShowInfo = false
+ x.ShowDebug = false
+ x.ShowErr = true
+ x.ShowWarn = true
+ }
}
return nil
@@ -125,7 +122,7 @@ func getEngine() (*xorm.Engine, error) {
DbCfg.User, DbCfg.Pwd, host, port, DbCfg.Name, DbCfg.SslMode)
case "sqlite3":
os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm)
- cnnstr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc"
+ cnnstr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc&_loc=Local"
default:
return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
}
diff --git a/pkg/services/sqlstore/sqlstore.goconvey b/pkg/services/sqlstore/sqlstore.goconvey
new file mode 100644
index 00000000000..92feb5268a5
--- /dev/null
+++ b/pkg/services/sqlstore/sqlstore.goconvey
@@ -0,0 +1 @@
+-timeout=10s
diff --git a/pkg/services/sqlstore/sqlutil/sqlutil.go b/pkg/services/sqlstore/sqlutil/sqlutil.go
index f873a1a2f9f..075b56c1c18 100644
--- a/pkg/services/sqlstore/sqlutil/sqlutil.go
+++ b/pkg/services/sqlstore/sqlutil/sqlutil.go
@@ -11,7 +11,7 @@ type TestDB struct {
ConnStr string
}
-var TestDB_Sqlite3 = TestDB{DriverName: "sqlite3", ConnStr: ":memory:"}
+var TestDB_Sqlite3 = TestDB{DriverName: "sqlite3", ConnStr: ":memory:?_loc=Local"}
var TestDB_Mysql = TestDB{DriverName: "mysql", ConnStr: "grafana:password@tcp(localhost:3306)/grafana_tests?charset=utf8"}
var TestDB_Postgres = TestDB{DriverName: "postgres", ConnStr: "user=grafanatest password=grafanatest host=localhost port=5432 dbname=grafanatest sslmode=disable"}
diff --git a/pkg/services/sqlstore/stats.go b/pkg/services/sqlstore/stats.go
new file mode 100644
index 00000000000..7995dd43f38
--- /dev/null
+++ b/pkg/services/sqlstore/stats.go
@@ -0,0 +1,36 @@
+package sqlstore
+
+import (
+ "github.com/grafana/grafana/pkg/bus"
+ m "github.com/grafana/grafana/pkg/models"
+)
+
+func init() {
+ bus.AddHandler("sql", GetSystemStats)
+}
+
+func GetSystemStats(query *m.GetSystemStatsQuery) error {
+ var rawSql = `SELECT
+ (
+ SELECT COUNT(*)
+ FROM ` + dialect.Quote("user") + `
+ ) AS user_count,
+ (
+ SELECT COUNT(*)
+ FROM ` + dialect.Quote("org") + `
+ ) AS org_count,
+ (
+ SELECT COUNT(*)
+ FROM ` + dialect.Quote("dashboard") + `
+ ) AS dashboard_count
+ `
+
+ var stats m.SystemStats
+ _, err := x.Sql(rawSql).Get(&stats)
+ if err != nil {
+ return err
+ }
+
+ query.Result = &stats
+ return err
+}
diff --git a/pkg/services/sqlstore/xorm.log b/pkg/services/sqlstore/xorm.log
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/pkg/setting/setting.go b/pkg/setting/setting.go
index b8d038dbc29..defa8311e8c 100644
--- a/pkg/setting/setting.go
+++ b/pkg/setting/setting.go
@@ -96,6 +96,8 @@ var (
PhantomDir string
configFiles []string
+
+ ReportingEnabled bool
)
func init() {
@@ -233,6 +235,8 @@ func NewConfigContext(config string) {
ImagesDir = "data/png"
PhantomDir = "vendor/phantomjs"
+ ReportingEnabled = Cfg.Section("").Key("reporting-enabled").MustBool(true)
+
readSessionConfig()
}
diff --git a/src/app/directives/graphiteSegment.js b/src/app/directives/graphiteSegment.js
index 577bbf5d6b7..c8ad131e6c7 100644
--- a/src/app/directives/graphiteSegment.js
+++ b/src/app/directives/graphiteSegment.js
@@ -37,12 +37,14 @@ function (angular, app, _, $) {
if (selected) {
segment.value = selected.value;
segment.html = selected.html;
+ segment.fake = false;
segment.expandable = selected.expandable;
}
else {
segment.value = value;
segment.html = $sce.trustAsHtml(value);
segment.expandable = true;
+ segment.fake = false;
}
$scope.segmentValueChanged(segment, $scope.$index);
});
@@ -71,7 +73,7 @@ function (angular, app, _, $) {
options = _.map($scope.altSegments, function(alt) { return alt.value; });
// add custom values
- if (segment.value !== 'select metric' && _.indexOf(options, segment.value) === -1) {
+ if (!segment.fake && _.indexOf(options, segment.value) === -1) {
options.unshift(segment.value);
}
diff --git a/src/app/directives/templateParamSelector.js b/src/app/directives/templateParamSelector.js
index 6cd2ce5a964..3d7a9f964d4 100644
--- a/src/app/directives/templateParamSelector.js
+++ b/src/app/directives/templateParamSelector.js
@@ -4,87 +4,9 @@ define([
'lodash',
'jquery',
],
-function (angular, app, _, $) {
+function (angular, app, _) {
'use strict';
- angular
- .module('grafana.directives')
- .directive('templateParamSelector', function($compile) {
- var inputTemplate = '';
-
- var buttonTemplate = '{{variable.current.text}} ';
-
- return {
- link: function($scope, elem) {
- var $input = $(inputTemplate);
- var $button = $(buttonTemplate);
- var variable = $scope.variable;
-
- $input.appendTo(elem);
- $button.appendTo(elem);
-
- function updateVariableValue(value) {
- $scope.$apply(function() {
- var selected = _.findWhere(variable.options, { text: value });
- if (!selected) {
- selected = { text: value, value: value };
- }
- $scope.setVariableValue($scope.variable, selected);
- });
- }
-
- $input.attr('data-provide', 'typeahead');
- $input.typeahead({
- minLength: 0,
- items: 1000,
- updater: function(value) {
- $input.val(value);
- $input.trigger('blur');
- return value;
- }
- });
-
- var typeahead = $input.data('typeahead');
- typeahead.lookup = function () {
- var options = _.map(variable.options, function(option) { return option.text; });
- this.query = this.$element.val() || '';
- return this.process(options);
- };
-
- $button.click(function() {
- $input.css('width', ($button.width() + 16) + 'px');
-
- $button.hide();
- $input.show();
- $input.focus();
-
- var typeahead = $input.data('typeahead');
- if (typeahead) {
- $input.val('');
- typeahead.lookup();
- }
-
- });
-
- $input.blur(function() {
- if ($input.val() !== '') { updateVariableValue($input.val()); }
- $input.hide();
- $button.show();
- $button.focus();
- });
-
- $scope.$on('$destroy', function() {
- $button.unbind();
- typeahead.destroy();
- });
-
- $compile(elem.contents())($scope);
- }
- };
- });
-
angular
.module('grafana.directives')
.directive('variableValueSelect', function($compile, $window, $timeout) {
@@ -162,9 +84,9 @@ function (angular, app, _, $) {
scope.hide = function() {
scope.selectorOpen = false;
- if (scope.oldCurrentText !== variable.current.text) {
- scope.onUpdated();
- }
+ // if (scope.oldCurrentText !== variable.current.text) {
+ // scope.onUpdated();
+ // }
bodyEl.off('click', scope.bodyOnClick);
};
diff --git a/src/app/features/dashboard/all.js b/src/app/features/dashboard/all.js
index 811f48cc464..f658011bc3d 100644
--- a/src/app/features/dashboard/all.js
+++ b/src/app/features/dashboard/all.js
@@ -5,6 +5,7 @@ define([
'./playlistCtrl',
'./rowCtrl',
'./sharePanelCtrl',
+ './shareSnapshotCtrl',
'./submenuCtrl',
'./dashboardSrv',
'./keybindings',
diff --git a/src/app/features/dashboard/dashboardCtrl.js b/src/app/features/dashboard/dashboardCtrl.js
index c194dcdb7ed..76060e64a70 100644
--- a/src/app/features/dashboard/dashboardCtrl.js
+++ b/src/app/features/dashboard/dashboardCtrl.js
@@ -18,6 +18,7 @@ function (angular, $, config) {
dynamicDashboardSrv,
dashboardSrv,
dashboardViewStateSrv,
+ contextSrv,
$timeout) {
$scope.editor = { index: 0 };
@@ -49,7 +50,7 @@ function (angular, $, config) {
$scope.dashboard = dashboard;
$scope.dashboardViewState = dashboardViewStateSrv.create($scope);
- $scope.dashboardMeta = data.meta;
+ $scope.initDashboardMeta(data.meta, $scope.dashboard);
dashboardKeybindings.shortcuts($scope);
@@ -60,6 +61,33 @@ function (angular, $, config) {
});
};
+ $scope.initDashboardMeta = function(meta, dashboard) {
+ meta.canShare = true;
+ meta.canSave = true;
+ meta.canEdit = true;
+ meta.canStar = true;
+
+ if (contextSrv.hasRole('Viewer')) {
+ meta.canSave = false;
+ }
+
+ if (meta.isHome) {
+ meta.canShare = false;
+ meta.canStar = false;
+ meta.canSave = false;
+ meta.canEdit = false;
+ }
+
+ if (dashboard.snapshot) {
+ meta.canEdit = false;
+ meta.canSave = false;
+ meta.canStar = false;
+ meta.canShare = false;
+ }
+
+ $scope.dashboardMeta = meta;
+ };
+
$scope.updateSubmenuVisibility = function() {
$scope.submenuEnabled = $scope.dashboard.hasTemplateVarsOrAnnotations();
};
@@ -135,4 +163,5 @@ function (angular, $, config) {
};
});
+
});
diff --git a/src/app/features/dashboard/dashboardNavCtrl.js b/src/app/features/dashboard/dashboardNavCtrl.js
index 5950c504a3a..17bdfb5efc7 100644
--- a/src/app/features/dashboard/dashboardNavCtrl.js
+++ b/src/app/features/dashboard/dashboardNavCtrl.js
@@ -11,7 +11,7 @@ function (angular, _, moment) {
var module = angular.module('grafana.controllers');
- module.controller('DashboardNavCtrl', function($scope, $rootScope, alertSrv, $location, playlistSrv, backendSrv, timeSrv) {
+ module.controller('DashboardNavCtrl', function($scope, $rootScope, alertSrv, $location, playlistSrv, backendSrv, timeSrv, $timeout) {
$scope.init = function() {
$scope.onAppEvent('save-dashboard', $scope.saveDashboard);
@@ -157,6 +157,18 @@ function (angular, _, moment) {
});
};
+ $scope.snapshot = function() {
+ $scope.dashboard.snapshot = true;
+ $rootScope.$broadcast('refresh');
+
+ $timeout(function() {
+ $scope.exportDashboard();
+ $scope.dashboard.snapshot = false;
+ $scope.appEvent('dashboard-snapshot-cleanup');
+ }, 1000);
+
+ };
+
$scope.editJson = function() {
$scope.appEvent('show-json-editor', { object: $scope.dashboard });
};
diff --git a/src/app/features/dashboard/dashboardSrv.js b/src/app/features/dashboard/dashboardSrv.js
index 0eab4f867d9..a4e50b1d70c 100644
--- a/src/app/features/dashboard/dashboardSrv.js
+++ b/src/app/features/dashboard/dashboardSrv.js
@@ -37,6 +37,7 @@ function (angular, $, kbn, _, moment) {
this.templating = this._ensureListExist(data.templating);
this.annotations = this._ensureListExist(data.annotations);
this.refresh = data.refresh;
+ this.snapshot = data.snapshot;
this.schemaVersion = data.schemaVersion || 0;
this.version = data.version || 0;
@@ -67,6 +68,16 @@ function (angular, $, kbn, _, moment) {
return max + 1;
};
+ p.forEachPanel = function(callback) {
+ var i, j, row;
+ for (i = 0; i < this.rows.length; i++) {
+ row = this.rows[i];
+ for (j = 0; j < row.panels.length; j++) {
+ callback(row.panels[j], row);
+ }
+ }
+ };
+
p.rowSpan = function(row) {
return _.reduce(row.panels, function(p,v) {
return p + v.span;
diff --git a/src/app/features/dashboard/dynamicDashboardSrv.js b/src/app/features/dashboard/dynamicDashboardSrv.js
index f7956fd94a7..ba70bd0b018 100644
--- a/src/app/features/dashboard/dynamicDashboardSrv.js
+++ b/src/app/features/dashboard/dynamicDashboardSrv.js
@@ -103,11 +103,12 @@ function (angular, _) {
}
for (i = 0; i < copy.panels.length; i++) {
- panel = row.panels[i];
+ panel = copy.panels[i];
panel.scopedVars = panel.scopedVars || {};
panel.scopedVars[variable.name] = option;
}
});
+
};
this.repeatPanel = function(panel, row, dashboard) {
diff --git a/src/app/features/dashboard/partials/shareDashboard.html b/src/app/features/dashboard/partials/shareDashboard.html
index e052c5b298f..fefca5a9100 100644
--- a/src/app/features/dashboard/partials/shareDashboard.html
+++ b/src/app/features/dashboard/partials/shareDashboard.html
@@ -1,12 +1,12 @@