summaryrefslogtreecommitdiff
path: root/sql/my_json_writer.cc
blob: 206597da59ec0e9e7dfcbef2d1bd4a95f573d137 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/* Todo: SkySQL copyrights */

#include <my_global.h>
#include "sql_priv.h"
#include "sql_string.h"

#include "my_json_writer.h"

void Json_writer::append_indent()
{
  if (!document_start)
    output.append('\n');
  for (int i=0; i< indent_level; i++)
    output.append(' ');
}

void Json_writer::start_object()
{
  if (!element_started)
    start_element();

  output.append("{");
  indent_level+=INDENT_SIZE;
  first_child=true;
  element_started= false;
  document_start= false;
}

void Json_writer::start_array()
{
  if (!element_started)
    start_element();

  output.append("[");
  indent_level+=INDENT_SIZE;
  first_child=true;
  element_started= false;
  document_start= false;
}


void Json_writer::end_object()
{
  indent_level-=INDENT_SIZE;
  if (!first_child)
    append_indent();
  output.append("}");
}


void Json_writer::end_array()
{
  indent_level-=INDENT_SIZE;
  if (!first_child)
    append_indent();
  output.append("]");
}


Json_writer& Json_writer::add_member(const char *name)
{
  // assert that we are in an object
  DBUG_ASSERT(!element_started);
  start_element();

  output.append('"');
  output.append(name);
  output.append("\": ");
  return *this;
}


void Json_writer::start_element()
{
  element_started= true;

  if (first_child)
    first_child= false;
  else
    output.append(',');

  append_indent();
}

void Json_writer::add_ll(longlong val)
{
  if (!element_started)
    start_element();

  char buf[64];
  my_snprintf(buf, sizeof(buf), "%ld", val);
  output.append(buf);
  element_started= false;
}


void Json_writer::add_double(double val)
{
  if (!element_started)
    start_element();

  char buf[64];
  my_snprintf(buf, sizeof(buf), "%lf", val);
  output.append(buf);
  element_started= false;
}


void Json_writer::add_str(const char *str)
{
  if (!element_started)
    start_element();

  output.append('"');
  output.append(str);
  output.append('"');
  element_started= false;
}

void Json_writer::add_bool(bool val)
{
  add_str(val? "true" : "false");
}

void Json_writer::add_str(const String &str)
{
  add_str(str.ptr());
}