|
| 1 | + |
| 2 | + |
| 3 | +def parse_mysql_enum(enum_definition): |
| 4 | + """ |
| 5 | + Accepts a MySQL ENUM definition string (case–insensitive), |
| 6 | + for example: |
| 7 | + enum('point','qwe','def') |
| 8 | + ENUM("asd", 'qwe', "def") |
| 9 | + enum(`point`,`qwe`,`def`) |
| 10 | + and returns a list of strings like: |
| 11 | + ['point', 'qwe', 'def'] |
| 12 | +
|
| 13 | + Note: |
| 14 | + - For single- and double–quoted values, backslash escapes are handled. |
| 15 | + - For backtick–quoted values, only doubling (``) is recognized as escaping. |
| 16 | + """ |
| 17 | + # First, trim any whitespace. |
| 18 | + s = enum_definition.strip() |
| 19 | + |
| 20 | + # Check that the string begins with "enum" (case–insensitive) |
| 21 | + if not s[:4].lower() == "enum": |
| 22 | + raise ValueError("String does not start with 'enum'") |
| 23 | + |
| 24 | + # Find the first opening parenthesis. |
| 25 | + pos = s.find('(') |
| 26 | + if pos == -1: |
| 27 | + raise ValueError("Missing '(' in the enum definition") |
| 28 | + |
| 29 | + # Extract the text inside the outer parenthesis. |
| 30 | + # We use a helper to extract the contents taking into account |
| 31 | + # that quotes (of any supported type) and escapes may appear. |
| 32 | + inner_content, next_index = _extract_parenthesized_content(s, pos) |
| 33 | + # Optionally, you can check that only whitespace follows next_index. |
| 34 | + |
| 35 | + # Now parse out the comma–separated string literals. |
| 36 | + return _parse_enum_values(inner_content) |
| 37 | + |
| 38 | + |
| 39 | +def _extract_parenthesized_content(s, start_index): |
| 40 | + """ |
| 41 | + Given a string s and the index of a '(' in it, |
| 42 | + return a tuple (content, pos) where content is the substring |
| 43 | + inside the outer matching parentheses and pos is the index |
| 44 | + immediately after the matching closing ')'. |
| 45 | +
|
| 46 | + This function takes special care to ignore any parentheses |
| 47 | + that occur inside quotes (a quoted literal is any part enclosed by |
| 48 | + ', " or `) and also to skip over escape sequences in single/double quotes. |
| 49 | + (Backticks do not process backslash escapes.) |
| 50 | + """ |
| 51 | + if s[start_index] != '(': |
| 52 | + raise ValueError("Expected '(' at position {}".format(start_index)) |
| 53 | + depth = 1 |
| 54 | + i = start_index + 1 |
| 55 | + content_start = i |
| 56 | + in_quote = None # will be set to a quoting character when inside a quoted literal |
| 57 | + |
| 58 | + # Allow these quote characters. |
| 59 | + allowed_quotes = ("'", '"', '`') |
| 60 | + |
| 61 | + while i < len(s): |
| 62 | + c = s[i] |
| 63 | + if in_quote: |
| 64 | + # Inside a quoted literal. |
| 65 | + if in_quote in ("'", '"'): |
| 66 | + if c == '\\': |
| 67 | + # Skip the escape character and the next character. |
| 68 | + i += 2 |
| 69 | + continue |
| 70 | + # Whether we are in a backtick or one of the other quotes, |
| 71 | + # check for the closing quote. |
| 72 | + if c == in_quote: |
| 73 | + # Check for a doubled quote. |
| 74 | + if i + 1 < len(s) and s[i + 1] == in_quote: |
| 75 | + i += 2 |
| 76 | + continue |
| 77 | + else: |
| 78 | + in_quote = None |
| 79 | + i += 1 |
| 80 | + continue |
| 81 | + else: |
| 82 | + i += 1 |
| 83 | + continue |
| 84 | + else: |
| 85 | + # Not inside a quoted literal. |
| 86 | + if c in allowed_quotes: |
| 87 | + in_quote = c |
| 88 | + i += 1 |
| 89 | + continue |
| 90 | + elif c == '(': |
| 91 | + depth += 1 |
| 92 | + i += 1 |
| 93 | + continue |
| 94 | + elif c == ')': |
| 95 | + depth -= 1 |
| 96 | + i += 1 |
| 97 | + if depth == 0: |
| 98 | + # Return the substring inside (excluding the outer parentheses) |
| 99 | + return s[content_start:i - 1], i |
| 100 | + continue |
| 101 | + else: |
| 102 | + i += 1 |
| 103 | + |
| 104 | + raise ValueError("Unbalanced parentheses in enum definition") |
| 105 | + |
| 106 | + |
| 107 | +def _parse_enum_values(content): |
| 108 | + """ |
| 109 | + Given the inner text from an ENUM declaration—for example: |
| 110 | + "'point', 'qwe', 'def'" |
| 111 | + parse and return a list of the string values as MySQL would see them. |
| 112 | +
|
| 113 | + This function handles: |
| 114 | + - For single- and double–quoted strings: backslash escapes and doubled quotes. |
| 115 | + - For backtick–quoted identifiers: only doubled backticks are recognized. |
| 116 | + """ |
| 117 | + values = [] |
| 118 | + i = 0 |
| 119 | + allowed_quotes = ("'", '"', '`') |
| 120 | + while i < len(content): |
| 121 | + # Skip any whitespace. |
| 122 | + while i < len(content) and content[i].isspace(): |
| 123 | + i += 1 |
| 124 | + if i >= len(content): |
| 125 | + break |
| 126 | + # The next non–whitespace character must be one of the allowed quotes. |
| 127 | + if content[i] not in allowed_quotes: |
| 128 | + raise ValueError("Expected starting quote for enum value at position {} in {!r}".format(i, content)) |
| 129 | + quote = content[i] |
| 130 | + i += 1 # skip the opening quote |
| 131 | + |
| 132 | + literal_chars = [] |
| 133 | + while i < len(content): |
| 134 | + c = content[i] |
| 135 | + # For single- and double–quotes, process backslash escapes. |
| 136 | + if quote in ("'", '"') and c == '\\': |
| 137 | + if i + 1 < len(content): |
| 138 | + next_char = content[i + 1] |
| 139 | + # Mapping for common escapes. (For the quote character, map it to itself.) |
| 140 | + escapes = { |
| 141 | + '0': '\0', |
| 142 | + 'b': '\b', |
| 143 | + 'n': '\n', |
| 144 | + 'r': '\r', |
| 145 | + 't': '\t', |
| 146 | + 'Z': '\x1a', |
| 147 | + '\\': '\\', |
| 148 | + quote: quote |
| 149 | + } |
| 150 | + literal_chars.append(escapes.get(next_char, next_char)) |
| 151 | + i += 2 |
| 152 | + continue |
| 153 | + else: |
| 154 | + # Trailing backslash – treat it as literal. |
| 155 | + literal_chars.append('\\') |
| 156 | + i += 1 |
| 157 | + continue |
| 158 | + elif c == quote: |
| 159 | + # Check for a doubled quote (works for all three quoting styles). |
| 160 | + if i + 1 < len(content) and content[i + 1] == quote: |
| 161 | + literal_chars.append(quote) |
| 162 | + i += 2 |
| 163 | + continue |
| 164 | + else: |
| 165 | + i += 1 # skip the closing quote |
| 166 | + break # end of this literal |
| 167 | + else: |
| 168 | + # For backticks, we do not treat backslashes specially. |
| 169 | + literal_chars.append(c) |
| 170 | + i += 1 |
| 171 | + # Finished reading one literal; join the characters. |
| 172 | + value = ''.join(literal_chars) |
| 173 | + values.append(value) |
| 174 | + |
| 175 | + # Skip whitespace after the literal. |
| 176 | + while i < len(content) and content[i].isspace(): |
| 177 | + i += 1 |
| 178 | + # If there’s a comma, skip it; otherwise, we must be at the end. |
| 179 | + if i < len(content): |
| 180 | + if content[i] == ',': |
| 181 | + i += 1 |
| 182 | + else: |
| 183 | + raise ValueError("Expected comma between enum values at position {} in {!r}" |
| 184 | + .format(i, content)) |
| 185 | + return values |
| 186 | + |
| 187 | + |
| 188 | +# --- For testing purposes --- |
| 189 | +if __name__ == '__main__': |
| 190 | + tests = [ |
| 191 | + "enum('point','qwe','def')", |
| 192 | + "ENUM('asd', 'qwe', 'def')", |
| 193 | + 'enum("first", \'second\', "Don""t stop")', |
| 194 | + "enum('a\\'b','c\\\\d','Hello\\nWorld')", |
| 195 | + # Now with backticks: |
| 196 | + "enum(`point`,`qwe`,`def`)", |
| 197 | + "enum('point',`qwe`,'def')", |
| 198 | + "enum(`first`, `Don``t`, `third`)", |
| 199 | + ] |
| 200 | + |
| 201 | + for t in tests: |
| 202 | + try: |
| 203 | + result = parse_mysql_enum(t) |
| 204 | + print("Input: {}\nParsed: {}\n".format(t, result)) |
| 205 | + except Exception as e: |
| 206 | + print("Error parsing {}: {}\n".format(t, e)) |
0 commit comments