vtable.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "github.com/mattn/go-sqlite3"
  8. )
  9. type githubRepo struct {
  10. ID int `json:"id"`
  11. FullName string `json:"full_name"`
  12. Description string `json:"description"`
  13. HTMLURL string `json:"html_url"`
  14. }
  15. type githubModule struct {
  16. }
  17. func (m *githubModule) Create(c *sqlite3.SQLiteConn, args []string) (sqlite3.VTab, error) {
  18. err := c.DeclareVTab(fmt.Sprintf(`
  19. CREATE TABLE %s (
  20. id INT,
  21. full_name TEXT,
  22. description TEXT,
  23. html_url TEXT
  24. )`, args[0]))
  25. if err != nil {
  26. return nil, err
  27. }
  28. return &ghRepoTable{}, nil
  29. }
  30. func (m *githubModule) Connect(c *sqlite3.SQLiteConn, args []string) (sqlite3.VTab, error) {
  31. return m.Create(c, args)
  32. }
  33. func (m *githubModule) DestroyModule() {}
  34. type ghRepoTable struct {
  35. repos []githubRepo
  36. }
  37. func (v *ghRepoTable) Open() (sqlite3.VTabCursor, error) {
  38. resp, err := http.Get("https://api.github.com/repositories")
  39. if err != nil {
  40. return nil, err
  41. }
  42. defer resp.Body.Close()
  43. body, err := ioutil.ReadAll(resp.Body)
  44. if err != nil {
  45. return nil, err
  46. }
  47. var repos []githubRepo
  48. if err := json.Unmarshal(body, &repos); err != nil {
  49. return nil, err
  50. }
  51. return &ghRepoCursor{0, repos}, nil
  52. }
  53. func (v *ghRepoTable) BestIndex(cst []sqlite3.InfoConstraint, ob []sqlite3.InfoOrderBy) (*sqlite3.IndexResult, error) {
  54. return &sqlite3.IndexResult{}, nil
  55. }
  56. func (v *ghRepoTable) Disconnect() error { return nil }
  57. func (v *ghRepoTable) Destroy() error { return nil }
  58. type ghRepoCursor struct {
  59. index int
  60. repos []githubRepo
  61. }
  62. func (vc *ghRepoCursor) Column(c *sqlite3.SQLiteContext, col int) error {
  63. switch col {
  64. case 0:
  65. c.ResultInt(vc.repos[vc.index].ID)
  66. case 1:
  67. c.ResultText(vc.repos[vc.index].FullName)
  68. case 2:
  69. c.ResultText(vc.repos[vc.index].Description)
  70. case 3:
  71. c.ResultText(vc.repos[vc.index].HTMLURL)
  72. }
  73. return nil
  74. }
  75. func (vc *ghRepoCursor) Filter(idxNum int, idxStr string, vals []interface{}) error {
  76. vc.index = 0
  77. return nil
  78. }
  79. func (vc *ghRepoCursor) Next() error {
  80. vc.index++
  81. return nil
  82. }
  83. func (vc *ghRepoCursor) EOF() bool {
  84. return vc.index >= len(vc.repos)
  85. }
  86. func (vc *ghRepoCursor) Rowid() (int64, error) {
  87. return int64(vc.index), nil
  88. }
  89. func (vc *ghRepoCursor) Close() error {
  90. return nil
  91. }