github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/builtin/providers/influxdb/continuous_query.go (about) 1 package influxdb 2 3 import ( 4 "fmt" 5 6 "github.com/hashicorp/terraform/helper/schema" 7 "github.com/influxdata/influxdb/client" 8 ) 9 10 func resourceContinuousQuery() *schema.Resource { 11 return &schema.Resource{ 12 Create: createContinuousQuery, 13 Read: readContinuousQuery, 14 Delete: deleteContinuousQuery, 15 16 Schema: map[string]*schema.Schema{ 17 "name": &schema.Schema{ 18 Type: schema.TypeString, 19 Required: true, 20 ForceNew: true, 21 }, 22 "database": &schema.Schema{ 23 Type: schema.TypeString, 24 Required: true, 25 ForceNew: true, 26 }, 27 "query": &schema.Schema{ 28 Type: schema.TypeString, 29 Required: true, 30 ForceNew: true, 31 }, 32 }, 33 } 34 } 35 36 func createContinuousQuery(d *schema.ResourceData, meta interface{}) error { 37 conn := meta.(*client.Client) 38 39 name := d.Get("name").(string) 40 database := d.Get("database").(string) 41 42 queryStr := fmt.Sprintf("CREATE CONTINUOUS QUERY %s ON %s BEGIN %s END", name, quoteIdentifier(database), d.Get("query").(string)) 43 query := client.Query{ 44 Command: queryStr, 45 } 46 47 resp, err := conn.Query(query) 48 if err != nil { 49 return err 50 } 51 if resp.Err != nil { 52 return resp.Err 53 } 54 55 d.Set("name", name) 56 d.Set("database", database) 57 d.Set("query", d.Get("query").(string)) 58 d.SetId(fmt.Sprintf("influxdb-cq:%s", name)) 59 60 return readContinuousQuery(d, meta) 61 } 62 63 func readContinuousQuery(d *schema.ResourceData, meta interface{}) error { 64 conn := meta.(*client.Client) 65 name := d.Get("name").(string) 66 database := d.Get("database").(string) 67 68 // InfluxDB doesn't have a command to check the existence of a single 69 // ContinuousQuery, so we instead must read the list of all ContinuousQuerys and see 70 // if ours is present in it. 71 query := client.Query{ 72 Command: "SHOW CONTINUOUS QUERIES", 73 } 74 75 resp, err := conn.Query(query) 76 if err != nil { 77 return err 78 } 79 if resp.Err != nil { 80 return resp.Err 81 } 82 83 for _, series := range resp.Results[0].Series { 84 if series.Name == database { 85 for _, result := range series.Values { 86 if result[0].(string) == name { 87 return nil 88 } 89 } 90 } 91 } 92 93 // If we fell out here then we didn't find our ContinuousQuery in the list. 94 d.SetId("") 95 96 return nil 97 } 98 99 func deleteContinuousQuery(d *schema.ResourceData, meta interface{}) error { 100 conn := meta.(*client.Client) 101 name := d.Get("name").(string) 102 database := d.Get("database").(string) 103 104 queryStr := fmt.Sprintf("DROP CONTINUOUS QUERY %s ON %s", name, quoteIdentifier(database)) 105 query := client.Query{ 106 Command: queryStr, 107 } 108 109 resp, err := conn.Query(query) 110 if err != nil { 111 return err 112 } 113 if resp.Err != nil { 114 return resp.Err 115 } 116 117 d.SetId("") 118 119 return nil 120 }