blob: 300e17715bd885e40d44eb5b9ba9b9e685927841 [file] [log] [blame]
Jamie Hannaford1943b382015-02-12 11:50:02 +01001package databases
2
3import (
4 "fmt"
5
6 "github.com/racker/perigee"
7 "github.com/rackspace/gophercloud"
8 "github.com/rackspace/gophercloud/pagination"
9)
10
11type CreateOptsBuilder interface {
12 ToDBCreateMap() (map[string]interface{}, error)
13}
14
15// DatabaseOpts is the struct responsible for configuring a database; often in
16// the context of an instance.
17type CreateOpts struct {
18 // Specifies the name of the database. Optional.
19 Name string
20
21 // Set of symbols and encodings. Optional; the default character set is utf8.
22 CharSet string
23
24 // Set of rules for comparing characters in a character set. Optional; the
25 // default value for collate is utf8_general_ci.
26 Collate string
27}
28
29func (opts CreateOpts) ToMap() (map[string]string, error) {
30 if opts.Name == "" {
31 return nil, fmt.Errorf("Name is a required field")
32 }
33 if len(opts.Name) > 64 {
34 return nil, fmt.Errorf("Name must be less than 64 chars long")
35 }
36
37 db := map[string]string{"name": opts.Name}
38
39 if opts.CharSet != "" {
40 db["character_set"] = opts.CharSet
41 }
42 if opts.Collate != "" {
43 db["collate"] = opts.Collate
44 }
45 return db, nil
46}
47
48type BatchCreateOpts []CreateOpts
49
50func (opts BatchCreateOpts) ToDBCreateMap() (map[string]interface{}, error) {
51 var dbs []map[string]string
52 for _, db := range opts {
53 dbMap, err := db.ToMap()
54 if err != nil {
55 return nil, err
56 }
57 dbs = append(dbs, dbMap)
58 }
59 return map[string]interface{}{"databases": dbs}, nil
60}
61
62func Create(client *gophercloud.ServiceClient, instanceID string, opts CreateOptsBuilder) CreateResult {
63 var res CreateResult
64
65 reqBody, err := opts.ToDBCreateMap()
66 if err != nil {
67 res.Err = err
68 return res
69 }
70
71 resp, err := perigee.Request("POST", baseURL(client, instanceID), perigee.Options{
72 MoreHeaders: client.AuthenticatedHeaders(),
73 ReqBody: &reqBody,
74 Results: &res.Body,
75 OkCodes: []int{202},
76 })
77
78 res.Header = resp.HttpResponse.Header
79 res.Err = err
80
81 return res
82}
83
84func List(client *gophercloud.ServiceClient, instanceID string) pagination.Pager {
85 createPageFn := func(r pagination.PageResult) pagination.Page {
86 return DBPage{pagination.LinkedPageBase{PageResult: r}}
87 }
88
89 return pagination.NewPager(client, baseURL(client, instanceID), createPageFn)
90}
91
92func Delete(client *gophercloud.ServiceClient, instanceID, dbName string) DeleteResult {
93 var res DeleteResult
94
95 resp, err := perigee.Request("DELETE", dbURL(client, instanceID, dbName), perigee.Options{
96 MoreHeaders: client.AuthenticatedHeaders(),
97 Results: &res.Body,
98 OkCodes: []int{202},
99 })
100
101 res.Header = resp.HttpResponse.Header
102 res.Err = err
103
104 return res
105}