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