CQL.js 15.9 KB
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 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
/* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for 
 * full list of contributors). Published under the Clear BSD license.  
 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

/**
 * @requires OpenLayers/Format/WKT.js
 */

/**
 * Class: OpenLayers.Format.CQL
 * Read CQL strings to get <OpenLayers.Filter> objects.  Write 
 *     <OpenLayers.Filter> objects to get CQL strings. Create a new parser with 
 *     the <OpenLayers.Format.CQL> constructor.
 *
 * Inherits from:
 *  - <OpenLayers.Format>
 */
OpenLayers.Format.CQL = (function() {
    
    var tokens = [
        "PROPERTY", "COMPARISON", "VALUE", "LOGICAL"
    ],

    patterns = {
        PROPERTY: /^[_a-zA-Z]\w*/,
        COMPARISON: /^(=|<>|<=|<|>=|>|LIKE)/i,
        COMMA: /^,/,
        LOGICAL: /^(AND|OR)/i,
        VALUE: /^('\w+'|\d+(\.\d*)?|\.\d+)/,
        LPAREN: /^\(/,
        RPAREN: /^\)/,
        SPATIAL: /^(BBOX|INTERSECTS|DWITHIN|WITHIN|CONTAINS)/i,
        NOT: /^NOT/i,
        BETWEEN: /^BETWEEN/i,
        GEOMETRY: function(text) {
            var type = /^(POINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON|GEOMETRYCOLLECTION)/.exec(text);
            if (type) {
                var len = text.length;
                var idx = text.indexOf("(", type[0].length);
                if (idx > -1) {
                    var depth = 1;
                    while (idx < len && depth > 0) {
                        idx++;
                        switch(text.charAt(idx)) {
                            case '(':
                                depth++;
                                break;
                            case ')':
                                depth--;
                                break;
                            default:
                                // in default case, do nothing
                        }
                    }
                }
                return [text.substr(0, idx+1)];
            }
        },
        END: /^$/
    },

    follows = {
        LPAREN: ['GEOMETRY', 'SPATIAL', 'PROPERTY', 'VALUE', 'LPAREN'],
        RPAREN: ['NOT', 'LOGICAL', 'END', 'RPAREN'],
        PROPERTY: ['COMPARISON', 'BETWEEN', 'COMMA'],
        BETWEEN: ['VALUE'],
        COMPARISON: ['VALUE'],
        COMMA: ['GEOMETRY', 'VALUE', 'PROPERTY'],
        VALUE: ['LOGICAL', 'COMMA', 'RPAREN', 'END'],
        SPATIAL: ['LPAREN'],
        LOGICAL: ['NOT', 'VALUE', 'SPATIAL', 'PROPERTY', 'LPAREN'],
        NOT: ['PROPERTY', 'LPAREN'],
        GEOMETRY: ['COMMA', 'RPAREN']
    },

    operators = {
        '=': OpenLayers.Filter.Comparison.EQUAL_TO,
        '<>': OpenLayers.Filter.Comparison.NOT_EQUAL_TO,
        '<': OpenLayers.Filter.Comparison.LESS_THAN,
        '<=': OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO,
        '>': OpenLayers.Filter.Comparison.GREATER_THAN,
        '>=': OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO,
        'LIKE': OpenLayers.Filter.Comparison.LIKE,
        'BETWEEN': OpenLayers.Filter.Comparison.BETWEEN
    },

    operatorReverse = {},

    logicals = {
        'AND': OpenLayers.Filter.Logical.AND,
        'OR': OpenLayers.Filter.Logical.OR
    },

    logicalReverse = {},

    precedence = {
        'RPAREN': 3,
        'LOGICAL': 2,
        'COMPARISON': 1
    };

    var i;
    for (i in operators) {
        if (operators.hasOwnProperty(i)) {
            operatorReverse[operators[i]] = i;
        }
    }

    for (i in logicals) {
        if (logicals.hasOwnProperty(i)) {
            logicalReverse[logicals[i]] = i;
        }
    }

    function tryToken(text, pattern) {
        if (pattern instanceof RegExp) {
            return pattern.exec(text);
        } else {
            return pattern(text);
        }
    }

    function nextToken(text, tokens) {
        var i, token, len = tokens.length;
        for (i=0; i<len; i++) {
            token = tokens[i];
            var pat = patterns[token];
            var matches = tryToken(text, pat);
            if (matches) {
                var match = matches[0];
                var remainder = text.substr(match.length).replace(/^\s*/, "");
                return {
                    type: token,
                    text: match,
                    remainder: remainder
                };
            }
        }

        var msg = "ERROR: In parsing: [" + text + "], expected one of: ";
        for (i=0; i<len; i++) {
            token = tokens[i];
            msg += "\n    " + token + ": " + patterns[token];
        }

        throw new Error(msg);
    }

    function tokenize(text) {
        var results = [];
        var token, expect = ["NOT", "GEOMETRY", "SPATIAL", "PROPERTY", "LPAREN"];

        do {
            token = nextToken(text, expect);
            text = token.remainder;
            expect = follows[token.type];
            if (token.type != "END" && !expect) {
                throw new Error("No follows list for " + token.type);
            }
            results.push(token);
        } while (token.type != "END");

        return results;
    }

    function buildAst(tokens) {
        var operatorStack = [],
            postfix = [];

        while (tokens.length) {
            var tok = tokens.shift();
            switch (tok.type) {
                case "PROPERTY":
                case "GEOMETRY":
                case "VALUE":
                    postfix.push(tok);
                    break;
                case "COMPARISON":
                case "BETWEEN":
                case "LOGICAL":
                    var p = precedence[tok.type];

                    while (operatorStack.length > 0 &&
                        (precedence[operatorStack[operatorStack.length - 1].type] <= p)
                    ) {
                        postfix.push(operatorStack.pop());
                    }

                    operatorStack.push(tok);
                    break;
                case "SPATIAL":
                case "NOT":
                case "LPAREN":
                    operatorStack.push(tok);
                    break;
                case "RPAREN":
                    while (operatorStack.length > 0 &&
                        (operatorStack[operatorStack.length - 1].type != "LPAREN")
                    ) {
                        postfix.push(operatorStack.pop());
                    }
                    operatorStack.pop(); // toss out the LPAREN

                    if (operatorStack.length > 0 &&
                        operatorStack[operatorStack.length-1].type == "SPATIAL") {
                        postfix.push(operatorStack.pop());
                    }
                case "COMMA":
                case "END":
                    break;
                default:
                    throw new Error("Unknown token type " + tok.type);
            }
        }

        while (operatorStack.length > 0) {
            postfix.push(operatorStack.pop());
        }

        function buildTree() {
            var tok = postfix.pop();
            switch (tok.type) {
                case "LOGICAL":
                    var rhs = buildTree(),
                        lhs = buildTree();
                    return new OpenLayers.Filter.Logical({
                        filters: [lhs, rhs],
                        type: logicals[tok.text.toUpperCase()]
                    });
                case "NOT":
                    var operand = buildTree();
                    return new OpenLayers.Filter.Logical({
                        filters: [operand],
                        type: OpenLayers.Filter.Logical.NOT
                    });
                case "BETWEEN":
                    var min, max, property;
                    postfix.pop(); // unneeded AND token here
                    max = buildTree();
                    min = buildTree();
                    property = buildTree();
                    return new OpenLayers.Filter.Comparison({
                        property: property,
                        lowerBoundary: min,
                        upperBoundary: max,
                        type: OpenLayers.Filter.Comparison.BETWEEN
                    });
                case "COMPARISON":
                    var value = buildTree(),
                        property = buildTree();
                    return new OpenLayers.Filter.Comparison({
                        property: property,
                        value: value,
                        type: operators[tok.text.toUpperCase()]
                    });
                case "VALUE":
                    if ((/^'.*'$/).test(tok.text)) {
                        return tok.text.substr(1, tok.text.length - 2);
                    } else {
                        return Number(tok.text);
                    }
                case "SPATIAL":
                    switch(tok.text.toUpperCase()) {
                        case "BBOX":
                            var maxy = buildTree(),
                                maxx = buildTree(),
                                miny = buildTree(),
                                minx = buildTree(),
                                prop = buildTree();

                            return new OpenLayers.Filter.Spatial({
                                type: OpenLayers.Filter.Spatial.BBOX,
                                property: prop,
                                value: OpenLayers.Bounds.fromArray(
                                    [minx, miny, maxx, maxy]
                                )
                            });
                        case "INTERSECTS":
                            var value = buildTree(),
                                property = buildTree();
                            return new OpenLayers.Filter.Spatial({
                                type: OpenLayers.Filter.Spatial.INTERSECTS,
                                property: property,
                                value: value
                            });
                        case "WITHIN":
                            var value = buildTree(),
                                property = buildTree();
                            return new OpenLayers.Filter.Spatial({
                                type: OpenLayers.Filter.Spatial.WITHIN,
                                property: property,
                                value: value
                            });
                        case "CONTAINS":
                            var value = buildTree(),
                                property = buildTree();
                            return new OpenLayers.Filter.Spatial({
                                type: OpenLayers.Filter.Spatial.CONTAINS,
                                property: property,
                                value: value
                            });
                        case "DWITHIN":
                            var distance = buildTree(),
                                value = buildTree(),
                                property = buildTree();
                            return new OpenLayers.Filter.Spatial({
                                type: OpenLayers.Filter.Spatial.DWITHIN,
                                value: value,
                                property: property,
                                distance: Number(distance)
                            });
                    }
                case "GEOMETRY":
                    return OpenLayers.Geometry.fromWKT(tok.text);
                default:
                    return tok.text;
            }
        }

        var result = buildTree();
        if (postfix.length > 0) {
            var msg = "Remaining tokens after building AST: \n";
            for (var i = postfix.length - 1; i >= 0; i--) {
                msg += postfix[i].type + ": " + postfix[i].text + "\n";
            }
            throw new Error(msg);
        }

        return result;
    }

    return OpenLayers.Class(OpenLayers.Format, {
        /**
         * APIMethod: read
         * Generate a filter from a CQL string.

         * Parameters:
         * text - {String} The CQL text.
         *
         * Returns:
         * {<OpenLayers.Filter>} A filter based on the CQL text.
         */
        read: function(text) { 
            var result = buildAst(tokenize(text));
            if (this.keepData) {
                this.data = result;
            };
            return result;
        },

        /**
         * APIMethod: write
         * Convert a filter into a CQL string.

         * Parameters:
         * filter - {<OpenLayers.Filter>} The filter.
         *
         * Returns:
         * {String} A CQL string based on the filter.
         */
        write: function(filter) {
            if (filter instanceof OpenLayers.Geometry) {
                return filter.toString();
            }
            switch (filter.CLASS_NAME) {
                case "OpenLayers.Filter.Spatial":
                    switch(filter.type) {
                        case OpenLayers.Filter.Spatial.BBOX:
                            return "BBOX(" +
                                filter.property + "," +
                                filter.value.toBBOX() +
                                ")";
                        case OpenLayers.Filter.Spatial.DWITHIN:
                            return "DWITHIN(" +
                                filter.property + ", " +
                                this.write(filter.value) + ", " +
                                filter.distance + ")";
                        case OpenLayers.Filter.Spatial.WITHIN:
                            return "WITHIN(" +
                                filter.property + ", " +
                                this.write(filter.value) + ")";
                        case OpenLayers.Filter.Spatial.INTERSECTS:
                            return "INTERSECTS(" +
                                filter.property + ", " +
                                this.write(filter.value) + ")";
                        case OpenLayers.Filter.Spatial.CONTAINS:
                            return "CONTAINS(" +
                                filter.property + ", " +
                                this.write(filter.value) + ")";
                        default:
                            throw new Error("Unknown spatial filter type: " + filter.type);
                    }
                case "OpenLayers.Filter.Logical":
                    if (filter.type == OpenLayers.Filter.Logical.NOT) {
                        // TODO: deal with precedence of logical operators to 
                        // avoid extra parentheses (not urgent)
                        return "NOT (" + this.write(filter.filters[0]) + ")";
                    } else {
                        var res = "(";
                        var first = true;
                        for (var i = 0; i < filter.filters.length; i++) {
                            if (first) {
                                first = false;
                            } else {
                                res += ") " + logicalReverse[filter.type] + " (";
                            }
                            res += this.write(filter.filters[i]);
                        }
                        return res + ")";
                    }
                case "OpenLayers.Filter.Comparison":
                    if (filter.type == OpenLayers.Filter.Comparison.BETWEEN) {
                        return filter.property + " BETWEEN " + 
                            this.write(filter.lowerBoundary) + " AND " + 
                            this.write(filter.upperBoundary);
                    } else {
                        
                        return filter.property +
                            " " + operatorReverse[filter.type] + " " + 
                            this.write(filter.value);
                    }
                case undefined:
                    if (typeof filter === "string") {
                        return "'" + filter + "'";
                    } else if (typeof filter === "number") {
                        return String(filter);
                    }
                default:
                    throw new Error("Can't encode: " + filter.CLASS_NAME + " " + filter);
            }
        },

        CLASS_NAME: "OpenLayers.Format.CQL"

    });
})();