paulb@0 | 1 | #!/usr/bin/env python |
paulb@0 | 2 | |
paulb@1 | 3 | """ |
paulb@1 | 4 | A regular expression implementation of SQL statement tokenisation. |
paulb@1 | 5 | |
paulb@1 | 6 | Copyright (C) 2007 Paul Boddie <paul@boddie.org.uk> |
paulb@1 | 7 | |
paulb@1 | 8 | This library is free software; you can redistribute it and/or |
paulb@1 | 9 | modify it under the terms of the GNU Lesser General Public |
paulb@1 | 10 | License as published by the Free Software Foundation; either |
paulb@1 | 11 | version 2.1 of the License, or (at your option) any later version. |
paulb@1 | 12 | |
paulb@1 | 13 | This library is distributed in the hope that it will be useful, |
paulb@1 | 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
paulb@1 | 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
paulb@1 | 16 | Lesser General Public License for more details. |
paulb@1 | 17 | |
paulb@1 | 18 | You should have received a copy of the GNU Lesser General Public |
paulb@1 | 19 | License along with this library; if not, write to the Free Software |
paulb@1 | 20 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA |
paulb@1 | 21 | """ |
paulb@1 | 22 | |
paulb@4 | 23 | import sqlliterals.common |
paulb@0 | 24 | import re |
paulb@1 | 25 | |
paulb@1 | 26 | region_expr = re.compile("(?P<non_literal>[^']+)|(?P<literal>'(?:[^']|(?:''))*')") |
paulb@0 | 27 | |
paulb@0 | 28 | def parseString(s): |
paulb@1 | 29 | |
paulb@1 | 30 | """ |
paulb@1 | 31 | Parse the string 's' and return a list of regions, with the first element |
paulb@1 | 32 | being a non-literal region, the next element being a literal region, and |
paulb@1 | 33 | with subsequent elements repeating this pattern. Note that the first region |
paulb@1 | 34 | may be an empty string. |
paulb@1 | 35 | """ |
paulb@1 | 36 | |
paulb@0 | 37 | regions = [] |
paulb@0 | 38 | first = 1 |
paulb@1 | 39 | for match in region_expr.finditer(s): |
paulb@0 | 40 | non_literal, literal = match.groups() |
paulb@0 | 41 | if first and literal: |
paulb@0 | 42 | regions.append("") |
paulb@0 | 43 | if non_literal: |
paulb@0 | 44 | regions.append(non_literal) |
paulb@0 | 45 | elif literal: |
paulb@0 | 46 | regions.append(literal) |
paulb@0 | 47 | first = 0 |
paulb@0 | 48 | |
paulb@0 | 49 | return regions |
paulb@0 | 50 | |
paulb@4 | 51 | # NOTE: Duplicated across implementations. |
paulb@4 | 52 | |
paulb@4 | 53 | def replace(fromstyle, tostyle, s): |
paulb@4 | 54 | |
paulb@4 | 55 | """ |
paulb@4 | 56 | Return a new string, where the paramstyle 'fromstyle' is |
paulb@4 | 57 | replaced with 'tostyle' in the appropriate regions of 's'. |
paulb@4 | 58 | """ |
paulb@4 | 59 | |
paulb@4 | 60 | regions = parseString(s) |
paulb@4 | 61 | return "".join(sqlliterals.common.replace(fromstyle, tostyle, regions)) |
paulb@4 | 62 | |
paulb@0 | 63 | # vim: tabstop=4 expandtab shiftwidth=4 |