parser.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. """
  2. jupyter-mysql-kernel
  3. author:rabin
  4. """
  5. class MysqlParser(object):
  6. def __init__(self, response, commands=False):
  7. self.response = response
  8. self.result = []
  9. self.is_array = False
  10. self.is_error = False
  11. if not commands:
  12. self.parse_response()
  13. else:
  14. self.parse_commands()
  15. def parse_commands(self):
  16. # get each section of the command response
  17. sections = self.response.split('*6\r\n')
  18. for section in sections:
  19. parts = section.split('\r\n')
  20. # only the second one is the command name
  21. # no need to parse for now
  22. if parts[1] is not None and parts[1].__len__() > 0:
  23. self.result.append(parts[1])
  24. def parse_response(self):
  25. # get each line of the response
  26. parts = self.response.split('\r\n')
  27. if parts[0].startswith('*'):
  28. self.is_array = True
  29. for part in parts:
  30. if part != '':
  31. value = self.parse_part(part)
  32. if value is not None:
  33. self.result.append(value)
  34. def parse_part(self, part):
  35. if part[0] == '*':
  36. # array count
  37. return None
  38. elif part[0] in ['-', '+', ':']:
  39. if part[0] == '-':
  40. self.is_error = True
  41. #error or string or integer
  42. return part[1:]
  43. elif part[0] == '+':
  44. return part[1:]
  45. elif part[0] == ':':
  46. return int(part[1:])
  47. elif part[0] == '$':
  48. if part[1:] == '-1':
  49. # handle nil
  50. return 'nil'
  51. else:
  52. # ignore the byte count
  53. return None
  54. else:
  55. # values returned after the type specifier
  56. return part
  57. def html(self):
  58. out = None
  59. res = self.get_result()
  60. if self.is_error:
  61. out = "<p style='color:red'>" + res + '</p>'
  62. else:
  63. out = res
  64. return out
  65. def text(self):
  66. return self.get_result()
  67. def get_result(self):
  68. if self.result.__len__() > 1:
  69. out = []
  70. for x in self.result:
  71. if isinstance(x, int):
  72. out.append(str(x))
  73. else:
  74. out.append(x)
  75. return out
  76. elif self.result.__len__() > 0:
  77. if type(self.result[0] == int):
  78. return str(self.result[0])
  79. else:
  80. return self.result[0]
  81. else:
  82. self.is_error = True
  83. return 'Error executing command. There was no result.'