├── .editorconfig ├── .github ├── FUNDING.yml └── workflows │ └── CI.yml ├── .gitignore ├── .travis.yml ├── Cargo.lock ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-BSD3 ├── README.md ├── benches └── logq_benchmark.rs ├── data ├── AWSALB.log ├── AWSELB.log ├── S3.log ├── Squid.log └── structured.log ├── rustfmt.toml ├── scripts └── elb_log_generator.rb ├── src ├── app.rs ├── cli.yml ├── common │ ├── mod.rs │ └── types.rs ├── execution │ ├── datasource.rs │ ├── mod.rs │ ├── stream.rs │ └── types.rs ├── logical │ ├── mod.rs │ ├── parser.rs │ └── types.rs ├── main.rs └── syntax │ ├── ast.rs │ ├── mod.rs │ └── parser.rs └── tests ├── exists-queries.txt ├── select.txt └── tpc-w-queries.txt /.editorconfig: -------------------------------------------------------------------------------- 1 | # editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | charset = utf-8 7 | end_of_line = lf 8 | indent_size = 4 9 | indent_style = space 10 | insert_final_newline = true 11 | trim_trailing_whitespace = true 12 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: MnO2 2 | -------------------------------------------------------------------------------- /.github/workflows/CI.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | 3 | name: CI 4 | 5 | jobs: 6 | check: 7 | name: Check 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | - uses: actions-rs/toolchain@v1 12 | with: 13 | profile: minimal 14 | toolchain: stable 15 | override: true 16 | - uses: actions-rs/cargo@v1 17 | with: 18 | command: check 19 | args: --all-features 20 | 21 | test: 22 | name: Test Suite 23 | runs-on: ${{ matrix.os }} 24 | strategy: 25 | matrix: 26 | os: [ubuntu-latest, macos-latest, windows-latest] 27 | steps: 28 | - uses: actions/checkout@v2 29 | - uses: actions-rs/toolchain@v1 30 | with: 31 | profile: minimal 32 | toolchain: stable 33 | override: true 34 | - name: Check build with default features 35 | uses: actions-rs/cargo@v1 36 | with: 37 | command: build 38 | - name: Test 39 | uses: actions-rs/cargo@v1 40 | with: 41 | command: test 42 | args: --all-features --all --benches 43 | 44 | codecov: 45 | name: Code Coverage 46 | runs-on: ubuntu-latest 47 | steps: 48 | - uses: actions/checkout@v2 49 | - uses: actions-rs/toolchain@v1 50 | with: 51 | profile: minimal 52 | toolchain: stable 53 | override: true 54 | - name: Run cargo-tarpaulin 55 | uses: actions-rs/tarpaulin@v0.1 56 | with: 57 | args: '--all-features' 58 | - name: Upload to codecov.io 59 | uses: codecov/codecov-action@v1 60 | with: 61 | token: ${{secrets.CODECOV_TOKEN}} 62 | - name: Archive code coverage results 63 | uses: actions/upload-artifact@v1 64 | with: 65 | name: code-coverage-report 66 | path: cobertura.xml 67 | 68 | fmt: 69 | name: Rustfmt 70 | runs-on: ubuntu-latest 71 | steps: 72 | - uses: actions/checkout@v2 73 | - uses: actions-rs/toolchain@v1 74 | with: 75 | profile: minimal 76 | toolchain: stable 77 | override: true 78 | - run: rustup component add rustfmt 79 | - uses: actions-rs/cargo@v1 80 | with: 81 | command: fmt 82 | args: --all -- --check 83 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | .idea 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | dist: trusty 3 | language: rust 4 | addons: 5 | apt: 6 | packages: 7 | - libssl-dev 8 | - pkg-config 9 | - zlib1g-dev 10 | rust: 11 | - stable 12 | 13 | before_script: 14 | - rustup component add rustfmt 15 | - | 16 | if [[ "$TRAVIS_OS_NAME" == "linux" && "$TRAVIS_RUST_VERSION" == "stable" ]]; then 17 | rustup component add clippy 18 | fi 19 | 20 | script: 21 | - cargo fmt --all -- --check 22 | - cargo build --verbose 23 | - cargo test 24 | 25 | after_success: 26 | - | 27 | if [[ "$TRAVIS_OS_NAME" == "linux" && "$TRAVIS_RUST_VERSION" == "stable" ]]; then 28 | bash <(curl https://raw.githubusercontent.com/xd009642/tarpaulin/master/travis-install.sh) 29 | cargo tarpaulin --out Xml 30 | bash <(curl -s https://codecov.io/bash) 31 | fi 32 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "addr2line" 7 | version = "0.14.0" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "7c0929d69e78dd9bf5408269919fcbcaeb2e35e5d43e5815517cdc6a8e11a423" 10 | dependencies = [ 11 | "gimli", 12 | ] 13 | 14 | [[package]] 15 | name = "adler" 16 | version = "0.2.3" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | checksum = "ee2a4ec343196209d6594e19543ae87a39f96d5534d7174822a3ad825dd6ed7e" 19 | 20 | [[package]] 21 | name = "ahash" 22 | version = "0.7.4" 23 | source = "registry+https://github.com/rust-lang/crates.io-index" 24 | checksum = "43bb833f0bf979d8475d38fbf09ed3b8a55e1885fe93ad3f93239fc6a4f17b98" 25 | dependencies = [ 26 | "getrandom 0.2.0", 27 | "once_cell", 28 | "version_check", 29 | ] 30 | 31 | [[package]] 32 | name = "aho-corasick" 33 | version = "0.7.18" 34 | source = "registry+https://github.com/rust-lang/crates.io-index" 35 | checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" 36 | dependencies = [ 37 | "memchr", 38 | ] 39 | 40 | [[package]] 41 | name = "ansi_term" 42 | version = "0.11.0" 43 | source = "registry+https://github.com/rust-lang/crates.io-index" 44 | checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" 45 | dependencies = [ 46 | "winapi", 47 | ] 48 | 49 | [[package]] 50 | name = "anyhow" 51 | version = "1.0.38" 52 | source = "registry+https://github.com/rust-lang/crates.io-index" 53 | checksum = "afddf7f520a80dbf76e6f50a35bca42a2331ef227a28b3b6dc5c2e2338d114b1" 54 | 55 | [[package]] 56 | name = "arrayref" 57 | version = "0.3.6" 58 | source = "registry+https://github.com/rust-lang/crates.io-index" 59 | checksum = "a4c527152e37cf757a3f78aae5a06fbeefdb07ccc535c980a3208ee3060dd544" 60 | 61 | [[package]] 62 | name = "arrayvec" 63 | version = "0.5.2" 64 | source = "registry+https://github.com/rust-lang/crates.io-index" 65 | checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" 66 | 67 | [[package]] 68 | name = "atty" 69 | version = "0.2.14" 70 | source = "registry+https://github.com/rust-lang/crates.io-index" 71 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 72 | dependencies = [ 73 | "hermit-abi", 74 | "libc", 75 | "winapi", 76 | ] 77 | 78 | [[package]] 79 | name = "autocfg" 80 | version = "0.1.7" 81 | source = "registry+https://github.com/rust-lang/crates.io-index" 82 | checksum = "1d49d90015b3c36167a20fe2810c5cd875ad504b39cff3d4eae7977e6b7c1cb2" 83 | 84 | [[package]] 85 | name = "autocfg" 86 | version = "1.0.1" 87 | source = "registry+https://github.com/rust-lang/crates.io-index" 88 | checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" 89 | 90 | [[package]] 91 | name = "backtrace" 92 | version = "0.3.55" 93 | source = "registry+https://github.com/rust-lang/crates.io-index" 94 | checksum = "ef5140344c85b01f9bbb4d4b7288a8aa4b3287ccef913a14bcc78a1063623598" 95 | dependencies = [ 96 | "addr2line", 97 | "cfg-if 1.0.0", 98 | "libc", 99 | "miniz_oxide", 100 | "object", 101 | "rustc-demangle", 102 | ] 103 | 104 | [[package]] 105 | name = "base64" 106 | version = "0.13.0" 107 | source = "registry+https://github.com/rust-lang/crates.io-index" 108 | checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" 109 | 110 | [[package]] 111 | name = "bitflags" 112 | version = "1.2.1" 113 | source = "registry+https://github.com/rust-lang/crates.io-index" 114 | checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" 115 | 116 | [[package]] 117 | name = "blake2b_simd" 118 | version = "0.5.11" 119 | source = "registry+https://github.com/rust-lang/crates.io-index" 120 | checksum = "afa748e348ad3be8263be728124b24a24f268266f6f5d58af9d75f6a40b5c587" 121 | dependencies = [ 122 | "arrayref", 123 | "arrayvec", 124 | "constant_time_eq", 125 | ] 126 | 127 | [[package]] 128 | name = "bstr" 129 | version = "0.2.14" 130 | source = "registry+https://github.com/rust-lang/crates.io-index" 131 | checksum = "473fc6b38233f9af7baa94fb5852dca389e3d95b8e21c8e3719301462c5d9faf" 132 | dependencies = [ 133 | "lazy_static", 134 | "memchr", 135 | "regex-automata", 136 | "serde", 137 | ] 138 | 139 | [[package]] 140 | name = "bumpalo" 141 | version = "3.4.0" 142 | source = "registry+https://github.com/rust-lang/crates.io-index" 143 | checksum = "2e8c087f005730276d1096a652e92a8bacee2e2472bcc9715a74d2bec38b5820" 144 | 145 | [[package]] 146 | name = "bytecount" 147 | version = "0.5.1" 148 | source = "registry+https://github.com/rust-lang/crates.io-index" 149 | checksum = "be0fdd54b507df8f22012890aadd099979befdba27713c767993f8380112ca7c" 150 | 151 | [[package]] 152 | name = "byteorder" 153 | version = "1.3.4" 154 | source = "registry+https://github.com/rust-lang/crates.io-index" 155 | checksum = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de" 156 | 157 | [[package]] 158 | name = "cast" 159 | version = "0.2.3" 160 | source = "registry+https://github.com/rust-lang/crates.io-index" 161 | checksum = "4b9434b9a5aa1450faa3f9cb14ea0e8c53bb5d2b3c1bfd1ab4fc03e9f33fbfb0" 162 | dependencies = [ 163 | "rustc_version", 164 | ] 165 | 166 | [[package]] 167 | name = "cfg-if" 168 | version = "0.1.10" 169 | source = "registry+https://github.com/rust-lang/crates.io-index" 170 | checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" 171 | 172 | [[package]] 173 | name = "cfg-if" 174 | version = "1.0.0" 175 | source = "registry+https://github.com/rust-lang/crates.io-index" 176 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 177 | 178 | [[package]] 179 | name = "chrono" 180 | version = "0.4.19" 181 | source = "registry+https://github.com/rust-lang/crates.io-index" 182 | checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73" 183 | dependencies = [ 184 | "libc", 185 | "num-integer", 186 | "num-traits", 187 | "time", 188 | "winapi", 189 | ] 190 | 191 | [[package]] 192 | name = "clap" 193 | version = "2.33.3" 194 | source = "registry+https://github.com/rust-lang/crates.io-index" 195 | checksum = "37e58ac78573c40708d45522f0d80fa2f01cc4f9b4e2bf749807255454312002" 196 | dependencies = [ 197 | "ansi_term", 198 | "atty", 199 | "bitflags", 200 | "strsim", 201 | "textwrap", 202 | "unicode-width", 203 | "vec_map", 204 | "yaml-rust", 205 | ] 206 | 207 | [[package]] 208 | name = "cloudabi" 209 | version = "0.0.3" 210 | source = "registry+https://github.com/rust-lang/crates.io-index" 211 | checksum = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" 212 | dependencies = [ 213 | "bitflags", 214 | ] 215 | 216 | [[package]] 217 | name = "const_fn" 218 | version = "0.4.4" 219 | source = "registry+https://github.com/rust-lang/crates.io-index" 220 | checksum = "cd51eab21ab4fd6a3bf889e2d0958c0a6e3a61ad04260325e919e652a2a62826" 221 | 222 | [[package]] 223 | name = "constant_time_eq" 224 | version = "0.1.5" 225 | source = "registry+https://github.com/rust-lang/crates.io-index" 226 | checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" 227 | 228 | [[package]] 229 | name = "criterion" 230 | version = "0.3.3" 231 | source = "registry+https://github.com/rust-lang/crates.io-index" 232 | checksum = "70daa7ceec6cf143990669a04c7df13391d55fb27bd4079d252fca774ba244d8" 233 | dependencies = [ 234 | "atty", 235 | "cast", 236 | "clap", 237 | "criterion-plot", 238 | "csv", 239 | "itertools", 240 | "lazy_static", 241 | "num-traits", 242 | "oorandom", 243 | "plotters", 244 | "rayon", 245 | "regex", 246 | "serde", 247 | "serde_cbor", 248 | "serde_derive", 249 | "serde_json", 250 | "tinytemplate", 251 | "walkdir", 252 | ] 253 | 254 | [[package]] 255 | name = "criterion-plot" 256 | version = "0.4.3" 257 | source = "registry+https://github.com/rust-lang/crates.io-index" 258 | checksum = "e022feadec601fba1649cfa83586381a4ad31c6bf3a9ab7d408118b05dd9889d" 259 | dependencies = [ 260 | "cast", 261 | "itertools", 262 | ] 263 | 264 | [[package]] 265 | name = "crossbeam-channel" 266 | version = "0.5.0" 267 | source = "registry+https://github.com/rust-lang/crates.io-index" 268 | checksum = "dca26ee1f8d361640700bde38b2c37d8c22b3ce2d360e1fc1c74ea4b0aa7d775" 269 | dependencies = [ 270 | "cfg-if 1.0.0", 271 | "crossbeam-utils", 272 | ] 273 | 274 | [[package]] 275 | name = "crossbeam-deque" 276 | version = "0.8.0" 277 | source = "registry+https://github.com/rust-lang/crates.io-index" 278 | checksum = "94af6efb46fef72616855b036a624cf27ba656ffc9be1b9a3c931cfc7749a9a9" 279 | dependencies = [ 280 | "cfg-if 1.0.0", 281 | "crossbeam-epoch", 282 | "crossbeam-utils", 283 | ] 284 | 285 | [[package]] 286 | name = "crossbeam-epoch" 287 | version = "0.9.1" 288 | source = "registry+https://github.com/rust-lang/crates.io-index" 289 | checksum = "a1aaa739f95311c2c7887a76863f500026092fb1dce0161dab577e559ef3569d" 290 | dependencies = [ 291 | "cfg-if 1.0.0", 292 | "const_fn", 293 | "crossbeam-utils", 294 | "lazy_static", 295 | "memoffset", 296 | "scopeguard", 297 | ] 298 | 299 | [[package]] 300 | name = "crossbeam-utils" 301 | version = "0.8.1" 302 | source = "registry+https://github.com/rust-lang/crates.io-index" 303 | checksum = "02d96d1e189ef58269ebe5b97953da3274d83a93af647c2ddd6f9dab28cedb8d" 304 | dependencies = [ 305 | "autocfg 1.0.1", 306 | "cfg-if 1.0.0", 307 | "lazy_static", 308 | ] 309 | 310 | [[package]] 311 | name = "csv" 312 | version = "1.1.5" 313 | source = "registry+https://github.com/rust-lang/crates.io-index" 314 | checksum = "f9d58633299b24b515ac72a3f869f8b91306a3cec616a602843a383acd6f9e97" 315 | dependencies = [ 316 | "bstr", 317 | "csv-core", 318 | "itoa", 319 | "ryu", 320 | "serde", 321 | ] 322 | 323 | [[package]] 324 | name = "csv-core" 325 | version = "0.1.10" 326 | source = "registry+https://github.com/rust-lang/crates.io-index" 327 | checksum = "2b2466559f260f48ad25fe6317b3c8dac77b5bdb5763ac7d9d6103530663bc90" 328 | dependencies = [ 329 | "memchr", 330 | ] 331 | 332 | [[package]] 333 | name = "dirs" 334 | version = "1.0.5" 335 | source = "registry+https://github.com/rust-lang/crates.io-index" 336 | checksum = "3fd78930633bd1c6e35c4b42b1df7b0cbc6bc191146e512bb3bedf243fcc3901" 337 | dependencies = [ 338 | "libc", 339 | "redox_users", 340 | "winapi", 341 | ] 342 | 343 | [[package]] 344 | name = "either" 345 | version = "1.6.1" 346 | source = "registry+https://github.com/rust-lang/crates.io-index" 347 | checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" 348 | 349 | [[package]] 350 | name = "encode_unicode" 351 | version = "0.3.6" 352 | source = "registry+https://github.com/rust-lang/crates.io-index" 353 | checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" 354 | 355 | [[package]] 356 | name = "failure" 357 | version = "0.1.8" 358 | source = "registry+https://github.com/rust-lang/crates.io-index" 359 | checksum = "d32e9bd16cc02eae7db7ef620b392808b89f6a5e16bb3497d159c6b92a0f4f86" 360 | dependencies = [ 361 | "backtrace", 362 | "failure_derive", 363 | ] 364 | 365 | [[package]] 366 | name = "failure_derive" 367 | version = "0.1.8" 368 | source = "registry+https://github.com/rust-lang/crates.io-index" 369 | checksum = "aa4da3c766cd7a0db8242e326e9e4e081edd567072893ed320008189715366a4" 370 | dependencies = [ 371 | "proc-macro2", 372 | "quote", 373 | "syn", 374 | "synstructure", 375 | ] 376 | 377 | [[package]] 378 | name = "fixedbitset" 379 | version = "0.1.9" 380 | source = "registry+https://github.com/rust-lang/crates.io-index" 381 | checksum = "86d4de0081402f5e88cdac65c8dcdcc73118c1a7a465e2a05f0da05843a8ea33" 382 | 383 | [[package]] 384 | name = "form_urlencoded" 385 | version = "1.0.0" 386 | source = "registry+https://github.com/rust-lang/crates.io-index" 387 | checksum = "ece68d15c92e84fa4f19d3780f1294e5ca82a78a6d515f1efaabcc144688be00" 388 | dependencies = [ 389 | "matches", 390 | "percent-encoding", 391 | ] 392 | 393 | [[package]] 394 | name = "fuchsia-cprng" 395 | version = "0.1.1" 396 | source = "registry+https://github.com/rust-lang/crates.io-index" 397 | checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" 398 | 399 | [[package]] 400 | name = "getrandom" 401 | version = "0.1.15" 402 | source = "registry+https://github.com/rust-lang/crates.io-index" 403 | checksum = "fc587bc0ec293155d5bfa6b9891ec18a1e330c234f896ea47fbada4cadbe47e6" 404 | dependencies = [ 405 | "cfg-if 0.1.10", 406 | "libc", 407 | "wasi 0.9.0+wasi-snapshot-preview1", 408 | ] 409 | 410 | [[package]] 411 | name = "getrandom" 412 | version = "0.2.0" 413 | source = "registry+https://github.com/rust-lang/crates.io-index" 414 | checksum = "ee8025cf36f917e6a52cce185b7c7177689b838b7ec138364e50cc2277a56cf4" 415 | dependencies = [ 416 | "cfg-if 0.1.10", 417 | "libc", 418 | "wasi 0.9.0+wasi-snapshot-preview1", 419 | ] 420 | 421 | [[package]] 422 | name = "gimli" 423 | version = "0.23.0" 424 | source = "registry+https://github.com/rust-lang/crates.io-index" 425 | checksum = "f6503fe142514ca4799d4c26297c4248239fe8838d827db6bd6065c6ed29a6ce" 426 | 427 | [[package]] 428 | name = "half" 429 | version = "1.6.0" 430 | source = "registry+https://github.com/rust-lang/crates.io-index" 431 | checksum = "d36fab90f82edc3c747f9d438e06cf0a491055896f2a279638bb5beed6c40177" 432 | 433 | [[package]] 434 | name = "hashbrown" 435 | version = "0.11.2" 436 | source = "registry+https://github.com/rust-lang/crates.io-index" 437 | checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" 438 | dependencies = [ 439 | "ahash", 440 | ] 441 | 442 | [[package]] 443 | name = "hermit-abi" 444 | version = "0.1.17" 445 | source = "registry+https://github.com/rust-lang/crates.io-index" 446 | checksum = "5aca5565f760fb5b220e499d72710ed156fdb74e631659e99377d9ebfbd13ae8" 447 | dependencies = [ 448 | "libc", 449 | ] 450 | 451 | [[package]] 452 | name = "idna" 453 | version = "0.2.0" 454 | source = "registry+https://github.com/rust-lang/crates.io-index" 455 | checksum = "02e2673c30ee86b5b96a9cb52ad15718aa1f966f5ab9ad54a8b95d5ca33120a9" 456 | dependencies = [ 457 | "matches", 458 | "unicode-bidi", 459 | "unicode-normalization", 460 | ] 461 | 462 | [[package]] 463 | name = "itertools" 464 | version = "0.9.0" 465 | source = "registry+https://github.com/rust-lang/crates.io-index" 466 | checksum = "284f18f85651fe11e8a991b2adb42cb078325c996ed026d994719efcfca1d54b" 467 | dependencies = [ 468 | "either", 469 | ] 470 | 471 | [[package]] 472 | name = "itoa" 473 | version = "0.4.6" 474 | source = "registry+https://github.com/rust-lang/crates.io-index" 475 | checksum = "dc6f3ad7b9d11a0c00842ff8de1b60ee58661048eb8049ed33c73594f359d7e6" 476 | 477 | [[package]] 478 | name = "js-sys" 479 | version = "0.3.46" 480 | source = "registry+https://github.com/rust-lang/crates.io-index" 481 | checksum = "cf3d7383929f7c9c7c2d0fa596f325832df98c3704f2c60553080f7127a58175" 482 | dependencies = [ 483 | "wasm-bindgen", 484 | ] 485 | 486 | [[package]] 487 | name = "json" 488 | version = "0.12.4" 489 | source = "registry+https://github.com/rust-lang/crates.io-index" 490 | checksum = "078e285eafdfb6c4b434e0d31e8cfcb5115b651496faca5749b88fafd4f23bfd" 491 | 492 | [[package]] 493 | name = "lazy_static" 494 | version = "1.4.0" 495 | source = "registry+https://github.com/rust-lang/crates.io-index" 496 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 497 | 498 | [[package]] 499 | name = "libc" 500 | version = "0.2.81" 501 | source = "registry+https://github.com/rust-lang/crates.io-index" 502 | checksum = "1482821306169ec4d07f6aca392a4681f66c75c9918aa49641a2595db64053cb" 503 | 504 | [[package]] 505 | name = "linked-hash-map" 506 | version = "0.5.3" 507 | source = "registry+https://github.com/rust-lang/crates.io-index" 508 | checksum = "8dd5a6d5999d9907cda8ed67bbd137d3af8085216c2ac62de5be860bd41f304a" 509 | 510 | [[package]] 511 | name = "log" 512 | version = "0.4.11" 513 | source = "registry+https://github.com/rust-lang/crates.io-index" 514 | checksum = "4fabed175da42fed1fa0746b0ea71f412aa9d35e76e95e59b192c64b9dc2bf8b" 515 | dependencies = [ 516 | "cfg-if 0.1.10", 517 | ] 518 | 519 | [[package]] 520 | name = "logq" 521 | version = "0.1.19" 522 | dependencies = [ 523 | "anyhow", 524 | "chrono", 525 | "clap", 526 | "criterion", 527 | "csv", 528 | "failure", 529 | "hashbrown", 530 | "json", 531 | "lazy_static", 532 | "linked-hash-map", 533 | "nom", 534 | "ordered-float 2.8.0", 535 | "pdatastructs", 536 | "prettytable-rs", 537 | "rand 0.8.0", 538 | "regex", 539 | "tdigest", 540 | "tempfile", 541 | "url", 542 | ] 543 | 544 | [[package]] 545 | name = "matches" 546 | version = "0.1.8" 547 | source = "registry+https://github.com/rust-lang/crates.io-index" 548 | checksum = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08" 549 | 550 | [[package]] 551 | name = "memchr" 552 | version = "2.4.1" 553 | source = "registry+https://github.com/rust-lang/crates.io-index" 554 | checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" 555 | 556 | [[package]] 557 | name = "memoffset" 558 | version = "0.6.1" 559 | source = "registry+https://github.com/rust-lang/crates.io-index" 560 | checksum = "157b4208e3059a8f9e78d559edc658e13df41410cb3ae03979c83130067fdd87" 561 | dependencies = [ 562 | "autocfg 1.0.1", 563 | ] 564 | 565 | [[package]] 566 | name = "minimal-lexical" 567 | version = "0.1.3" 568 | source = "registry+https://github.com/rust-lang/crates.io-index" 569 | checksum = "0c835948974f68e0bd58636fc6c5b1fbff7b297e3046f11b3b3c18bbac012c6d" 570 | 571 | [[package]] 572 | name = "miniz_oxide" 573 | version = "0.4.3" 574 | source = "registry+https://github.com/rust-lang/crates.io-index" 575 | checksum = "0f2d26ec3309788e423cfbf68ad1800f061638098d76a83681af979dc4eda19d" 576 | dependencies = [ 577 | "adler", 578 | "autocfg 1.0.1", 579 | ] 580 | 581 | [[package]] 582 | name = "nom" 583 | version = "7.0.0" 584 | source = "registry+https://github.com/rust-lang/crates.io-index" 585 | checksum = "7ffd9d26838a953b4af82cbeb9f1592c6798916983959be223a7124e992742c1" 586 | dependencies = [ 587 | "memchr", 588 | "minimal-lexical", 589 | "version_check", 590 | ] 591 | 592 | [[package]] 593 | name = "num-integer" 594 | version = "0.1.44" 595 | source = "registry+https://github.com/rust-lang/crates.io-index" 596 | checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db" 597 | dependencies = [ 598 | "autocfg 1.0.1", 599 | "num-traits", 600 | ] 601 | 602 | [[package]] 603 | name = "num-traits" 604 | version = "0.2.14" 605 | source = "registry+https://github.com/rust-lang/crates.io-index" 606 | checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" 607 | dependencies = [ 608 | "autocfg 1.0.1", 609 | ] 610 | 611 | [[package]] 612 | name = "num_cpus" 613 | version = "1.13.0" 614 | source = "registry+https://github.com/rust-lang/crates.io-index" 615 | checksum = "05499f3756671c15885fee9034446956fff3f243d6077b91e5767df161f766b3" 616 | dependencies = [ 617 | "hermit-abi", 618 | "libc", 619 | ] 620 | 621 | [[package]] 622 | name = "object" 623 | version = "0.22.0" 624 | source = "registry+https://github.com/rust-lang/crates.io-index" 625 | checksum = "8d3b63360ec3cb337817c2dbd47ab4a0f170d285d8e5a2064600f3def1402397" 626 | 627 | [[package]] 628 | name = "once_cell" 629 | version = "1.8.0" 630 | source = "registry+https://github.com/rust-lang/crates.io-index" 631 | checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56" 632 | 633 | [[package]] 634 | name = "oorandom" 635 | version = "11.1.3" 636 | source = "registry+https://github.com/rust-lang/crates.io-index" 637 | checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" 638 | 639 | [[package]] 640 | name = "ordered-float" 641 | version = "1.1.1" 642 | source = "registry+https://github.com/rust-lang/crates.io-index" 643 | checksum = "3305af35278dd29f46fcdd139e0b1fbfae2153f0e5928b39b035542dd31e37b7" 644 | dependencies = [ 645 | "num-traits", 646 | ] 647 | 648 | [[package]] 649 | name = "ordered-float" 650 | version = "2.8.0" 651 | source = "registry+https://github.com/rust-lang/crates.io-index" 652 | checksum = "97c9d06878b3a851e8026ef94bf7fef9ba93062cd412601da4d9cf369b1cc62d" 653 | dependencies = [ 654 | "num-traits", 655 | ] 656 | 657 | [[package]] 658 | name = "pdatastructs" 659 | version = "0.6.0" 660 | source = "registry+https://github.com/rust-lang/crates.io-index" 661 | checksum = "fd2c982a59d7a982f5a99d0fa343531b3b3bd78ade59fede41845762c625f6c0" 662 | dependencies = [ 663 | "bytecount", 664 | "fixedbitset", 665 | "num-traits", 666 | "rand 0.6.5", 667 | "succinct", 668 | "void", 669 | ] 670 | 671 | [[package]] 672 | name = "percent-encoding" 673 | version = "2.1.0" 674 | source = "registry+https://github.com/rust-lang/crates.io-index" 675 | checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" 676 | 677 | [[package]] 678 | name = "plotters" 679 | version = "0.2.15" 680 | source = "registry+https://github.com/rust-lang/crates.io-index" 681 | checksum = "0d1685fbe7beba33de0330629da9d955ac75bd54f33d7b79f9a895590124f6bb" 682 | dependencies = [ 683 | "js-sys", 684 | "num-traits", 685 | "wasm-bindgen", 686 | "web-sys", 687 | ] 688 | 689 | [[package]] 690 | name = "ppv-lite86" 691 | version = "0.2.10" 692 | source = "registry+https://github.com/rust-lang/crates.io-index" 693 | checksum = "ac74c624d6b2d21f425f752262f42188365d7b8ff1aff74c82e45136510a4857" 694 | 695 | [[package]] 696 | name = "prettytable-rs" 697 | version = "0.8.0" 698 | source = "registry+https://github.com/rust-lang/crates.io-index" 699 | checksum = "0fd04b170004fa2daccf418a7f8253aaf033c27760b5f225889024cf66d7ac2e" 700 | dependencies = [ 701 | "atty", 702 | "csv", 703 | "encode_unicode", 704 | "lazy_static", 705 | "term", 706 | "unicode-width", 707 | ] 708 | 709 | [[package]] 710 | name = "proc-macro2" 711 | version = "1.0.24" 712 | source = "registry+https://github.com/rust-lang/crates.io-index" 713 | checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71" 714 | dependencies = [ 715 | "unicode-xid", 716 | ] 717 | 718 | [[package]] 719 | name = "quote" 720 | version = "1.0.8" 721 | source = "registry+https://github.com/rust-lang/crates.io-index" 722 | checksum = "991431c3519a3f36861882da93630ce66b52918dcf1b8e2fd66b397fc96f28df" 723 | dependencies = [ 724 | "proc-macro2", 725 | ] 726 | 727 | [[package]] 728 | name = "rand" 729 | version = "0.6.5" 730 | source = "registry+https://github.com/rust-lang/crates.io-index" 731 | checksum = "6d71dacdc3c88c1fde3885a3be3fbab9f35724e6ce99467f7d9c5026132184ca" 732 | dependencies = [ 733 | "autocfg 0.1.7", 734 | "libc", 735 | "rand_chacha 0.1.1", 736 | "rand_core 0.4.2", 737 | "rand_hc 0.1.0", 738 | "rand_isaac", 739 | "rand_jitter", 740 | "rand_os", 741 | "rand_pcg", 742 | "rand_xorshift", 743 | "winapi", 744 | ] 745 | 746 | [[package]] 747 | name = "rand" 748 | version = "0.8.0" 749 | source = "registry+https://github.com/rust-lang/crates.io-index" 750 | checksum = "a76330fb486679b4ace3670f117bbc9e16204005c4bde9c4bd372f45bed34f12" 751 | dependencies = [ 752 | "libc", 753 | "rand_chacha 0.3.0", 754 | "rand_core 0.6.0", 755 | "rand_hc 0.3.0", 756 | ] 757 | 758 | [[package]] 759 | name = "rand_chacha" 760 | version = "0.1.1" 761 | source = "registry+https://github.com/rust-lang/crates.io-index" 762 | checksum = "556d3a1ca6600bfcbab7c7c91ccb085ac7fbbcd70e008a98742e7847f4f7bcef" 763 | dependencies = [ 764 | "autocfg 0.1.7", 765 | "rand_core 0.3.1", 766 | ] 767 | 768 | [[package]] 769 | name = "rand_chacha" 770 | version = "0.3.0" 771 | source = "registry+https://github.com/rust-lang/crates.io-index" 772 | checksum = "e12735cf05c9e10bf21534da50a147b924d555dc7a547c42e6bb2d5b6017ae0d" 773 | dependencies = [ 774 | "ppv-lite86", 775 | "rand_core 0.6.0", 776 | ] 777 | 778 | [[package]] 779 | name = "rand_core" 780 | version = "0.3.1" 781 | source = "registry+https://github.com/rust-lang/crates.io-index" 782 | checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" 783 | dependencies = [ 784 | "rand_core 0.4.2", 785 | ] 786 | 787 | [[package]] 788 | name = "rand_core" 789 | version = "0.4.2" 790 | source = "registry+https://github.com/rust-lang/crates.io-index" 791 | checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" 792 | 793 | [[package]] 794 | name = "rand_core" 795 | version = "0.6.0" 796 | source = "registry+https://github.com/rust-lang/crates.io-index" 797 | checksum = "a8b34ba8cfb21243bd8df91854c830ff0d785fff2e82ebd4434c2644cb9ada18" 798 | dependencies = [ 799 | "getrandom 0.2.0", 800 | ] 801 | 802 | [[package]] 803 | name = "rand_hc" 804 | version = "0.1.0" 805 | source = "registry+https://github.com/rust-lang/crates.io-index" 806 | checksum = "7b40677c7be09ae76218dc623efbf7b18e34bced3f38883af07bb75630a21bc4" 807 | dependencies = [ 808 | "rand_core 0.3.1", 809 | ] 810 | 811 | [[package]] 812 | name = "rand_hc" 813 | version = "0.3.0" 814 | source = "registry+https://github.com/rust-lang/crates.io-index" 815 | checksum = "3190ef7066a446f2e7f42e239d161e905420ccab01eb967c9eb27d21b2322a73" 816 | dependencies = [ 817 | "rand_core 0.6.0", 818 | ] 819 | 820 | [[package]] 821 | name = "rand_isaac" 822 | version = "0.1.1" 823 | source = "registry+https://github.com/rust-lang/crates.io-index" 824 | checksum = "ded997c9d5f13925be2a6fd7e66bf1872597f759fd9dd93513dd7e92e5a5ee08" 825 | dependencies = [ 826 | "rand_core 0.3.1", 827 | ] 828 | 829 | [[package]] 830 | name = "rand_jitter" 831 | version = "0.1.4" 832 | source = "registry+https://github.com/rust-lang/crates.io-index" 833 | checksum = "1166d5c91dc97b88d1decc3285bb0a99ed84b05cfd0bc2341bdf2d43fc41e39b" 834 | dependencies = [ 835 | "libc", 836 | "rand_core 0.4.2", 837 | "winapi", 838 | ] 839 | 840 | [[package]] 841 | name = "rand_os" 842 | version = "0.1.3" 843 | source = "registry+https://github.com/rust-lang/crates.io-index" 844 | checksum = "7b75f676a1e053fc562eafbb47838d67c84801e38fc1ba459e8f180deabd5071" 845 | dependencies = [ 846 | "cloudabi", 847 | "fuchsia-cprng", 848 | "libc", 849 | "rand_core 0.4.2", 850 | "rdrand", 851 | "winapi", 852 | ] 853 | 854 | [[package]] 855 | name = "rand_pcg" 856 | version = "0.1.2" 857 | source = "registry+https://github.com/rust-lang/crates.io-index" 858 | checksum = "abf9b09b01790cfe0364f52bf32995ea3c39f4d2dd011eac241d2914146d0b44" 859 | dependencies = [ 860 | "autocfg 0.1.7", 861 | "rand_core 0.4.2", 862 | ] 863 | 864 | [[package]] 865 | name = "rand_xorshift" 866 | version = "0.1.1" 867 | source = "registry+https://github.com/rust-lang/crates.io-index" 868 | checksum = "cbf7e9e623549b0e21f6e97cf8ecf247c1a8fd2e8a992ae265314300b2455d5c" 869 | dependencies = [ 870 | "rand_core 0.3.1", 871 | ] 872 | 873 | [[package]] 874 | name = "rayon" 875 | version = "1.5.0" 876 | source = "registry+https://github.com/rust-lang/crates.io-index" 877 | checksum = "8b0d8e0819fadc20c74ea8373106ead0600e3a67ef1fe8da56e39b9ae7275674" 878 | dependencies = [ 879 | "autocfg 1.0.1", 880 | "crossbeam-deque", 881 | "either", 882 | "rayon-core", 883 | ] 884 | 885 | [[package]] 886 | name = "rayon-core" 887 | version = "1.9.0" 888 | source = "registry+https://github.com/rust-lang/crates.io-index" 889 | checksum = "9ab346ac5921dc62ffa9f89b7a773907511cdfa5490c572ae9be1be33e8afa4a" 890 | dependencies = [ 891 | "crossbeam-channel", 892 | "crossbeam-deque", 893 | "crossbeam-utils", 894 | "lazy_static", 895 | "num_cpus", 896 | ] 897 | 898 | [[package]] 899 | name = "rdrand" 900 | version = "0.4.0" 901 | source = "registry+https://github.com/rust-lang/crates.io-index" 902 | checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" 903 | dependencies = [ 904 | "rand_core 0.3.1", 905 | ] 906 | 907 | [[package]] 908 | name = "redox_syscall" 909 | version = "0.1.57" 910 | source = "registry+https://github.com/rust-lang/crates.io-index" 911 | checksum = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce" 912 | 913 | [[package]] 914 | name = "redox_syscall" 915 | version = "0.2.10" 916 | source = "registry+https://github.com/rust-lang/crates.io-index" 917 | checksum = "8383f39639269cde97d255a32bdb68c047337295414940c68bdd30c2e13203ff" 918 | dependencies = [ 919 | "bitflags", 920 | ] 921 | 922 | [[package]] 923 | name = "redox_users" 924 | version = "0.3.5" 925 | source = "registry+https://github.com/rust-lang/crates.io-index" 926 | checksum = "de0737333e7a9502c789a36d7c7fa6092a49895d4faa31ca5df163857ded2e9d" 927 | dependencies = [ 928 | "getrandom 0.1.15", 929 | "redox_syscall 0.1.57", 930 | "rust-argon2", 931 | ] 932 | 933 | [[package]] 934 | name = "regex" 935 | version = "1.5.4" 936 | source = "registry+https://github.com/rust-lang/crates.io-index" 937 | checksum = "d07a8629359eb56f1e2fb1652bb04212c072a87ba68546a04065d525673ac461" 938 | dependencies = [ 939 | "aho-corasick", 940 | "memchr", 941 | "regex-syntax", 942 | ] 943 | 944 | [[package]] 945 | name = "regex-automata" 946 | version = "0.1.9" 947 | source = "registry+https://github.com/rust-lang/crates.io-index" 948 | checksum = "ae1ded71d66a4a97f5e961fd0cb25a5f366a42a41570d16a763a69c092c26ae4" 949 | dependencies = [ 950 | "byteorder", 951 | ] 952 | 953 | [[package]] 954 | name = "regex-syntax" 955 | version = "0.6.25" 956 | source = "registry+https://github.com/rust-lang/crates.io-index" 957 | checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" 958 | 959 | [[package]] 960 | name = "remove_dir_all" 961 | version = "0.5.3" 962 | source = "registry+https://github.com/rust-lang/crates.io-index" 963 | checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" 964 | dependencies = [ 965 | "winapi", 966 | ] 967 | 968 | [[package]] 969 | name = "rust-argon2" 970 | version = "0.8.3" 971 | source = "registry+https://github.com/rust-lang/crates.io-index" 972 | checksum = "4b18820d944b33caa75a71378964ac46f58517c92b6ae5f762636247c09e78fb" 973 | dependencies = [ 974 | "base64", 975 | "blake2b_simd", 976 | "constant_time_eq", 977 | "crossbeam-utils", 978 | ] 979 | 980 | [[package]] 981 | name = "rustc-demangle" 982 | version = "0.1.18" 983 | source = "registry+https://github.com/rust-lang/crates.io-index" 984 | checksum = "6e3bad0ee36814ca07d7968269dd4b7ec89ec2da10c4bb613928d3077083c232" 985 | 986 | [[package]] 987 | name = "rustc_version" 988 | version = "0.2.3" 989 | source = "registry+https://github.com/rust-lang/crates.io-index" 990 | checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" 991 | dependencies = [ 992 | "semver", 993 | ] 994 | 995 | [[package]] 996 | name = "ryu" 997 | version = "1.0.5" 998 | source = "registry+https://github.com/rust-lang/crates.io-index" 999 | checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" 1000 | 1001 | [[package]] 1002 | name = "same-file" 1003 | version = "1.0.6" 1004 | source = "registry+https://github.com/rust-lang/crates.io-index" 1005 | checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" 1006 | dependencies = [ 1007 | "winapi-util", 1008 | ] 1009 | 1010 | [[package]] 1011 | name = "scopeguard" 1012 | version = "1.1.0" 1013 | source = "registry+https://github.com/rust-lang/crates.io-index" 1014 | checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" 1015 | 1016 | [[package]] 1017 | name = "semver" 1018 | version = "0.9.0" 1019 | source = "registry+https://github.com/rust-lang/crates.io-index" 1020 | checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" 1021 | dependencies = [ 1022 | "semver-parser", 1023 | ] 1024 | 1025 | [[package]] 1026 | name = "semver-parser" 1027 | version = "0.7.0" 1028 | source = "registry+https://github.com/rust-lang/crates.io-index" 1029 | checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" 1030 | 1031 | [[package]] 1032 | name = "serde" 1033 | version = "1.0.118" 1034 | source = "registry+https://github.com/rust-lang/crates.io-index" 1035 | checksum = "06c64263859d87aa2eb554587e2d23183398d617427327cf2b3d0ed8c69e4800" 1036 | 1037 | [[package]] 1038 | name = "serde_cbor" 1039 | version = "0.11.1" 1040 | source = "registry+https://github.com/rust-lang/crates.io-index" 1041 | checksum = "1e18acfa2f90e8b735b2836ab8d538de304cbb6729a7360729ea5a895d15a622" 1042 | dependencies = [ 1043 | "half", 1044 | "serde", 1045 | ] 1046 | 1047 | [[package]] 1048 | name = "serde_derive" 1049 | version = "1.0.118" 1050 | source = "registry+https://github.com/rust-lang/crates.io-index" 1051 | checksum = "c84d3526699cd55261af4b941e4e725444df67aa4f9e6a3564f18030d12672df" 1052 | dependencies = [ 1053 | "proc-macro2", 1054 | "quote", 1055 | "syn", 1056 | ] 1057 | 1058 | [[package]] 1059 | name = "serde_json" 1060 | version = "1.0.60" 1061 | source = "registry+https://github.com/rust-lang/crates.io-index" 1062 | checksum = "1500e84d27fe482ed1dc791a56eddc2f230046a040fa908c08bda1d9fb615779" 1063 | dependencies = [ 1064 | "itoa", 1065 | "ryu", 1066 | "serde", 1067 | ] 1068 | 1069 | [[package]] 1070 | name = "strsim" 1071 | version = "0.8.0" 1072 | source = "registry+https://github.com/rust-lang/crates.io-index" 1073 | checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" 1074 | 1075 | [[package]] 1076 | name = "succinct" 1077 | version = "0.4.4" 1078 | source = "registry+https://github.com/rust-lang/crates.io-index" 1079 | checksum = "cb9c14c504047586cd552f663b3deb1e7755c2973a83ededc47a555d51c164da" 1080 | dependencies = [ 1081 | "byteorder", 1082 | "num-traits", 1083 | ] 1084 | 1085 | [[package]] 1086 | name = "syn" 1087 | version = "1.0.56" 1088 | source = "registry+https://github.com/rust-lang/crates.io-index" 1089 | checksum = "a9802ddde94170d186eeee5005b798d9c159fa970403f1be19976d0cfb939b72" 1090 | dependencies = [ 1091 | "proc-macro2", 1092 | "quote", 1093 | "unicode-xid", 1094 | ] 1095 | 1096 | [[package]] 1097 | name = "synstructure" 1098 | version = "0.12.4" 1099 | source = "registry+https://github.com/rust-lang/crates.io-index" 1100 | checksum = "b834f2d66f734cb897113e34aaff2f1ab4719ca946f9a7358dba8f8064148701" 1101 | dependencies = [ 1102 | "proc-macro2", 1103 | "quote", 1104 | "syn", 1105 | "unicode-xid", 1106 | ] 1107 | 1108 | [[package]] 1109 | name = "tdigest" 1110 | version = "0.2.2" 1111 | source = "registry+https://github.com/rust-lang/crates.io-index" 1112 | checksum = "9b776c1c621df834c2bb190cc05cf4e67e4349fcea37fe8dc20588fb6f1a7a2c" 1113 | dependencies = [ 1114 | "ordered-float 1.1.1", 1115 | ] 1116 | 1117 | [[package]] 1118 | name = "tempfile" 1119 | version = "3.2.0" 1120 | source = "registry+https://github.com/rust-lang/crates.io-index" 1121 | checksum = "dac1c663cfc93810f88aed9b8941d48cabf856a1b111c29a40439018d870eb22" 1122 | dependencies = [ 1123 | "cfg-if 1.0.0", 1124 | "libc", 1125 | "rand 0.8.0", 1126 | "redox_syscall 0.2.10", 1127 | "remove_dir_all", 1128 | "winapi", 1129 | ] 1130 | 1131 | [[package]] 1132 | name = "term" 1133 | version = "0.5.2" 1134 | source = "registry+https://github.com/rust-lang/crates.io-index" 1135 | checksum = "edd106a334b7657c10b7c540a0106114feadeb4dc314513e97df481d5d966f42" 1136 | dependencies = [ 1137 | "byteorder", 1138 | "dirs", 1139 | "winapi", 1140 | ] 1141 | 1142 | [[package]] 1143 | name = "textwrap" 1144 | version = "0.11.0" 1145 | source = "registry+https://github.com/rust-lang/crates.io-index" 1146 | checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" 1147 | dependencies = [ 1148 | "unicode-width", 1149 | ] 1150 | 1151 | [[package]] 1152 | name = "time" 1153 | version = "0.1.44" 1154 | source = "registry+https://github.com/rust-lang/crates.io-index" 1155 | checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" 1156 | dependencies = [ 1157 | "libc", 1158 | "wasi 0.10.0+wasi-snapshot-preview1", 1159 | "winapi", 1160 | ] 1161 | 1162 | [[package]] 1163 | name = "tinytemplate" 1164 | version = "1.1.0" 1165 | source = "registry+https://github.com/rust-lang/crates.io-index" 1166 | checksum = "6d3dc76004a03cec1c5932bca4cdc2e39aaa798e3f82363dd94f9adf6098c12f" 1167 | dependencies = [ 1168 | "serde", 1169 | "serde_json", 1170 | ] 1171 | 1172 | [[package]] 1173 | name = "tinyvec" 1174 | version = "1.1.0" 1175 | source = "registry+https://github.com/rust-lang/crates.io-index" 1176 | checksum = "ccf8dbc19eb42fba10e8feaaec282fb50e2c14b2726d6301dbfeed0f73306a6f" 1177 | dependencies = [ 1178 | "tinyvec_macros", 1179 | ] 1180 | 1181 | [[package]] 1182 | name = "tinyvec_macros" 1183 | version = "0.1.0" 1184 | source = "registry+https://github.com/rust-lang/crates.io-index" 1185 | checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" 1186 | 1187 | [[package]] 1188 | name = "unicode-bidi" 1189 | version = "0.3.4" 1190 | source = "registry+https://github.com/rust-lang/crates.io-index" 1191 | checksum = "49f2bd0c6468a8230e1db229cff8029217cf623c767ea5d60bfbd42729ea54d5" 1192 | dependencies = [ 1193 | "matches", 1194 | ] 1195 | 1196 | [[package]] 1197 | name = "unicode-normalization" 1198 | version = "0.1.16" 1199 | source = "registry+https://github.com/rust-lang/crates.io-index" 1200 | checksum = "a13e63ab62dbe32aeee58d1c5408d35c36c392bba5d9d3142287219721afe606" 1201 | dependencies = [ 1202 | "tinyvec", 1203 | ] 1204 | 1205 | [[package]] 1206 | name = "unicode-width" 1207 | version = "0.1.8" 1208 | source = "registry+https://github.com/rust-lang/crates.io-index" 1209 | checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3" 1210 | 1211 | [[package]] 1212 | name = "unicode-xid" 1213 | version = "0.2.1" 1214 | source = "registry+https://github.com/rust-lang/crates.io-index" 1215 | checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" 1216 | 1217 | [[package]] 1218 | name = "url" 1219 | version = "2.2.0" 1220 | source = "registry+https://github.com/rust-lang/crates.io-index" 1221 | checksum = "5909f2b0817350449ed73e8bcd81c8c3c8d9a7a5d8acba4b27db277f1868976e" 1222 | dependencies = [ 1223 | "form_urlencoded", 1224 | "idna", 1225 | "matches", 1226 | "percent-encoding", 1227 | ] 1228 | 1229 | [[package]] 1230 | name = "vec_map" 1231 | version = "0.8.2" 1232 | source = "registry+https://github.com/rust-lang/crates.io-index" 1233 | checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" 1234 | 1235 | [[package]] 1236 | name = "version_check" 1237 | version = "0.9.2" 1238 | source = "registry+https://github.com/rust-lang/crates.io-index" 1239 | checksum = "b5a972e5669d67ba988ce3dc826706fb0a8b01471c088cb0b6110b805cc36aed" 1240 | 1241 | [[package]] 1242 | name = "void" 1243 | version = "1.0.2" 1244 | source = "registry+https://github.com/rust-lang/crates.io-index" 1245 | checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" 1246 | 1247 | [[package]] 1248 | name = "walkdir" 1249 | version = "2.3.1" 1250 | source = "registry+https://github.com/rust-lang/crates.io-index" 1251 | checksum = "777182bc735b6424e1a57516d35ed72cb8019d85c8c9bf536dccb3445c1a2f7d" 1252 | dependencies = [ 1253 | "same-file", 1254 | "winapi", 1255 | "winapi-util", 1256 | ] 1257 | 1258 | [[package]] 1259 | name = "wasi" 1260 | version = "0.9.0+wasi-snapshot-preview1" 1261 | source = "registry+https://github.com/rust-lang/crates.io-index" 1262 | checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" 1263 | 1264 | [[package]] 1265 | name = "wasi" 1266 | version = "0.10.0+wasi-snapshot-preview1" 1267 | source = "registry+https://github.com/rust-lang/crates.io-index" 1268 | checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" 1269 | 1270 | [[package]] 1271 | name = "wasm-bindgen" 1272 | version = "0.2.69" 1273 | source = "registry+https://github.com/rust-lang/crates.io-index" 1274 | checksum = "3cd364751395ca0f68cafb17666eee36b63077fb5ecd972bbcd74c90c4bf736e" 1275 | dependencies = [ 1276 | "cfg-if 1.0.0", 1277 | "wasm-bindgen-macro", 1278 | ] 1279 | 1280 | [[package]] 1281 | name = "wasm-bindgen-backend" 1282 | version = "0.2.69" 1283 | source = "registry+https://github.com/rust-lang/crates.io-index" 1284 | checksum = "1114f89ab1f4106e5b55e688b828c0ab0ea593a1ea7c094b141b14cbaaec2d62" 1285 | dependencies = [ 1286 | "bumpalo", 1287 | "lazy_static", 1288 | "log", 1289 | "proc-macro2", 1290 | "quote", 1291 | "syn", 1292 | "wasm-bindgen-shared", 1293 | ] 1294 | 1295 | [[package]] 1296 | name = "wasm-bindgen-macro" 1297 | version = "0.2.69" 1298 | source = "registry+https://github.com/rust-lang/crates.io-index" 1299 | checksum = "7a6ac8995ead1f084a8dea1e65f194d0973800c7f571f6edd70adf06ecf77084" 1300 | dependencies = [ 1301 | "quote", 1302 | "wasm-bindgen-macro-support", 1303 | ] 1304 | 1305 | [[package]] 1306 | name = "wasm-bindgen-macro-support" 1307 | version = "0.2.69" 1308 | source = "registry+https://github.com/rust-lang/crates.io-index" 1309 | checksum = "b5a48c72f299d80557c7c62e37e7225369ecc0c963964059509fbafe917c7549" 1310 | dependencies = [ 1311 | "proc-macro2", 1312 | "quote", 1313 | "syn", 1314 | "wasm-bindgen-backend", 1315 | "wasm-bindgen-shared", 1316 | ] 1317 | 1318 | [[package]] 1319 | name = "wasm-bindgen-shared" 1320 | version = "0.2.69" 1321 | source = "registry+https://github.com/rust-lang/crates.io-index" 1322 | checksum = "7e7811dd7f9398f14cc76efd356f98f03aa30419dea46aa810d71e819fc97158" 1323 | 1324 | [[package]] 1325 | name = "web-sys" 1326 | version = "0.3.46" 1327 | source = "registry+https://github.com/rust-lang/crates.io-index" 1328 | checksum = "222b1ef9334f92a21d3fb53dc3fd80f30836959a90f9274a626d7e06315ba3c3" 1329 | dependencies = [ 1330 | "js-sys", 1331 | "wasm-bindgen", 1332 | ] 1333 | 1334 | [[package]] 1335 | name = "winapi" 1336 | version = "0.3.9" 1337 | source = "registry+https://github.com/rust-lang/crates.io-index" 1338 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 1339 | dependencies = [ 1340 | "winapi-i686-pc-windows-gnu", 1341 | "winapi-x86_64-pc-windows-gnu", 1342 | ] 1343 | 1344 | [[package]] 1345 | name = "winapi-i686-pc-windows-gnu" 1346 | version = "0.4.0" 1347 | source = "registry+https://github.com/rust-lang/crates.io-index" 1348 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 1349 | 1350 | [[package]] 1351 | name = "winapi-util" 1352 | version = "0.1.5" 1353 | source = "registry+https://github.com/rust-lang/crates.io-index" 1354 | checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" 1355 | dependencies = [ 1356 | "winapi", 1357 | ] 1358 | 1359 | [[package]] 1360 | name = "winapi-x86_64-pc-windows-gnu" 1361 | version = "0.4.0" 1362 | source = "registry+https://github.com/rust-lang/crates.io-index" 1363 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 1364 | 1365 | [[package]] 1366 | name = "yaml-rust" 1367 | version = "0.3.5" 1368 | source = "registry+https://github.com/rust-lang/crates.io-index" 1369 | checksum = "e66366e18dc58b46801afbf2ca7661a9f59cc8c5962c29892b6039b4f86fa992" 1370 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "logq" 3 | description = "A web-server log file command line toolkit with SQL interface" 4 | repository = "https://github.com/MnO2/logq" 5 | version = "0.1.19" 6 | license = "Apache-2.0 OR BSD-3-Clause" 7 | authors = ["Paul Meng "] 8 | readme = "README.md" 9 | keywords = ["log", "sql", "query", "search"] 10 | categories = ["command-line-utilities"] 11 | edition = "2018" 12 | exclude = ["/benches/**", "/.travis.yml", "/data/**"] 13 | 14 | [badges] 15 | travis-ci = { repository = "MnO2/logq" } 16 | codecov = { repository = "MnO2/logq" } 17 | 18 | [dependencies] 19 | clap = {version = "2.33", features = ["yaml"]} 20 | regex = "1.5" 21 | failure = "0.1" 22 | hashbrown = "0.11" 23 | ordered-float = "2.8" 24 | nom = "7.0" 25 | prettytable-rs = "^0.8" 26 | chrono = "0.4" 27 | url = "2.2" 28 | csv = "1.1" 29 | lazy_static = "1.4.0" 30 | json = "0.12" 31 | tdigest = "0.2" 32 | pdatastructs = "0.6.0" 33 | linked-hash-map = "0.5" 34 | anyhow = "1.0" 35 | 36 | [dev-dependencies] 37 | criterion = "0.3" 38 | rand = "0.8" 39 | tempfile = "3.2" 40 | 41 | [[bench]] 42 | name = "logq_benchmark" 43 | harness = false 44 | path = "./benches/logq_benchmark.rs" 45 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-BSD3: -------------------------------------------------------------------------------- 1 | Valid-License-Identifier: BSD-3-Clause 2 | SPDX-URL: https://spdx.org/licenses/BSD-3-Clause.html 3 | Usage-Guide: 4 | To use the BSD 3-clause "New" or "Revised" License put the following SPDX 5 | tag/value pair into a comment according to the placement guidelines in 6 | the licensing rules documentation: 7 | SPDX-License-Identifier: BSD-3-Clause 8 | License-Text: 9 | 10 | Copyright (c) . All rights reserved. 11 | 12 | Redistribution and use in source and binary forms, with or without 13 | modification, are permitted provided that the following conditions are met: 14 | 15 | 1. Redistributions of source code must retain the above copyright notice, 16 | this list of conditions and the following disclaimer. 17 | 18 | 2. Redistributions in binary form must reproduce the above copyright 19 | notice, this list of conditions and the following disclaimer in the 20 | documentation and/or other materials provided with the distribution. 21 | 22 | 3. Neither the name of the copyright holder nor the names of its 23 | contributors may be used to endorse or promote products derived from this 24 | software without specific prior written permission. 25 | 26 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 27 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 28 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 29 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 30 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 31 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 32 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 33 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 34 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 35 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 36 | POSSIBILITY OF SUCH DAMAGE. 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # logq - Analyzing log files in PartiQL with command-line toolkit, implemented in Rust 2 | 3 | [![Build Status](https://travis-ci.com/MnO2/logq.svg?branch=master)](https://travis-ci.com/MnO2/logq) 4 | [![codecov](https://codecov.io/gh/MnO2/logq/branch/master/graph/badge.svg)](https://codecov.io/gh/MnO2/logq) 5 | 6 | 7 | This project is in alpha stage, PRs are welcomed. 8 | 9 | logq is a command line tool for easily analyzing, querying, aggregating web-server log files though PartiQL (which is compatible with SQL-92) inteface 10 | Right now the supported formats are 11 | 12 | 1. AWS classic elastic load balancer 13 | 2. AWS application load balancer 14 | 3. AWS S3 Access Log (preliminary support) 15 | 4. Squid native format (preliminary support) 16 | 17 | More log formats would be supported in the future, and ideally it could be customized through configuration like what GoAccess does. 18 | 19 | ## Installation 20 | 21 | ``` 22 | cargo install logq 23 | ``` 24 | 25 | ## Examples on querying flat logs 26 | 27 | Project the columns of `timestamp` and `backend_and_port` fields from the log file and print the first three records out. 28 | 29 | ``` 30 | > logq query 'select timestamp, backend_processing_time from it order by timestamp asc limit 3' --table it:elb=data/AWSELB.log 31 | 32 | +-----------------------------------+----------+ 33 | | 2015-11-07 18:45:33.007671 +00:00 | 0.618779 | 34 | +-----------------------------------+----------+ 35 | | 2015-11-07 18:45:33.054086 +00:00 | 0.654135 | 36 | +-----------------------------------+----------+ 37 | | 2015-11-07 18:45:33.094266 +00:00 | 0.506634 | 38 | +-----------------------------------+----------+ 39 | ``` 40 | 41 | Summing up the total sent bytes in 5 seconds time frame. 42 | ``` 43 | > logq query 'select t, sum(sent_bytes) as s from it group by time_bucket("5 seconds", timestamp) as t' --table it:elb=data/AWSELB.log 44 | +----------------------------+----------+ 45 | | 2015-11-07 18:45:30 +00:00 | 12256229 | 46 | +----------------------------+----------+ 47 | | 2015-11-07 18:45:35 +00:00 | 33148328 | 48 | +----------------------------+----------+ 49 | ``` 50 | 51 | Select the 90th percentile backend_processsing_time with 5 second as the time frame. 52 | ``` 53 | > logq query 'select t, percentile_disc(0.9) within group (order by backend_processing_time asc) as bps from it group by time_bucket("5 seconds", timestamp) as t' --table it:elb=data/AWSELB.log 54 | +----------------------------+----------+ 55 | | 2015-11-07 18:45:30 +00:00 | 0.112312 | 56 | +----------------------------+----------+ 57 | | 2015-11-07 18:45:35 +00:00 | 0.088791 | 58 | +----------------------------+----------+ 59 | ``` 60 | 61 | To collapse the part of the url path so that they are mapping to the same Restful handler, you could use `url_path_bucket` 62 | ``` 63 | > logq query 'select time_bucket("5 seconds", timestamp) as t, url_path_bucket(request, 1, "_") as s from it limit 10' --table it:elb=data/AWSELB.log 64 | +----------------------------+----------------------------------------------+ 65 | | 2015-11-07 18:45:30 +00:00 | / | 66 | +----------------------------+----------------------------------------------+ 67 | | 2015-11-07 18:45:30 +00:00 | /img/_/000000000000000000000000 | 68 | +----------------------------+----------------------------------------------+ 69 | | 2015-11-07 18:45:30 +00:00 | /favicons/_ | 70 | +----------------------------+----------------------------------------------+ 71 | | 2015-11-07 18:45:30 +00:00 | /images/_/devices.png | 72 | +----------------------------+----------------------------------------------+ 73 | | 2015-11-07 18:45:30 +00:00 | /stylesheets/_/font-awesome.css | 74 | +----------------------------+----------------------------------------------+ 75 | | 2015-11-07 18:45:30 +00:00 | /favicons/_ | 76 | +----------------------------+----------------------------------------------+ 77 | | 2015-11-07 18:45:30 +00:00 | /mobile/_/register-push | 78 | +----------------------------+----------------------------------------------+ 79 | | 2015-11-07 18:45:30 +00:00 | /img/_/205/2r1/562e37d9208bee5b70f56836.anim | 80 | +----------------------------+----------------------------------------------+ 81 | | 2015-11-07 18:45:30 +00:00 | /img/_/300/2r0/54558148eab71c6c2517f1d9.jpg | 82 | +----------------------------+----------------------------------------------+ 83 | | 2015-11-07 18:45:30 +00:00 | / | 84 | +----------------------------+----------------------------------------------+ 85 | ``` 86 | 87 | Output in different format, you can specify the format by `--output`, it supports `json` and `csv` at this moment. 88 | ``` 89 | > logq query --output csv 'select t, sum(sent_bytes) as s from it group by time_bucket("5 seconds", timestamp) as t' --table it:elb=data/AWSELB.log 90 | 2015-11-07 18:45:35 +00:00,33148328 91 | 2015-11-07 18:45:30 +00:00,12256229 92 | ``` 93 | 94 | ``` 95 | > logq query --output json 'select t, sum(sent_bytes) as s from it group by time_bucket("5 seconds", timestamp) as t' --table it:elb=data/AWSELB.log 96 | [{"t":"2015-11-07 18:45:30 +00:00","s":12256229},{"t":"2015-11-07 18:45:35 +00:00","s":33148328}] 97 | ``` 98 | 99 | You can use graphing command-line tools to graph the data set in terminal. For example, [termgraph](https://github.com/mkaz/termgraph) would be a good choice for bar charts 100 | ``` 101 | > logq query --output csv 'select backend_and_port, sum(sent_bytes) from it group by backend_and_port' --table it:elb=data/AWSELB.log | termgraph 102 | 103 | 10.0.2.143:80: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 20014156.00 104 | 10.0.0.215:80: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 25390392.00 105 | ``` 106 | 107 | Or you could use [spark](https://github.com/holman/spark) to draw the processing time over time 108 | ``` 109 | > logq query --output csv 'select host_name(backend_and_port) as h, backend_processing_time from it where h = "10.0.2.143"' --table it:elb=data/AWSELB.log | cut -d, -f2 | spark 110 | ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ 111 | ``` 112 | 113 | If you are unclear how the execution was running, the query plan could be explained. 114 | ``` 115 | > logq explain 'select t, sum(sent_bytes) as s from it group by time_bucket("5 seconds", timestamp) as t' 116 | Query Plan: 117 | GroupBy(["t"], [NamedAggregate { aggregate: Sum(SumAggregate { sums: {} }, Expression(Variable("sent_bytes"), Some("sent_bytes"))), name_opt: Some("s") }], Map([Expression(Function("time_bucket", [Expression(Variable("const_000000000"), None), Expression(Variable("timestamp"), Some("timestamp"))]), Some("t")), Expression(Variable("sent_bytes"), Some("sent_bytes"))], DataSource(Stdin))) 118 | ``` 119 | 120 | To know what are the fields, here is the table schema. 121 | ``` 122 | > logq schema elb 123 | +--------------------------+-------------+ 124 | | timestamp | DateTime | 125 | +--------------------------+-------------+ 126 | | elbname | String | 127 | +--------------------------+-------------+ 128 | | client_and_port | Host | 129 | +--------------------------+-------------+ 130 | | backend_and_port | Host | 131 | +--------------------------+-------------+ 132 | | request_processing_time | Float | 133 | +--------------------------+-------------+ 134 | | backend_processing_time | Float | 135 | +--------------------------+-------------+ 136 | | response_processing_time | Float | 137 | +--------------------------+-------------+ 138 | | elb_status_code | String | 139 | +--------------------------+-------------+ 140 | | backend_status_code | String | 141 | +--------------------------+-------------+ 142 | | received_bytes | Integral | 143 | +--------------------------+-------------+ 144 | | sent_bytes | Integral | 145 | +--------------------------+-------------+ 146 | | request | HttpRequest | 147 | +--------------------------+-------------+ 148 | | user_agent | String | 149 | +--------------------------+-------------+ 150 | | ssl_cipher | String | 151 | +--------------------------+-------------+ 152 | | ssl_protocol | String | 153 | +--------------------------+-------------+ 154 | | target_group_arn | String | 155 | +--------------------------+-------------+ 156 | | trace_id | String | 157 | +--------------------------+-------------+ 158 | ``` 159 | 160 | To know the supported log format at this moment. 161 | ``` 162 | > logq schema 163 | The supported log format 164 | * elb 165 | ``` 166 | 167 | ## Examples to query nested `jsonl` logs 168 | 169 | For the `jsonl` format like this 170 | 171 | ``` 172 | {"a": 1, "b": "123", "c": 456.1, "d": [0, 1, 2], "e": {"f": {"g": 1}}} 173 | {"a": 1, "b": "123", "d": [1, 2, 3], "e": {"f": {"g": 2}}} 174 | {"a": 1, "b": "456", "d": [4, 5, 6], "e": {"f": {"g": 3}}} 175 | ``` 176 | 177 | We can query the log like this 178 | 179 | ``` 180 | logq run query 'select x, count(*) as x from it group by d[0] as x' --table it:jsonl=data/structured.log --output=json 181 | [{"x":1},{"x":1},{"x":1}] 182 | ``` 183 | 184 | ``` 185 | logq run query 'select b, e.f.g from it' --table it:jsonl=data/structured.log --output=json 186 | [{"b":"123","g":1},{"b":"123","g":2},{"b":"456","g":3}] 187 | ``` 188 | 189 | 190 | ## Available Functions 191 | 192 | | Function Name | Description | Input Type | Output Type | 193 | | --- | --- | --- | --- | 194 | | url_host | To retrieve the host from the request | Request | String | 195 | | url_port | To retrieve the port from teh request | Request | String | 196 | | url_path | To retrieve the path from the request | Request | String | 197 | | url_fragment | To retrieve the fragment from the request | Request | String | 198 | | url_query | To retrive the query from the request | Request | String | 199 | | url_path_segments | To retrieve the path segments from the request | Request | String | 200 | | url_path_bucket | To map the path segments into given string | Request, Integral, String | String | 201 | | time_bucket | To bucket the timestamp into given interval | String, DateTime | DateTime | 202 | | date_part | To get the part of the datetime with the given unit | String, DateTime | Float | 203 | | host_name | To retreive the hostname from host | Host | String | 204 | | host_port | To retreive the port from host | Host | String | 205 | 206 | ## Aggregation Functions 207 | 208 | | Function Name | Description | Input Type | 209 | | --- | --- | --- | 210 | | avg | average the numbers | Integral or Float | 211 | | count | counting the number of records | Any | 212 | | first | get the first of the records | Any | 213 | | last | get the last of the records | Any | 214 | | min | get the min of the records | Any | 215 | | max | get the max of the records | Any | 216 | | sum | get the sum of the numbers | Integral or Float | 217 | | percentile_disc | calculate record at the percentile | Float | 218 | | approx_percentile | calculate approximate record at the percentile | Float | 219 | 220 | 221 | ## Motivation 222 | 223 | Often time in the daily work when you are troubleshooting the production issues, there are certain metrics that's not provided by AWS CloudWatch or in-house ELK. Then you would download the original access logs from your company's archive and write an one-off script to analyze it. However, this approach has a few drawbacks. 224 | 225 | 1. You spend a lot of time to parse of the log format, but not focus on calculating the metrics helping to troubleshoot your production issues. 226 | 2. Most of the log formats are commonly seen and we should ideally abstract it and have every one benefit from the shared abstraction 227 | 3. For web-server log cases, the log volume usually is huge, it could be several hundred MB or even a few GB. Doing it in scripting langauges would make yourself impatiently waiting it is running at your local. 228 | 229 | For sure you could finely tuned the analytical tooling like AWS Athena or ELK to analyze the large volume of data, but often times you just want to adhocly analyze logs and don't bother to set things up and cost extra money. Also, the modern laptop/PC is actually powerful enough to analyze gigabytes of log volumes, just that the implementation is not efficient enough for doing that. Implementing logq in Rust is in hope to resolve those inconvenience and concerns. 230 | 231 | 232 | ### Why not TextQL, or insert the space delimited fields into sqlite? 233 | 234 | TextQL is implemented in python ant it's ok for the smaller cases. In the case of high traffic AWS ELB log files, it often goes up to gigabytes in volume and it is slow 235 | regarding to the speed. Furthermore, either TextQL and sqlite are limited in their provided SQL functions and data types, it makes the domain processing like URL, and HTTP 236 | reuqests line and User-Agents tedious. 237 | 238 | Another big reason is that we would like to support `jsonl` format (lines of `json`), which is nested semi-structured data that require the extension of SQL to be able to be queried effectively. 239 | 240 | Also, in the use case of web-traffic analytics, the questions you would to be answered are like "What is the 99th percentile in a given time frame to this Restful endpoint, by ignoring the user_id in the URL path segments". It would be easier to have a software providing handy functions to extract or canonicalize the information from the log. 241 | 242 | 243 | ## Roadmap 244 | 245 | - [ ] Using cmdline flag to specify the table names and their the backing files. 246 | - [ ] Spin-off the syntax parser as a separate cargo crate. 247 | - [ ] Support complete [PartiQL](https://partiql.org/assets/PartiQL-Specification.pdf) specification, tutorial [here](https://partiql.org/tutorial.html#running-the-partiql-repl). 248 | - [ ] Performance optimization, avoid unnecessary parsing 249 | - [ ] More supported functions 250 | - [ ] time_bucket with arbitrary interval (begin from epoch) 251 | - [ ] Polish the parser to be [SQL-92-compatible](https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#_5_lexical_elements) 252 | - [ ] Streaming mode to work with `tail -f` 253 | - [ ] Customizable Reader, to follow GoAccess's style 254 | - [ ] More supported log format 255 | - [ ] Plugin quickjs for user-defined functions 256 | - [ ] Implement APPROX_COUNT_DISTINCT with Hyperloglog 257 | - [ ] Building index for repetitive queries 258 | -------------------------------------------------------------------------------- /benches/logq_benchmark.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate criterion; 3 | 4 | use criterion::Criterion; 5 | 6 | fn bench_parse_query() { 7 | let _ = 1 + 1; 8 | } 9 | 10 | fn criterion_benchmark(c: &mut Criterion) { 11 | c.bench_function("parse query", |b| b.iter(bench_parse_query)); 12 | } 13 | 14 | criterion_group!(benches, criterion_benchmark); 15 | criterion_main!(benches); 16 | -------------------------------------------------------------------------------- /data/AWSALB.log: -------------------------------------------------------------------------------- 1 | http 2018-07-02T22:23:00.186641Z app/my-loadbalancer/50dc6c495c0c9188 192.168.131.39:2817 10.0.0.1:80 0.000 0.001 0.000 200 200 34 366 "GET http://www.example.com:80/ HTTP/1.1" "curl/7.46.0" - - arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067 "Root=1-58337262-36d228ad5d99923122bbe354" "-" "-" 0 2018-07-02T22:22:48.364000Z "forward" "-" "-" 2 | https 2018-07-02T22:23:00.186641Z app/my-loadbalancer/50dc6c495c0c9188 192.168.131.39:2817 10.0.0.1:80 0.086 0.048 0.037 200 200 0 57 "GET https://www.example.com:443/ HTTP/1.1" "curl/7.46.0" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067 "Root=1-58337281-1d84f3d73c47ec4e58577259" "www.example.com" "arn:aws:acm:us-east-2:123456789012:certificate/12345678-1234-1234-1234-123456789012" 1 2018-07-02T22:22:48.364000Z "authenticate,forward" "-" "-" 3 | h2 2018-07-02T22:23:00.186641Z app/my-loadbalancer/50dc6c495c0c9188 10.0.1.252:48160 10.0.0.66:9000 0.000 0.002 0.000 200 200 5 257 "GET https://10.0.2.105:773/ HTTP/2.0" "curl/7.46.0" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067 "Root=1-58337327-72bd00b0343d75b906739c42" "-" "-" 1 2018-07-02T22:22:48.364000Z "redirect" "https://example.com:80/" "-" 4 | ws 2018-07-02T22:23:00.186641Z app/my-loadbalancer/50dc6c495c0c9188 10.0.0.140:40914 10.0.1.192:8010 0.001 0.003 0.000 101 101 218 587 "GET http://10.0.0.30:80/ HTTP/1.1" "-" - - arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067 "Root=1-58337364-23a8c76965a2ef7629b185e3" "-" "-" 1 2018-07-02T22:22:48.364000Z "forward" "-" "-" 5 | wss 2018-07-02T22:23:00.186641Z app/my-loadbalancer/50dc6c495c0c9188 10.0.0.140:44244 10.0.0.171:8010 0.000 0.001 0.000 101 101 218 786 "GET https://10.0.0.30:443/ HTTP/1.1" "-" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067 "Root=1-58337364-23a8c76965a2ef7629b185e3" "-" "-" 1 2018-07-02T22:22:48.364000Z "forward" "-" "-" 6 | http 2018-11-30T22:23:00.186641Z app/my-loadbalancer/50dc6c495c0c9188 192.168.131.39:2817 - 0.000 0.001 0.000 200 200 34 366 "GET http://www.example.com:80/ HTTP/1.1" "curl/7.46.0" - - arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067 "Root=1-58337364-23a8c76965a2ef7629b185e3" "-" "-" 0 2018-11-30T22:22:48.364000Z "forward" "-" "-" 7 | http 2018-11-30T22:23:00.186641Z app/my-loadbalancer/50dc6c495c0c9188 192.168.131.39:2817 - 0.000 0.001 0.000 502 - 34 366 "GET http://www.example.com:80/ HTTP/1.1" "curl/7.46.0" - - arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067 "Root=1-58337364-23a8c76965a2ef7629b185e3" "-" "-" 0 2018-11-30T22:22:48.364000Z "forward" "-" "LambdaInvalidResponse" 8 | -------------------------------------------------------------------------------- /data/S3.log: -------------------------------------------------------------------------------- 1 | 79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be awsexamplebucket [06/Feb/2019:00:00:38 +0000] 192.0.2.3 79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be 3E57427F3EXAMPLE REST.GET.VERSIONING - "GET /awsexamplebucket?versioning HTTP/1.1" 200 - 113 - 7 - "-" "S3Console/0.4" - s9lzHYrFp76ZVxRcpX9+5cjAnEH2ROuNkd2BHfIa6UkFVdtjf5mKR3/eTPFvsiP/XV/VLi31234= SigV2 ECDHE-RSA-AES128-GCM-SHA256 AuthHeader awsexamplebucket.s3.amazonaws.com TLSV1.1 2 | 79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be awsexamplebucket [06/Feb/2019:00:00:38 +0000] 192.0.2.3 79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be 891CE47D2EXAMPLE REST.GET.LOGGING_STATUS - "GET /awsexamplebucket?logging HTTP/1.1" 200 - 242 - 11 - "-" "S3Console/0.4" - 9vKBE6vMhrNiWHZmb2L0mXOcqPGzQOI5XLnCtZNPxev+Hf+7tpT6sxDwDty4LHBUOZJG96N1234= SigV2 ECDHE-RSA-AES128-GCM-SHA256 AuthHeader awsexamplebucket.s3.amazonaws.com TLSV1.1 3 | 79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be awsexamplebucket [06/Feb/2019:00:00:38 +0000] 192.0.2.3 79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be A1206F460EXAMPLE REST.GET.BUCKETPOLICY - "GET /awsexamplebucket?policy HTTP/1.1" 404 NoSuchBucketPolicy 297 - 38 - "-" "S3Console/0.4" - BNaBsXZQQDbssi6xMBdBU2sLt+Yf5kZDmeBUP35sFoKa3sLLeMC78iwEIWxs99CRUrbS4n11234= SigV2 ECDHE-RSA-AES128-GCM-SHA256 AuthHeader awsexamplebucket.s3.amazonaws.com TLSV1.1 4 | 79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be awsexamplebucket [06/Feb/2019:00:01:00 +0000] 192.0.2.3 79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be 7B4A0FABBEXAMPLE REST.GET.VERSIONING - "GET /awsexamplebucket?versioning HTTP/1.1" 200 - 113 - 33 - "-" "S3Console/0.4" - Ke1bUcazaN1jWuUlPJaxF64cQVpUEhoZKEG/hmy/gijN/I1DeWqDfFvnpybfEseEME/u7ME1234= SigV2 ECDHE-RSA-AES128-GCM-SHA256 AuthHeader awsexamplebucket.s3.amazonaws.com TLSV1.1 5 | 79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be awsexamplebucket [06/Feb/2019:00:01:57 +0000] 192.0.2.3 79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be DD6CC733AEXAMPLE REST.PUT.OBJECT s3-dg.pdf "PUT /awsexamplebucket/s3-dg.pdf HTTP/1.1" 200 - - 4406583 41754 28 "-" "S3Console/0.4" - 10S62Zv81kBW7BB6SX4XJ48o6kpcl6LPwEoizZQQxJd5qDSCTLX0TgS37kYUBKQW3+bPdrg1234= SigV4 ECDHE-RSA-AES128-SHA AuthHeader awsexamplebucket.s3.amazonaws.com TLSV1.1 6 | -------------------------------------------------------------------------------- /data/Squid.log: -------------------------------------------------------------------------------- 1 | 1515734740.494 1 [MASKEDIPADDRESS] TCP_DENIED/407 3922 CONNECT d.dropbox.com:443 - HIER_NONE/- text/html 2 | 1515734801.274 60719 [MASKEDIPADDRESS] TCP_TUNNEL/200 3790 CONNECT d.dropbox.com:443 erik HIER_DIRECT/162.125.34.6 - 3 | 1515734943.397 1 [MASKEDIPADDRESS] TCP_DENIED/407 3954 CONNECT client-cf.dropbox.com:443 - HIER_NONE/- text/html 4 | 1515734943.889 1257872 [MASKEDIPADDRESS] TCP_TUNNEL/200 9033 CONNECT bolt.dropbox.com:443 erik HIER_DIRECT/162.125.18.133 - 5 | 1515734943.951 1 [MASKEDIPADDRESS] TCP_DENIED/407 3934 CONNECT bolt.dropbox.com:443 - HIER_NONE/- text/html 6 | 1515735003.743 60277 [MASKEDIPADDRESS] TCP_TUNNEL/200 4059 CONNECT client-cf.dropbox.com:443 erik HIER_DIRECT/162.125.65.3 - 7 | 1515735033.399 5897754 [MASKEDIPADDRESS] TCP_TUNNEL/200 29063 CONNECT bolt.dropbox.com:443 erik HIER_DIRECT/162.125.18.133 - 8 | 1515735033.465 1 [MASKEDIPADDRESS] TCP_DENIED/407 3934 CONNECT bolt.dropbox.com:443 - HIER_NONE/- text/html 9 | 1515735036.690 1 [MASKEDIPADDRESS] TCP_DENIED/407 428 HEAD http://www.nu.nl/feeds/rss/algemeen.rss - HIER_NONE/- text/html 10 | 1515735036.738 2 [MASKEDIPADDRESS] TCP_DENIED/407 4353 GET http://www.tubantia.nl/cmlink/1.3294177 - HIER_NONE/- text/html 11 | -------------------------------------------------------------------------------- /data/structured.log: -------------------------------------------------------------------------------- 1 | {"a": 1, "b": "123", "c": 456.1, "d": [0, 1, 2], "e": {"f": {"g": 1}}} 2 | {"a": 1, "b": "123", "d": [1, 2, 3], "e": {"f": {"g": 2}}} 3 | {"a": 1, "b": "456", "d": [4, 5, 6], "e": {"f": {"g": 3}}} 4 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width = 120 2 | -------------------------------------------------------------------------------- /scripts/elb_log_generator.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'date' 3 | 4 | for i in 1..100000 do 5 | dt = DateTime.now 6 | current_dt_str = dt.iso8601(6) 7 | 8 | log = %?#{current_dt_str} elb1 78.168.134.92:4586 10.0.0.215:80 0.000036 0.001035 0.000025 200 200 0 42355 "GET https://example.com:443/ HTTP/1.1" "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2? 9 | puts log 10 | end 11 | -------------------------------------------------------------------------------- /src/app.rs: -------------------------------------------------------------------------------- 1 | use csv::Writer; 2 | use nom::error::VerboseError; 3 | use prettytable::{Row, Table}; 4 | use std::result; 5 | use std::str::FromStr; 6 | 7 | use crate::common; 8 | use crate::execution; 9 | use crate::logical; 10 | use crate::syntax; 11 | 12 | pub(crate) type AppResult = result::Result; 13 | 14 | #[derive(Fail, Debug)] 15 | pub(crate) enum AppError { 16 | #[fail(display = "Syntax Error: {}", _0)] 17 | Syntax(String), 18 | #[fail(display = "Input is fully consumed, the leftover are \"{}\"", _0)] 19 | InputNotAllConsumed(String), 20 | #[fail(display = "{}", _0)] 21 | Parse(#[cause] logical::parser::ParseError), 22 | #[fail(display = "{}", _0)] 23 | PhysicalPlan(#[cause] logical::types::PhysicalPlanError), 24 | #[fail(display = "{}", _0)] 25 | CreateStream(#[cause] execution::types::CreateStreamError), 26 | #[fail(display = "{}", _0)] 27 | Stream(#[cause] execution::types::StreamError), 28 | #[fail(display = "Invalid Log File Format")] 29 | InvalidLogFileFormat, 30 | #[fail(display = "Invalid Table Spec String")] 31 | InvalidTableSpecString, 32 | #[fail(display = "{}", _0)] 33 | WriteCsv(#[cause] csv::Error), 34 | #[fail(display = "{}", _0)] 35 | WriteJson(#[cause] json::Error), 36 | } 37 | 38 | impl PartialEq for AppError { 39 | fn eq(&self, other: &Self) -> bool { 40 | match (self, other) { 41 | (AppError::Syntax(_), AppError::Syntax(_)) => true, 42 | (AppError::InputNotAllConsumed(_), AppError::InputNotAllConsumed(_)) => true, 43 | (AppError::Parse(_), AppError::Parse(_)) => true, 44 | (AppError::PhysicalPlan(_), AppError::PhysicalPlan(_)) => true, 45 | (AppError::CreateStream(_), AppError::CreateStream(_)) => true, 46 | (AppError::Stream(_), AppError::Stream(_)) => true, 47 | (AppError::InvalidLogFileFormat, AppError::InvalidLogFileFormat) => true, 48 | (AppError::InvalidTableSpecString, AppError::InvalidTableSpecString) => true, 49 | (AppError::WriteCsv(_), AppError::WriteCsv(_)) => true, 50 | (AppError::WriteJson(_), AppError::WriteJson(_)) => true, 51 | _ => false, 52 | } 53 | } 54 | } 55 | 56 | impl Eq for AppError {} 57 | 58 | impl From>> for AppError { 59 | fn from(e: nom::Err>) -> AppError { 60 | match e { 61 | nom::Err::Failure(v) => { 62 | let mut errors: String = String::new(); 63 | for (s, _) in v.errors { 64 | errors.push_str(&s.to_string()); 65 | errors.push('\n'); 66 | } 67 | 68 | AppError::Syntax(errors) 69 | } 70 | nom::Err::Error(v) => { 71 | let mut errors: String = String::new(); 72 | for (s, _) in v.errors { 73 | errors.push_str(&s.to_string()); 74 | errors.push('\n'); 75 | } 76 | 77 | AppError::Syntax(errors) 78 | } 79 | _ => AppError::Syntax(String::new()), 80 | } 81 | } 82 | } 83 | 84 | impl From for AppError { 85 | fn from(e: logical::parser::ParseError) -> AppError { 86 | AppError::Parse(e) 87 | } 88 | } 89 | 90 | impl From for AppError { 91 | fn from(err: logical::types::PhysicalPlanError) -> AppError { 92 | AppError::PhysicalPlan(err) 93 | } 94 | } 95 | 96 | impl From for AppError { 97 | fn from(err: execution::types::CreateStreamError) -> AppError { 98 | AppError::CreateStream(err) 99 | } 100 | } 101 | 102 | impl From for AppError { 103 | fn from(err: execution::types::StreamError) -> AppError { 104 | AppError::Stream(err) 105 | } 106 | } 107 | 108 | impl From for AppError { 109 | fn from(err: csv::Error) -> AppError { 110 | AppError::WriteCsv(err) 111 | } 112 | } 113 | 114 | impl From for AppError { 115 | fn from(err: json::Error) -> AppError { 116 | AppError::WriteJson(err) 117 | } 118 | } 119 | 120 | pub(crate) enum OutputMode { 121 | Table, 122 | Csv, 123 | Json, 124 | } 125 | 126 | impl FromStr for OutputMode { 127 | type Err = String; 128 | 129 | fn from_str(s: &str) -> result::Result { 130 | match s { 131 | "table" => Ok(OutputMode::Table), 132 | "csv" => Ok(OutputMode::Csv), 133 | "json" => Ok(OutputMode::Json), 134 | _ => Err("unknown output mode".to_string()), 135 | } 136 | } 137 | } 138 | 139 | pub(crate) fn explain(query_str: &str, data_source: common::types::DataSource) -> AppResult<()> { 140 | let (rest_of_str, select_stmt) = syntax::parser::select_query(&query_str)?; 141 | if !rest_of_str.is_empty() { 142 | return Err(AppError::InputNotAllConsumed(rest_of_str.to_string())); 143 | } 144 | 145 | let node = logical::parser::parse_query(select_stmt, data_source.clone())?; 146 | let mut physical_plan_creator = logical::types::PhysicalPlanCreator::new(data_source); 147 | let (physical_plan, _variables) = node.physical(&mut physical_plan_creator)?; 148 | 149 | println!("Query Plan:"); 150 | println!("{:?}", physical_plan); 151 | Ok(()) 152 | } 153 | 154 | pub(crate) fn run(query_str: &str, data_source: common::types::DataSource, output_mode: OutputMode) -> AppResult<()> { 155 | let (rest_of_str, select_stmt) = syntax::parser::select_query(&query_str)?; 156 | if !rest_of_str.is_empty() { 157 | return Err(AppError::InputNotAllConsumed(rest_of_str.to_string())); 158 | } 159 | 160 | let node = logical::parser::parse_query(select_stmt, data_source.clone())?; 161 | let mut physical_plan_creator = logical::types::PhysicalPlanCreator::new(data_source); 162 | let (physical_plan, variables) = node.physical(&mut physical_plan_creator)?; 163 | 164 | let mut stream = physical_plan.get(variables)?; 165 | 166 | match output_mode { 167 | OutputMode::Table => { 168 | let mut table = Table::new(); 169 | 170 | while let Some(record) = stream.next()? { 171 | table.add_row(Row::new(record.to_row())); 172 | } 173 | table.printstd(); 174 | } 175 | OutputMode::Csv => { 176 | let mut wtr = Writer::from_writer(std::io::stdout()); 177 | while let Some(record) = stream.next()? { 178 | let csv_record = record.to_csv_record(); 179 | wtr.write_record(csv_record)?; 180 | } 181 | } 182 | OutputMode::Json => { 183 | let mut data = json::JsonValue::new_array(); 184 | while let Some(record) = stream.next()? { 185 | let mut obj = json::JsonValue::new_object(); 186 | for (key, val) in record.to_tuples() { 187 | match val { 188 | common::types::Value::Boolean(b) => { 189 | obj[key] = b.into(); 190 | } 191 | common::types::Value::DateTime(dt) => { 192 | obj[key] = dt.to_string().into(); 193 | } 194 | common::types::Value::Float(f) => { 195 | obj[key] = f.into_inner().into(); 196 | } 197 | common::types::Value::Host(h) => { 198 | obj[key] = h.to_string().into(); 199 | } 200 | common::types::Value::HttpRequest(h) => { 201 | obj[key] = h.to_string().into(); 202 | } 203 | common::types::Value::Int(i) => { 204 | obj[key] = i.into(); 205 | } 206 | common::types::Value::Null => { 207 | obj[key] = json::Null; 208 | } 209 | common::types::Value::String(s) => { 210 | obj[key] = s.into(); 211 | } 212 | common::types::Value::Missing => obj[key] = json::Null, 213 | common::types::Value::Object(_) => { 214 | // 215 | obj[key] = json::JsonValue::String("{ ... }".to_string()); 216 | } 217 | common::types::Value::Array(_) => { 218 | obj[key] = json::JsonValue::String("[ ... ]".to_string()); 219 | } 220 | } 221 | } 222 | 223 | data.push(obj)?; 224 | } 225 | let s = data.dump(); 226 | println!("{}", s); 227 | } 228 | } 229 | 230 | Ok(()) 231 | } 232 | 233 | #[cfg(test)] 234 | mod tests { 235 | use super::*; 236 | use std::fs::File; 237 | use std::io::Write; 238 | use tempfile::tempdir; 239 | 240 | #[test] 241 | fn test_run_explain_mode() { 242 | let query_str = "select * from it"; 243 | let dir = tempdir().unwrap(); 244 | let file_path = dir.path().join("log_for_test.log"); 245 | let file_format = "squid".to_string(); 246 | let table_name = "it".to_string(); 247 | let mut file = File::create(file_path.clone()).unwrap(); 248 | writeln!(file, r#"1515734740.494 1 [MASKEDIPADDRESS] TCP_DENIED/407 3922 CONNECT d.dropbox.com:443 - HIER_NONE/- text/html"#).unwrap(); 249 | file.sync_all().unwrap(); 250 | drop(file); 251 | 252 | let data_source = common::types::DataSource::File(file_path, file_format.clone(), table_name.clone()); 253 | let result = run(&*query_str, data_source, OutputMode::Csv); 254 | 255 | assert_eq!(result, Ok(())); 256 | 257 | dir.close().unwrap(); 258 | } 259 | 260 | #[test] 261 | fn test_run_real_flat_log() { 262 | let dir = tempdir().unwrap(); 263 | let file_path = dir.path().join("log_for_test.log"); 264 | let file_format = "elb".to_string(); 265 | let table_name = "it".to_string(); 266 | let mut file = File::create(file_path.clone()).unwrap(); 267 | writeln!(file, r#"2019-06-07T18:45:33.559871Z elb1 78.168.134.92:4586 10.0.0.215:80 0.000036 0.001035 0.000025 200 200 0 42355 "GET https://example.com:443/ HTTP/1.1" "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2"#).unwrap(); 268 | file.sync_all().unwrap(); 269 | drop(file); 270 | 271 | let data_source = common::types::DataSource::File(file_path, file_format.clone(), table_name.clone()); 272 | let result = run( 273 | r#"select t, sum(sent_bytes) as s from it group by time_bucket("5 seconds", timestamp) as t order by t asc limit 1"#, 274 | data_source.clone(), 275 | OutputMode::Csv, 276 | ); 277 | assert_eq!(result, Ok(())); 278 | 279 | let result = run( 280 | r#"select time_bucket("5 seconds", timestamp) as t, url_path_bucket(request, 1, "_") as s from it limit 1"#, 281 | data_source.clone(), 282 | OutputMode::Csv, 283 | ); 284 | assert_eq!(result, Ok(())); 285 | 286 | let result = run( 287 | r#"select time_bucket("5 seconds", timestamp) as t, percentile_disc(0.9) within group (order by backend_processing_time asc) as bps from it group by t"#, 288 | data_source.clone(), 289 | OutputMode::Csv, 290 | ); 291 | assert_eq!(result, Ok(())); 292 | 293 | let result = run( 294 | r#"select time_bucket("5 seconds", timestamp) as t, approx_percentile(0.9) within group (order by backend_processing_time asc) as bps from it group by t"#, 295 | data_source.clone(), 296 | OutputMode::Csv, 297 | ); 298 | assert_eq!(result, Ok(())); 299 | 300 | dir.close().unwrap(); 301 | } 302 | 303 | #[test] 304 | fn test_run_real_jsonl_log() { 305 | let dir = tempdir().unwrap(); 306 | let file_path = dir.path().join("log_for_test.log"); 307 | let file_format = "jsonl".to_string(); 308 | let table_name = "it".to_string(); 309 | let mut file = File::create(file_path.clone()).unwrap(); 310 | writeln!( 311 | file, 312 | r#"{{"a": 1, "b": "123", "d": [1, 2, 3], "e": {{"f": {{"g": 2}}}}}}"# 313 | ) 314 | .unwrap(); 315 | file.sync_all().unwrap(); 316 | drop(file); 317 | 318 | let data_source = common::types::DataSource::File(file_path, file_format.clone(), table_name.clone()); 319 | let result = run( 320 | r#"select b, e.f.g as x from it limit 1"#, 321 | data_source.clone(), 322 | OutputMode::Csv, 323 | ); 324 | assert_eq!(result, Ok(())); 325 | 326 | let result = run( 327 | r#"select b, count(e.f.g) as x from it group by b"#, 328 | data_source.clone(), 329 | OutputMode::Csv, 330 | ); 331 | assert_eq!(result, Ok(())); 332 | 333 | let result = run( 334 | r#"select x, count(*) as x from it group by d[0] as x"#, 335 | data_source.clone(), 336 | OutputMode::Csv, 337 | ); 338 | assert_eq!(result, Ok(())); 339 | 340 | dir.close().unwrap(); 341 | } 342 | } 343 | -------------------------------------------------------------------------------- /src/cli.yml: -------------------------------------------------------------------------------- 1 | name: logq 2 | version: "0.1.18" 3 | author: Paul Meng 4 | about: A web-server log file command line toolkit with SQL interface. 5 | subcommands: 6 | - query: 7 | about: select the data by query string 8 | args: 9 | - output: 10 | help: output format 11 | long: output 12 | takes_value: true 13 | - table: 14 | help: table to file mapping 15 | long: table 16 | takes_value: true 17 | - query: 18 | help: query string 19 | index: 1 20 | - explain: 21 | about: dump the query plan graph 22 | args: 23 | - query: 24 | help: query string 25 | index: 1 26 | - schema: 27 | about: show the schema for log file format 28 | args: 29 | - type: 30 | help: log format 31 | index: 1 32 | - help: 33 | about: help on the commands 34 | -------------------------------------------------------------------------------- /src/common/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod types; 2 | -------------------------------------------------------------------------------- /src/common/types.rs: -------------------------------------------------------------------------------- 1 | use crate::common; 2 | use crate::syntax::ast; 3 | use chrono; 4 | use linked_hash_map::LinkedHashMap; 5 | use ordered_float::OrderedFloat; 6 | use regex::Regex; 7 | use std::fmt; 8 | use std::path::PathBuf; 9 | use std::result; 10 | use url; 11 | 12 | lazy_static! { 13 | //FIXME: use different type for string hostname and Ipv4 14 | static ref HOST_REGEX: Regex = Regex::new(r#"([\.0-9a-zA-Z]+):([0-9]+)"#).unwrap(); 15 | static ref SPLIT_HTTP_LINE_REGEX: Regex = Regex::new(r#"[^\s"']+"#).unwrap(); 16 | static ref SPLIT_TIME_INTERVAL_LINE_REGEX: Regex = Regex::new(r#"[^\s"']+"#).unwrap(); 17 | } 18 | 19 | #[derive(PartialEq, Eq, Hash, Clone, Debug)] 20 | pub(crate) enum Value { 21 | Int(i32), 22 | Float(OrderedFloat), 23 | Boolean(bool), 24 | String(String), 25 | Null, 26 | DateTime(chrono::DateTime), 27 | HttpRequest(common::types::HttpRequest), 28 | Host(common::types::Host), 29 | Missing, 30 | Object(LinkedHashMap), 31 | Array(Vec), 32 | } 33 | 34 | pub(crate) type ParseHostResult = result::Result; 35 | 36 | #[derive(Fail, Debug)] 37 | pub(crate) enum ParseHostError { 38 | #[fail(display = "Parse Host Error")] 39 | ParseHost, 40 | #[fail(display = "{}", _0)] 41 | ParsePort(#[cause] std::num::ParseIntError), 42 | } 43 | 44 | impl From for ParseHostError { 45 | fn from(err: std::num::ParseIntError) -> ParseHostError { 46 | ParseHostError::ParsePort(err) 47 | } 48 | } 49 | 50 | pub(crate) type Hostname = String; 51 | pub(crate) type Port = u16; 52 | 53 | #[derive(PartialEq, Eq, Hash, Clone, Debug)] 54 | pub(crate) struct Host { 55 | pub(crate) hostname: Hostname, 56 | pub(crate) port: Port, 57 | } 58 | 59 | impl fmt::Display for Host { 60 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 61 | fmt.write_str(&*self.hostname)?; 62 | fmt.write_str(":")?; 63 | fmt.write_str(&*self.port.to_string())?; 64 | Ok(()) 65 | } 66 | } 67 | 68 | pub(crate) fn parse_host(s: &str) -> ParseHostResult { 69 | if let Some(cap) = HOST_REGEX.captures(s) { 70 | //FIXME: very simplified parsing. 71 | let hostname = cap.get(1).map_or("", |m| m.as_str()).to_string(); 72 | let port: u16 = cap.get(2).map_or("", |m| m.as_str()).parse::()?; 73 | 74 | let host = Host { hostname, port }; 75 | Ok(host) 76 | } else { 77 | Err(ParseHostError::ParseHost) 78 | } 79 | } 80 | 81 | pub(crate) type ParseHttpRequestResult = result::Result; 82 | 83 | #[derive(Fail, Debug)] 84 | pub(crate) enum ParseHttpRequestError { 85 | #[fail(display = "Parse Http Method Error")] 86 | ParseHttpMethod, 87 | #[fail(display = "{}", _0)] 88 | ParseUrl(#[cause] url::ParseError), 89 | #[fail(display = "Parse Http Version Error")] 90 | ParseHttpVersion, 91 | #[fail(display = "Missing Field")] 92 | MissingField, 93 | } 94 | 95 | impl From for ParseHttpRequestError { 96 | fn from(err: url::ParseError) -> ParseHttpRequestError { 97 | ParseHttpRequestError::ParseUrl(err) 98 | } 99 | } 100 | 101 | pub(crate) type HttpMethod = String; 102 | pub(crate) type HttpVersion = String; 103 | 104 | #[derive(PartialEq, Eq, Hash, Clone, Debug)] 105 | pub(crate) struct HttpRequest { 106 | pub(crate) http_method: String, 107 | pub(crate) url: url::Url, 108 | pub(crate) http_version: String, 109 | } 110 | 111 | impl fmt::Display for HttpRequest { 112 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 113 | fmt.write_str(&*self.http_method)?; 114 | fmt.write_str(" ")?; 115 | fmt.write_str(&*self.url.to_string())?; 116 | fmt.write_str(" ")?; 117 | fmt.write_str(&*self.http_version)?; 118 | Ok(()) 119 | } 120 | } 121 | 122 | pub(crate) fn parse_http_method(s: &str) -> ParseHttpRequestResult { 123 | if s == "GET" || s == "POST" || s == "DELETE" || s == "HEAD" || s == "PUT" || s == "PATCH" { 124 | Ok(s.to_string()) 125 | } else { 126 | Err(ParseHttpRequestError::ParseHttpMethod) 127 | } 128 | } 129 | 130 | pub(crate) fn parse_http_version(s: &str) -> ParseHttpRequestResult { 131 | if s == "HTTP/1.1" || s == "HTTP/1.0" || s == "HTTP/2.0" { 132 | Ok(s.to_string()) 133 | } else { 134 | Err(ParseHttpRequestError::ParseHttpVersion) 135 | } 136 | } 137 | 138 | pub(crate) fn parse_http_request(s: &str) -> ParseHttpRequestResult { 139 | let mut iter = SPLIT_HTTP_LINE_REGEX.find_iter(&s); 140 | 141 | let http_method_opt = if let Some(m) = iter.next() { 142 | let method = parse_http_method(m.as_str())?; 143 | Some(method) 144 | } else { 145 | None 146 | }; 147 | 148 | let url_opt = if let Some(m) = iter.next() { 149 | let url = url::Url::parse(m.as_str())?; 150 | Some(url) 151 | } else { 152 | None 153 | }; 154 | 155 | let http_version_opt = if let Some(m) = iter.next() { 156 | let version = parse_http_version(m.as_str())?; 157 | Some(version) 158 | } else { 159 | None 160 | }; 161 | 162 | if let (Some(http_method), Some(url), Some(http_version)) = (http_method_opt, url_opt, http_version_opt) { 163 | let request = HttpRequest { 164 | http_method, 165 | url, 166 | http_version, 167 | }; 168 | 169 | Ok(request) 170 | } else { 171 | Err(ParseHttpRequestError::MissingField) 172 | } 173 | } 174 | 175 | pub(crate) type ParseTimeIntervalResult = result::Result; 176 | 177 | #[derive(Fail, PartialEq, Eq, Clone, Debug)] 178 | pub(crate) enum ParseTimeIntervalError { 179 | #[fail(display = "Parse Integral Error: {}", _0)] 180 | ParseIntegral(#[cause] std::num::ParseIntError), 181 | #[fail(display = "Missing Part")] 182 | MissingPart, 183 | #[fail(display = "Unknown Time Unit")] 184 | UnknownTimeUnit, 185 | } 186 | 187 | impl From for ParseTimeIntervalError { 188 | fn from(err: std::num::ParseIntError) -> ParseTimeIntervalError { 189 | ParseTimeIntervalError::ParseIntegral(err) 190 | } 191 | } 192 | 193 | #[derive(Debug, PartialEq, Eq, Clone)] 194 | pub(crate) enum TimeIntervalUnit { 195 | Second, 196 | Minute, 197 | Hour, 198 | Day, 199 | Month, 200 | Year, 201 | } 202 | 203 | #[derive(Debug, PartialEq, Eq, Clone)] 204 | pub(crate) struct TimeInterval { 205 | pub(crate) n: u32, 206 | pub(crate) unit: TimeIntervalUnit, 207 | } 208 | 209 | pub(crate) type ParseDatePartResult = result::Result; 210 | 211 | #[derive(Fail, PartialEq, Eq, Clone, Debug)] 212 | pub(crate) enum ParseDatePartError { 213 | #[fail(display = "Unknown DatePart Unit")] 214 | UnknownDatePartUnit, 215 | } 216 | 217 | #[derive(Debug, PartialEq, Eq, Clone)] 218 | pub(crate) enum DatePartUnit { 219 | Second, 220 | Minute, 221 | Hour, 222 | Day, 223 | Month, 224 | Year, 225 | } 226 | 227 | pub(crate) fn parse_date_part_unit(s: &str) -> ParseDatePartResult { 228 | match s { 229 | "second" => Ok(DatePartUnit::Second), 230 | "minute" => Ok(DatePartUnit::Minute), 231 | "hour" => Ok(DatePartUnit::Hour), 232 | "day" => Ok(DatePartUnit::Day), 233 | "month" => Ok(DatePartUnit::Month), 234 | "year" => Ok(DatePartUnit::Year), 235 | _ => Err(ParseDatePartError::UnknownDatePartUnit), 236 | } 237 | } 238 | 239 | pub(crate) fn parse_time_interval_unit(s: &str, plural: bool) -> ParseTimeIntervalResult { 240 | if plural { 241 | match s { 242 | "seconds" => Ok(TimeIntervalUnit::Second), 243 | "minutes" => Ok(TimeIntervalUnit::Minute), 244 | "hours" => Ok(TimeIntervalUnit::Hour), 245 | "days" => Ok(TimeIntervalUnit::Day), 246 | "months" => Ok(TimeIntervalUnit::Month), 247 | "years" => Ok(TimeIntervalUnit::Year), 248 | _ => Err(ParseTimeIntervalError::UnknownTimeUnit), 249 | } 250 | } else { 251 | match s { 252 | "second" => Ok(TimeIntervalUnit::Second), 253 | "minute" => Ok(TimeIntervalUnit::Minute), 254 | "hour" => Ok(TimeIntervalUnit::Hour), 255 | "day" => Ok(TimeIntervalUnit::Day), 256 | "month" => Ok(TimeIntervalUnit::Month), 257 | "year" => Ok(TimeIntervalUnit::Year), 258 | _ => Err(ParseTimeIntervalError::UnknownTimeUnit), 259 | } 260 | } 261 | } 262 | 263 | pub(crate) fn parse_time_interval(s: &str) -> ParseTimeIntervalResult { 264 | let mut iter = SPLIT_TIME_INTERVAL_LINE_REGEX.find_iter(&s); 265 | 266 | let integral_opt = if let Some(m) = iter.next() { 267 | let integral = m.as_str().parse::()?; 268 | Some(integral) 269 | } else { 270 | None 271 | }; 272 | 273 | let time_unit_opt = if let (Some(m), Some(integral)) = (iter.next(), integral_opt) { 274 | let time_unit = parse_time_interval_unit(m.as_str(), integral > 1)?; 275 | Some(time_unit) 276 | } else { 277 | None 278 | }; 279 | 280 | if let (Some(integral), Some(time_unit)) = (integral_opt, time_unit_opt) { 281 | let interval = TimeInterval { 282 | n: integral, 283 | unit: time_unit, 284 | }; 285 | 286 | Ok(interval) 287 | } else { 288 | Err(ParseTimeIntervalError::MissingPart) 289 | } 290 | } 291 | 292 | pub(crate) type Tuple = Vec; 293 | pub(crate) type VariableName = String; 294 | pub(crate) type Variables = LinkedHashMap; 295 | 296 | pub(crate) fn empty_variables() -> Variables { 297 | Variables::default() 298 | } 299 | 300 | pub(crate) fn merge(left: &Variables, right: &Variables) -> Variables { 301 | left.iter().chain(right).map(|(k, v)| (k.clone(), v.clone())).collect() 302 | } 303 | 304 | #[derive(Debug, Clone, PartialEq, Eq)] 305 | pub(crate) struct IndexBinding { 306 | pub(crate) idx: usize, 307 | pub(crate) name: String, 308 | } 309 | 310 | #[derive(Debug, Clone, PartialEq, Eq)] 311 | pub(crate) struct Binding { 312 | pub(crate) path_expr: ast::PathExpr, 313 | pub(crate) name: String, 314 | pub(crate) idx_name: Option, 315 | } 316 | 317 | #[derive(Debug, Clone, PartialEq, Eq)] 318 | pub(crate) struct ParsingContext { 319 | pub(crate) table_name: String, 320 | } 321 | 322 | #[derive(Debug, Clone, PartialEq, Eq)] 323 | pub(crate) enum DataSource { 324 | File(PathBuf, String, String), 325 | Stdin(String, String), 326 | } 327 | 328 | #[cfg(test)] 329 | mod tests { 330 | use super::*; 331 | 332 | #[test] 333 | fn test_parse_time_interval() { 334 | let ans = parse_time_interval("1 minute").unwrap(); 335 | let expected = TimeInterval { 336 | n: 1, 337 | unit: TimeIntervalUnit::Minute, 338 | }; 339 | 340 | assert_eq!(expected, ans); 341 | 342 | let ans = parse_time_interval("3 minutes").unwrap(); 343 | let expected = TimeInterval { 344 | n: 3, 345 | unit: TimeIntervalUnit::Minute, 346 | }; 347 | 348 | assert_eq!(expected, ans); 349 | 350 | let ans = parse_time_interval("1 second").unwrap(); 351 | let expected = TimeInterval { 352 | n: 1, 353 | unit: TimeIntervalUnit::Second, 354 | }; 355 | 356 | assert_eq!(expected, ans); 357 | 358 | let ans = parse_time_interval("13 seconds").unwrap(); 359 | let expected = TimeInterval { 360 | n: 13, 361 | unit: TimeIntervalUnit::Second, 362 | }; 363 | 364 | assert_eq!(expected, ans); 365 | } 366 | } 367 | -------------------------------------------------------------------------------- /src/execution/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod datasource; 2 | pub mod stream; 3 | pub mod types; 4 | -------------------------------------------------------------------------------- /src/execution/stream.rs: -------------------------------------------------------------------------------- 1 | use super::datasource::RecordRead; 2 | use super::types::{Aggregate, Formula, Named, NamedAggregate, StreamResult}; 3 | use crate::common; 4 | use crate::common::types::{Tuple, Value, VariableName, Variables}; 5 | use crate::syntax::ast; 6 | use linked_hash_map::LinkedHashMap; 7 | use prettytable::Cell; 8 | use std::collections::hash_set; 9 | use std::collections::VecDeque; 10 | 11 | fn get_value_by_path_expr(path_expr: &ast::PathExpr, i: usize, variables: &Variables) -> Value { 12 | if i >= path_expr.path_segments.len() { 13 | return Value::Missing; 14 | } 15 | 16 | match &path_expr.path_segments[i] { 17 | ast::PathSegment::AttrName(attr_name) => { 18 | if let Some(val) = variables.get(attr_name) { 19 | if i + 1 == path_expr.path_segments.len() { 20 | return val.clone(); 21 | } else { 22 | match val { 23 | Value::Object(o) => get_value_by_path_expr(path_expr, i + 1, o as &Variables), 24 | _ => Value::Missing, 25 | } 26 | } 27 | } else { 28 | Value::Missing 29 | } 30 | } 31 | ast::PathSegment::ArrayIndex(attr_name, idx) => { 32 | if let Some(val) = variables.get(attr_name) { 33 | if i + 1 == path_expr.path_segments.len() { 34 | match val { 35 | Value::Array(a) => { 36 | let a = &a[*idx]; 37 | return a.clone(); 38 | } 39 | _ => Value::Missing, 40 | } 41 | } else { 42 | match val { 43 | Value::Array(a) => { 44 | let a = &a[*idx]; 45 | match a { 46 | Value::Object(o) => get_value_by_path_expr(path_expr, i + 1, o as &Variables), 47 | _ => Value::Missing, 48 | } 49 | } 50 | _ => Value::Missing, 51 | } 52 | } 53 | } else { 54 | Value::Missing 55 | } 56 | } 57 | } 58 | } 59 | 60 | #[derive(Debug, PartialEq, Eq, Clone)] 61 | pub(crate) struct Record { 62 | variables: LinkedHashMap, 63 | } 64 | 65 | impl Record { 66 | pub(crate) fn new(field_names: &Vec, data: Vec) -> Self { 67 | let mut variables = LinkedHashMap::default(); 68 | for (i, v) in data.into_iter().enumerate() { 69 | variables.insert(field_names[i].clone(), v); 70 | } 71 | 72 | Record { variables } 73 | } 74 | 75 | pub(crate) fn new_with_variables(variables: Variables) -> Self { 76 | Record { variables } 77 | } 78 | 79 | pub(crate) fn get(&self, field_name: &ast::PathExpr) -> Value { 80 | get_value_by_path_expr(field_name, 0, &self.variables) 81 | } 82 | 83 | pub(crate) fn alias(&mut self, bindings: &Vec) { 84 | for binding in bindings.iter() { 85 | let val = get_value_by_path_expr(&binding.path_expr, 0, &self.variables); 86 | self.variables.insert(binding.name.clone(), val); 87 | } 88 | } 89 | 90 | pub(crate) fn project(&self, field_names: &[VariableName]) -> Record { 91 | let mut variables = Variables::default(); 92 | for name in field_names { 93 | if let Some(v) = self.variables.get(name) { 94 | variables.insert(name.clone(), v.clone()); 95 | } 96 | } 97 | Record::new_with_variables(variables) 98 | } 99 | 100 | pub(crate) fn get_many(&self, field_names: &[ast::PathExpr]) -> Vec { 101 | let mut ret = Vec::with_capacity(field_names.len()); 102 | for name in field_names { 103 | let v = get_value_by_path_expr(name, 0, &self.variables); 104 | ret.push(v); 105 | } 106 | ret 107 | } 108 | 109 | pub(crate) fn to_variables(&self) -> &Variables { 110 | &self.variables as &Variables 111 | } 112 | 113 | pub(crate) fn to_tuples(&self) -> Vec<(VariableName, Value)> { 114 | self.variables.iter().map(|(k, v)| (k.clone(), v.clone())).collect() 115 | } 116 | 117 | pub(crate) fn to_row(&self) -> Vec { 118 | self.variables 119 | .values() 120 | .map(|val| match val { 121 | Value::String(s) => Cell::new(&*s), 122 | Value::Int(i) => Cell::new(&*i.to_string()), 123 | Value::Float(f) => Cell::new(&*f.to_string()), 124 | Value::Boolean(b) => Cell::new(&*b.to_string()), 125 | Value::Null => Cell::new(""), 126 | Value::DateTime(dt) => Cell::new(&*dt.to_string()), 127 | Value::HttpRequest(request) => Cell::new(&*request.to_string()), 128 | Value::Host(host) => Cell::new(&*host.to_string()), 129 | Value::Missing => Cell::new(""), 130 | Value::Object(_) => Cell::new("{...}"), 131 | Value::Array(_) => Cell::new("[...]"), 132 | }) 133 | .collect() 134 | } 135 | 136 | pub(crate) fn to_csv_record(&self) -> Vec { 137 | self.variables 138 | .values() 139 | .map(|val| match val { 140 | Value::String(s) => s.to_string(), 141 | Value::Int(i) => i.to_string(), 142 | Value::Float(f) => f.to_string(), 143 | Value::Boolean(b) => b.to_string(), 144 | Value::Null => "".to_string(), 145 | Value::DateTime(dt) => dt.to_string(), 146 | Value::HttpRequest(request) => request.to_string(), 147 | Value::Host(host) => host.to_string(), 148 | Value::Missing => "".to_string(), 149 | Value::Object(_) => "{...}".to_string(), 150 | Value::Array(_) => "[...]".to_string(), 151 | }) 152 | .collect() 153 | } 154 | } 155 | 156 | pub(crate) trait RecordStream { 157 | fn next(&mut self) -> StreamResult>; 158 | fn close(&self); 159 | } 160 | 161 | pub(crate) struct MapStream { 162 | pub(crate) named_list: Vec, 163 | pub(crate) variables: Variables, 164 | pub(crate) source: Box, 165 | } 166 | 167 | impl MapStream { 168 | pub(crate) fn new(named_list: Vec, variables: Variables, source: Box) -> Self { 169 | MapStream { 170 | named_list, 171 | variables, 172 | source, 173 | } 174 | } 175 | } 176 | 177 | impl RecordStream for MapStream { 178 | fn close(&self) { 179 | self.source.close(); 180 | } 181 | 182 | fn next(&mut self) -> StreamResult> { 183 | if let Some(record) = self.source.next()? { 184 | let variables = common::types::merge(&self.variables, record.to_variables()); 185 | 186 | let capacity = self.named_list.len(); 187 | let mut field_names = Vec::with_capacity(capacity); 188 | let mut data = Vec::with_capacity(capacity); 189 | for (idx, named) in self.named_list.iter().enumerate() { 190 | match named { 191 | Named::Expression(expr, name_opt) => { 192 | let name = if let Some(name) = name_opt { 193 | name.clone() 194 | } else { 195 | //Give the column a positional name if not provided. 196 | format!("_{}", idx) 197 | }; 198 | 199 | field_names.push(name); 200 | let v = expr.expression_value(&variables)?; 201 | data.push(v); 202 | } 203 | Named::Star => { 204 | for (k, v) in record.to_tuples().into_iter() { 205 | field_names.push(k); 206 | data.push(v); 207 | } 208 | } 209 | } 210 | } 211 | 212 | let record = Record::new(&field_names, data); 213 | Ok(Some(record)) 214 | } else { 215 | Ok(None) 216 | } 217 | } 218 | } 219 | 220 | pub(crate) struct LimitStream { 221 | curr: u32, 222 | row_count: u32, 223 | source: Box, 224 | } 225 | 226 | impl LimitStream { 227 | pub(crate) fn new(row_count: u32, source: Box) -> Self { 228 | LimitStream { 229 | curr: 0, 230 | row_count, 231 | source, 232 | } 233 | } 234 | } 235 | 236 | impl RecordStream for LimitStream { 237 | fn next(&mut self) -> StreamResult> { 238 | while let Some(record) = self.source.next()? { 239 | if self.curr < self.row_count { 240 | self.curr += 1; 241 | return Ok(Some(record)); 242 | } 243 | } 244 | 245 | Ok(None) 246 | } 247 | 248 | fn close(&self) { 249 | self.source.close(); 250 | } 251 | } 252 | 253 | pub(crate) struct FilterStream { 254 | formula: Formula, 255 | variables: Variables, 256 | source: Box, 257 | } 258 | 259 | impl FilterStream { 260 | pub(crate) fn new(formula: Formula, variables: Variables, source: Box) -> Self { 261 | FilterStream { 262 | formula, 263 | variables, 264 | source, 265 | } 266 | } 267 | } 268 | 269 | impl RecordStream for FilterStream { 270 | fn next(&mut self) -> StreamResult> { 271 | while let Some(record) = self.source.next()? { 272 | let variables = common::types::merge(&self.variables, record.to_variables()); 273 | let predicate = self.formula.evaluate(&variables)?; 274 | 275 | if predicate { 276 | return Ok(Some(record)); 277 | } 278 | } 279 | 280 | Ok(None) 281 | } 282 | 283 | fn close(&self) { 284 | self.source.close(); 285 | } 286 | } 287 | 288 | pub(crate) struct InMemoryStream { 289 | pub(crate) data: VecDeque, 290 | } 291 | 292 | impl InMemoryStream { 293 | pub(crate) fn new(data: VecDeque) -> InMemoryStream { 294 | InMemoryStream { data } 295 | } 296 | } 297 | 298 | impl RecordStream for InMemoryStream { 299 | fn next(&mut self) -> StreamResult> { 300 | if let Some(record) = self.data.pop_front() { 301 | Ok(Some(record)) 302 | } else { 303 | Ok(None) 304 | } 305 | } 306 | 307 | fn close(&self) {} 308 | } 309 | 310 | pub(crate) struct GroupByStream { 311 | keys: Vec, 312 | variables: Variables, 313 | aggregates: Vec, 314 | source: Box, 315 | group_iterator: Option>>, 316 | } 317 | 318 | impl<'a> GroupByStream { 319 | pub(crate) fn new( 320 | keys: Vec, 321 | variables: Variables, 322 | aggregates: Vec, 323 | source: Box, 324 | ) -> Self { 325 | GroupByStream { 326 | keys, 327 | variables, 328 | aggregates, 329 | source, 330 | group_iterator: None, 331 | } 332 | } 333 | } 334 | 335 | impl RecordStream for GroupByStream { 336 | fn next(&mut self) -> StreamResult> { 337 | if self.group_iterator.is_none() { 338 | let mut groups: hash_set::HashSet> = hash_set::HashSet::new(); 339 | while let Some(record) = self.source.next()? { 340 | let variables = common::types::merge(&self.variables, record.to_variables()); 341 | 342 | let key = if self.keys.is_empty() { 343 | None 344 | } else { 345 | Some(record.get_many(&self.keys)) 346 | }; 347 | 348 | groups.insert(key.clone()); 349 | for named_agg in self.aggregates.iter_mut() { 350 | match &mut named_agg.aggregate { 351 | Aggregate::GroupAs(ref mut inner, named) => { 352 | let val = match named { 353 | Named::Expression(_expr, _) => Value::Object(record.to_variables().clone()), 354 | Named::Star => { 355 | unreachable!(); 356 | } 357 | }; 358 | 359 | inner.add_record(&key, &val)?; 360 | } 361 | Aggregate::Avg(ref mut inner, named) => { 362 | let val = match named { 363 | Named::Expression(expr, _) => expr.expression_value(&variables)?, 364 | Named::Star => { 365 | unreachable!(); 366 | } 367 | }; 368 | 369 | inner.add_record(&key, &val)?; 370 | } 371 | Aggregate::Count(ref mut inner, named) => { 372 | match named { 373 | Named::Expression(expr, _) => { 374 | let val = expr.expression_value(&variables)?; 375 | inner.add_record(&key, &val)?; 376 | } 377 | Named::Star => { 378 | inner.add_row(key.clone())?; 379 | } 380 | }; 381 | } 382 | Aggregate::First(ref mut inner, named) => { 383 | match named { 384 | Named::Expression(expr, _) => { 385 | let val = expr.expression_value(&variables)?; 386 | inner.add_record(&key, &val)?; 387 | } 388 | Named::Star => { 389 | unreachable!(); 390 | } 391 | }; 392 | } 393 | Aggregate::Last(ref mut inner, named) => { 394 | match named { 395 | Named::Expression(expr, _) => { 396 | let val = expr.expression_value(&variables)?; 397 | inner.add_record(&key, &val)?; 398 | } 399 | Named::Star => { 400 | unreachable!(); 401 | } 402 | }; 403 | } 404 | Aggregate::Max(ref mut inner, named) => { 405 | match named { 406 | Named::Expression(expr, _) => { 407 | let val = expr.expression_value(&variables)?; 408 | inner.add_record(&key, &val)?; 409 | } 410 | Named::Star => { 411 | unreachable!(); 412 | } 413 | }; 414 | } 415 | Aggregate::Min(ref mut inner, named) => { 416 | match named { 417 | Named::Expression(expr, _) => { 418 | let val = expr.expression_value(&variables)?; 419 | inner.add_record(&key, &val)?; 420 | } 421 | Named::Star => { 422 | unreachable!(); 423 | } 424 | }; 425 | } 426 | Aggregate::Sum(ref mut inner, named) => { 427 | match named { 428 | Named::Expression(expr, _) => { 429 | let val = expr.expression_value(&variables)?; 430 | inner.add_record(&key, &val)?; 431 | } 432 | Named::Star => { 433 | unreachable!(); 434 | } 435 | }; 436 | } 437 | Aggregate::ApproxCountDistinct(ref mut inner, named) => { 438 | match named { 439 | Named::Expression(expr, _) => { 440 | let val = expr.expression_value(&variables)?; 441 | inner.add_record(&key, &val)?; 442 | } 443 | Named::Star => { 444 | unreachable!(); 445 | } 446 | }; 447 | } 448 | Aggregate::PercentileDisc(ref mut inner, column_name) => { 449 | let val = variables.get(column_name).unwrap(); 450 | inner.add_record(&key, val)?; 451 | } 452 | Aggregate::ApproxPercentile(ref mut inner, column_name) => { 453 | let val = variables.get(column_name).unwrap(); 454 | inner.add_record(&key, val)?; 455 | } 456 | } 457 | } 458 | } 459 | 460 | self.group_iterator = Some(groups.into_iter()); 461 | } 462 | 463 | let iter = self.group_iterator.as_mut().unwrap(); 464 | if let Some(key) = iter.next() { 465 | let mut values: Vec = Vec::new(); 466 | let mut fields: Vec = Vec::new(); 467 | 468 | if let Some(values_in_key) = &key { 469 | for (position_idx, k) in self.keys.iter().enumerate() { 470 | match k.path_segments.last().unwrap() { 471 | ast::PathSegment::AttrName(s) => { 472 | fields.push(s.clone()); 473 | } 474 | ast::PathSegment::ArrayIndex(_s, _idx) => { 475 | fields.push(format!("_{}", position_idx + 1)); 476 | } 477 | } 478 | } 479 | 480 | for v in values_in_key { 481 | values.push(v.clone()); 482 | } 483 | } 484 | 485 | for named_agg in self.aggregates.iter_mut() { 486 | if let Some(ref field_name) = named_agg.name_opt { 487 | fields.push(field_name.clone()); 488 | } else { 489 | let idx = fields.len() + 1; 490 | fields.push(format!("_{}", idx)); 491 | } 492 | let v = named_agg.aggregate.get_aggregated(&key)?; 493 | values.push(v); 494 | } 495 | 496 | let record = Record::new(&fields, values); 497 | Ok(Some(record)) 498 | } else { 499 | Ok(None) 500 | } 501 | } 502 | 503 | fn close(&self) { 504 | self.source.close(); 505 | } 506 | } 507 | 508 | pub(crate) struct ProjectionStream { 509 | pub(crate) source: Box, 510 | pub(crate) bindings: Vec, 511 | produced_records: Option>, 512 | idx: usize, 513 | } 514 | 515 | impl ProjectionStream { 516 | pub(crate) fn new(source: Box, bindings: Vec) -> Self { 517 | ProjectionStream { 518 | source, 519 | bindings, 520 | produced_records: None, 521 | idx: 0, 522 | } 523 | } 524 | } 525 | 526 | impl RecordStream for ProjectionStream { 527 | fn next(&mut self) -> StreamResult> { 528 | loop { 529 | if self.produced_records.is_none() { 530 | if let Some(mut record) = self.source.next()? { 531 | record.alias(&self.bindings); 532 | let binding_names: Vec = self.bindings.iter().map(|b| b.name.clone()).collect(); 533 | let projected_record = record.project(&binding_names); 534 | 535 | let mut produced_records: Vec = vec![]; 536 | let mut results: Vec> = vec![]; 537 | let mut keys: Vec = vec![]; 538 | 539 | let key_value_pairs: Vec<(String, Value)> = projected_record 540 | .to_variables() 541 | .iter() 542 | .map(|(k, v)| (k.clone(), v.clone())) 543 | .collect(); 544 | 545 | for (k, v) in key_value_pairs.iter() { 546 | keys.push(k.clone()); 547 | 548 | let mut push_idx = false; 549 | for binding in self.bindings.iter() { 550 | if binding.name.eq(k) { 551 | if let Some(idx_name) = binding.idx_name.as_ref() { 552 | keys.push(idx_name.clone()); 553 | push_idx = true; 554 | } 555 | } 556 | } 557 | 558 | match v { 559 | Value::Array(a) => { 560 | let mut new_results = vec![]; 561 | for (i, e) in a.iter().enumerate() { 562 | let mut replica = results.clone(); 563 | if replica.is_empty() { 564 | let mut v = vec![e.clone()]; 565 | 566 | if push_idx { 567 | v.push(Value::Int(i as i32)) 568 | } 569 | 570 | replica.push(v); 571 | } else { 572 | for row in replica.iter_mut() { 573 | row.push(e.clone()); 574 | 575 | if push_idx { 576 | row.push(Value::Int(i as i32)); 577 | } 578 | } 579 | } 580 | 581 | new_results.extend(replica.into_iter()); 582 | } 583 | 584 | results = new_results; 585 | } 586 | _ => { 587 | if results.is_empty() { 588 | let mut x = vec![v.clone()]; 589 | if push_idx { 590 | x.push(Value::Missing); 591 | } 592 | 593 | results.push(x); 594 | } else { 595 | for row in results.iter_mut() { 596 | row.push(v.clone()); 597 | 598 | if push_idx { 599 | row.push(Value::Missing); 600 | } 601 | } 602 | } 603 | } 604 | } 605 | } 606 | 607 | for result in results.iter() { 608 | let r = Record::new(&keys, result.clone()); 609 | produced_records.push(r); 610 | } 611 | 612 | if produced_records.is_empty() { 613 | return Ok(None); 614 | } else { 615 | let r: Record = produced_records[0].clone(); 616 | self.produced_records = Some(produced_records); 617 | self.idx = 1; 618 | 619 | return Ok(Some(r)); 620 | } 621 | } else { 622 | return Ok(None); 623 | } 624 | } else { 625 | let idx = self.idx; 626 | let records = self.produced_records.as_ref().unwrap(); 627 | 628 | if idx < records.len() { 629 | let record = records[idx].clone(); 630 | self.idx += 1; 631 | return Ok(Some(record)); 632 | } else { 633 | self.produced_records = None; 634 | } 635 | } 636 | } 637 | } 638 | 639 | fn close(&self) {} 640 | } 641 | 642 | pub(crate) struct LogFileStream { 643 | pub(crate) reader: Box, 644 | } 645 | 646 | impl LogFileStream { 647 | pub(crate) fn new(reader: Box) -> Self { 648 | LogFileStream { reader } 649 | } 650 | } 651 | 652 | impl RecordStream for LogFileStream { 653 | fn next(&mut self) -> StreamResult> { 654 | if let Some(record) = self.reader.read_record()? { 655 | Ok(Some(record)) 656 | } else { 657 | Ok(None) 658 | } 659 | } 660 | 661 | fn close(&self) {} 662 | } 663 | 664 | #[cfg(test)] 665 | mod tests { 666 | use super::*; 667 | use crate::common::types::Value; 668 | use crate::execution::stream::{Record, RecordStream}; 669 | use crate::execution::types; 670 | use crate::execution::types::Expression; 671 | 672 | #[test] 673 | fn test_limit_stream() { 674 | let mut variables: Variables = Variables::default(); 675 | variables.insert("const".to_string(), Value::String("example.com".to_string())); 676 | 677 | let mut records = VecDeque::new(); 678 | records.push_back(Record::new( 679 | &vec!["host".to_string(), "port".to_string()], 680 | vec![Value::String("example01.com".to_string()), Value::Int(8000)], 681 | )); 682 | records.push_back(Record::new( 683 | &vec!["host".to_string(), "port".to_string()], 684 | vec![Value::String("example.com".to_string()), Value::Int(8001)], 685 | )); 686 | records.push_back(Record::new( 687 | &vec!["host".to_string(), "port".to_string()], 688 | vec![Value::String("example01.com".to_string()), Value::Int(8002)], 689 | )); 690 | let stream = Box::new(InMemoryStream::new(records)); 691 | 692 | let mut limit_stream = LimitStream::new(1, stream); 693 | 694 | let mut result = Vec::new(); 695 | while let Some(n) = limit_stream.next().unwrap() { 696 | result.push(n); 697 | } 698 | 699 | let expected = vec![Record::new( 700 | &vec!["host".to_string(), "port".to_string()], 701 | vec![Value::String("example01.com".to_string()), Value::Int(8000)], 702 | )]; 703 | 704 | assert_eq!(expected, result); 705 | } 706 | 707 | #[test] 708 | fn test_filter_stream() { 709 | let path_expr_host = ast::PathExpr::new(vec![ast::PathSegment::AttrName("host".to_string())]); 710 | let path_expr_const = ast::PathExpr::new(vec![ast::PathSegment::AttrName("const".to_string())]); 711 | 712 | let left = Box::new(types::Expression::Variable(path_expr_host)); 713 | let right = Box::new(types::Expression::Variable(path_expr_const)); 714 | let rel = types::Relation::Equal; 715 | let predicate = types::Formula::Predicate(rel, left, right); 716 | 717 | let mut variables: Variables = Variables::default(); 718 | variables.insert("const".to_string(), Value::String("example.com".to_string())); 719 | 720 | let mut records = VecDeque::new(); 721 | records.push_back(Record::new( 722 | &vec!["host".to_string(), "port".to_string()], 723 | vec![Value::String("example01.com".to_string()), Value::Int(8000)], 724 | )); 725 | records.push_back(Record::new( 726 | &vec!["host".to_string(), "port".to_string()], 727 | vec![Value::String("example.com".to_string()), Value::Int(8001)], 728 | )); 729 | records.push_back(Record::new( 730 | &vec!["host".to_string(), "port".to_string()], 731 | vec![Value::String("example01.com".to_string()), Value::Int(8002)], 732 | )); 733 | let stream = Box::new(InMemoryStream::new(records)); 734 | 735 | let mut filtered_stream = FilterStream::new(predicate, variables, stream); 736 | 737 | let mut result = Vec::new(); 738 | while let Some(n) = filtered_stream.next().unwrap() { 739 | result.push(n); 740 | } 741 | 742 | let expected = vec![Record::new( 743 | &vec!["host".to_string(), "port".to_string()], 744 | vec![Value::String("example.com".to_string()), Value::Int(8001)], 745 | )]; 746 | 747 | assert_eq!(expected, result); 748 | } 749 | 750 | #[test] 751 | fn test_map_stream_with_star() { 752 | let named_list = vec![Named::Star]; 753 | 754 | let mut variables: Variables = Variables::default(); 755 | variables.insert("const".to_string(), Value::String("example.com".to_string())); 756 | 757 | let mut records = VecDeque::new(); 758 | records.push_back(Record::new( 759 | &vec!["host".to_string(), "port".to_string()], 760 | vec![Value::String("example01.com".to_string()), Value::Int(8000)], 761 | )); 762 | records.push_back(Record::new( 763 | &vec!["host".to_string(), "port".to_string()], 764 | vec![Value::String("example.com".to_string()), Value::Int(8001)], 765 | )); 766 | records.push_back(Record::new( 767 | &vec!["host".to_string(), "port".to_string()], 768 | vec![Value::String("example01.com".to_string()), Value::Int(8002)], 769 | )); 770 | let stream = Box::new(InMemoryStream::new(records)); 771 | 772 | let mut filtered_stream = MapStream::new(named_list, variables, stream); 773 | 774 | let mut result = Vec::new(); 775 | while let Some(n) = filtered_stream.next().unwrap() { 776 | result.push(n); 777 | } 778 | 779 | let expected = vec![ 780 | Record::new( 781 | &vec!["host".to_string(), "port".to_string()], 782 | vec![Value::String("example01.com".to_string()), Value::Int(8000)], 783 | ), 784 | Record::new( 785 | &vec!["host".to_string(), "port".to_string()], 786 | vec![Value::String("example.com".to_string()), Value::Int(8001)], 787 | ), 788 | Record::new( 789 | &vec!["host".to_string(), "port".to_string()], 790 | vec![Value::String("example01.com".to_string()), Value::Int(8002)], 791 | ), 792 | ]; 793 | 794 | assert_eq!(expected, result); 795 | } 796 | 797 | #[test] 798 | fn test_map_stream_with_names() { 799 | let path_expr_port = ast::PathExpr::new(vec![ast::PathSegment::AttrName("port".to_string())]); 800 | let named_list = vec![Named::Expression( 801 | Expression::Variable(path_expr_port), 802 | Some("port".to_string()), 803 | )]; 804 | 805 | let mut variables: Variables = Variables::default(); 806 | variables.insert("const".to_string(), Value::String("example.com".to_string())); 807 | 808 | let mut records = VecDeque::new(); 809 | records.push_back(Record::new( 810 | &vec!["host".to_string(), "port".to_string()], 811 | vec![Value::String("example01.com".to_string()), Value::Int(8000)], 812 | )); 813 | records.push_back(Record::new( 814 | &vec!["host".to_string(), "port".to_string()], 815 | vec![Value::String("example.com".to_string()), Value::Int(8001)], 816 | )); 817 | records.push_back(Record::new( 818 | &vec!["host".to_string(), "port".to_string()], 819 | vec![Value::String("example01.com".to_string()), Value::Int(8002)], 820 | )); 821 | let stream = Box::new(InMemoryStream::new(records)); 822 | 823 | let mut filtered_stream = MapStream::new(named_list, variables, stream); 824 | 825 | let mut result = Vec::new(); 826 | while let Some(n) = filtered_stream.next().unwrap() { 827 | result.push(n); 828 | } 829 | 830 | let expected = vec![ 831 | Record::new(&vec!["port".to_string()], vec![Value::Int(8000)]), 832 | Record::new(&vec!["port".to_string()], vec![Value::Int(8001)]), 833 | Record::new(&vec!["port".to_string()], vec![Value::Int(8002)]), 834 | ]; 835 | 836 | assert_eq!(expected, result); 837 | } 838 | } 839 | -------------------------------------------------------------------------------- /src/logical/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod parser; 2 | pub mod types; 3 | -------------------------------------------------------------------------------- /src/logical/types.rs: -------------------------------------------------------------------------------- 1 | use crate::common::types as common; 2 | use crate::common::types::{DataSource, VariableName}; 3 | use crate::execution::types as execution; 4 | use crate::syntax::ast; 5 | use crate::syntax::ast::PathExpr; 6 | use ordered_float::OrderedFloat; 7 | use std::result; 8 | 9 | pub(crate) type PhysicalResult = result::Result; 10 | 11 | #[derive(Fail, PartialEq, Eq, Debug)] 12 | pub enum PhysicalPlanError { 13 | #[fail(display = "Type Mismatch")] 14 | #[allow(dead_code)] 15 | TypeMisMatch, 16 | } 17 | 18 | #[derive(Debug, Clone, PartialEq, Eq)] 19 | pub(crate) enum Node { 20 | DataSource(DataSource, Vec), 21 | Filter(Box, Box), 22 | Map(Vec, Box), 23 | GroupBy(Vec, Vec, Box), 24 | Limit(u32, Box), 25 | OrderBy(Vec, Vec, Box), 26 | } 27 | 28 | impl Node { 29 | pub(crate) fn physical( 30 | &self, 31 | physical_plan_creator: &mut PhysicalPlanCreator, 32 | ) -> PhysicalResult<(Box, common::Variables)> { 33 | match self { 34 | Node::DataSource(data_source, bindings) => { 35 | let node = execution::Node::DataSource(data_source.clone(), bindings.clone()); 36 | let variables = common::empty_variables(); 37 | 38 | Ok((Box::new(node), variables)) 39 | } 40 | Node::Filter(formula, source) => { 41 | let (physical_formula, formula_variables) = formula.physical(physical_plan_creator)?; 42 | let (child, child_variables) = source.physical(physical_plan_creator)?; 43 | 44 | let return_variables = common::merge(&formula_variables, &child_variables); 45 | let filter = execution::Node::Filter(child, physical_formula); 46 | Ok((Box::new(filter), return_variables)) 47 | } 48 | Node::Map(expressions, source) => { 49 | let mut physical_expressions: Vec = Vec::new(); 50 | let mut total_expression_variables = common::empty_variables(); 51 | 52 | for expression in expressions.iter() { 53 | let (physical_expression, expression_variables) = expression.physical(physical_plan_creator)?; 54 | physical_expressions.push(*physical_expression); 55 | total_expression_variables = common::merge(&total_expression_variables, &expression_variables); 56 | } 57 | 58 | let (child, child_variables) = source.physical(physical_plan_creator)?; 59 | let return_variables = common::merge(&total_expression_variables, &child_variables); 60 | 61 | let node = execution::Node::Map(physical_expressions, child); 62 | 63 | Ok((Box::new(node), return_variables)) 64 | } 65 | Node::GroupBy(fields, named_aggergates, source) => { 66 | let mut variables = common::empty_variables(); 67 | 68 | let mut physical_aggregates = Vec::new(); 69 | for named_aggregate in named_aggergates.iter() { 70 | let (physical_aggregate, aggregate_variables) = named_aggregate.physical(physical_plan_creator)?; 71 | variables = common::merge(&variables, &aggregate_variables); 72 | physical_aggregates.push(physical_aggregate); 73 | } 74 | let (child, child_variables) = source.physical(physical_plan_creator)?; 75 | let return_variables = common::merge(&variables, &child_variables); 76 | 77 | let node = execution::Node::GroupBy(fields.clone(), physical_aggregates, child); 78 | 79 | Ok((Box::new(node), return_variables)) 80 | } 81 | Node::Limit(row_count, source) => { 82 | let variables = common::empty_variables(); 83 | let (child, child_variables) = source.physical(physical_plan_creator)?; 84 | let return_variables = common::merge(&variables, &child_variables); 85 | let node = execution::Node::Limit(*row_count, child); 86 | Ok((Box::new(node), return_variables)) 87 | } 88 | Node::OrderBy(column_names, orderings, source) => { 89 | let variables = common::empty_variables(); 90 | let (child, child_variables) = source.physical(physical_plan_creator)?; 91 | let return_variables = common::merge(&variables, &child_variables); 92 | 93 | let mut physical_orderings = Vec::new(); 94 | for ordering in orderings.iter() { 95 | let physical_ordering = ordering.physical()?; 96 | physical_orderings.push(physical_ordering); 97 | } 98 | 99 | let node = execution::Node::OrderBy(column_names.clone(), physical_orderings, child); 100 | Ok((Box::new(node), return_variables)) 101 | } 102 | } 103 | } 104 | } 105 | 106 | #[derive(Debug, Clone, PartialEq, Eq)] 107 | pub(crate) enum Named { 108 | Expression(Expression, Option), 109 | Star, 110 | } 111 | 112 | impl Named { 113 | pub(crate) fn physical( 114 | &self, 115 | physical_plan_creator: &mut PhysicalPlanCreator, 116 | ) -> PhysicalResult<(Box, common::Variables)> { 117 | match self { 118 | Named::Expression(expr, name) => { 119 | let (physical_expr, expr_variables) = expr.physical(physical_plan_creator)?; 120 | Ok(( 121 | Box::new(execution::Named::Expression(*physical_expr, name.clone())), 122 | expr_variables, 123 | )) 124 | } 125 | Named::Star => Ok((Box::new(execution::Named::Star), common::empty_variables())), 126 | } 127 | } 128 | } 129 | 130 | #[derive(Debug, Clone, PartialEq, Eq)] 131 | pub(crate) enum Expression { 132 | Constant(common::Value), 133 | Variable(ast::PathExpr), 134 | Logic(Box), 135 | Function(String, Vec), 136 | Branch(Box, Box, Option>), 137 | } 138 | 139 | impl Expression { 140 | pub(crate) fn physical( 141 | &self, 142 | physical_plan_creator: &mut PhysicalPlanCreator, 143 | ) -> PhysicalResult<(Box, common::Variables)> { 144 | match self { 145 | Expression::Constant(value) => { 146 | let constant_name = physical_plan_creator.new_constant_name(); 147 | let path_expr = ast::PathExpr::new(vec![ast::PathSegment::AttrName(constant_name.clone())]); 148 | let node = Box::new(execution::Expression::Variable(path_expr)); 149 | let mut variables = common::Variables::default(); 150 | variables.insert(constant_name, value.clone()); 151 | 152 | Ok((node, variables)) 153 | } 154 | Expression::Variable(name) => { 155 | let node = Box::new(execution::Expression::Variable(name.clone())); 156 | let variables = common::empty_variables(); 157 | 158 | Ok((node, variables)) 159 | } 160 | Expression::Logic(formula) => { 161 | let (expr, variables) = formula.physical(physical_plan_creator)?; 162 | Ok((Box::new(execution::Expression::Logic(expr)), variables)) 163 | } 164 | Expression::Function(name, arguments) => { 165 | let mut physical_args = Vec::new(); 166 | let mut variables = common::empty_variables(); 167 | 168 | for arg in arguments.iter() { 169 | let (physical_arg, physical_variables) = arg.physical(physical_plan_creator)?; 170 | physical_args.push(*physical_arg); 171 | variables = common::merge(&variables, &physical_variables); 172 | } 173 | 174 | Ok(( 175 | Box::new(execution::Expression::Function(name.clone(), physical_args)), 176 | variables, 177 | )) 178 | } 179 | Expression::Branch(condition, then_expr, else_expr) => { 180 | let mut variables = common::empty_variables(); 181 | 182 | let (condition_expr, condition_ariables) = condition.physical(physical_plan_creator)?; 183 | variables = common::merge(&variables, &condition_ariables); 184 | 185 | let (then_expr, then_variables) = then_expr.physical(physical_plan_creator)?; 186 | variables = common::merge(&variables, &then_variables); 187 | 188 | if let Some(e) = else_expr { 189 | let (else_expr, else_ariables) = e.physical(physical_plan_creator)?; 190 | variables = common::merge(&variables, &else_ariables); 191 | Ok(( 192 | Box::new(execution::Expression::Branch( 193 | condition_expr, 194 | then_expr, 195 | Some(else_expr), 196 | )), 197 | variables, 198 | )) 199 | } else { 200 | Ok(( 201 | Box::new(execution::Expression::Branch(condition_expr, then_expr, None)), 202 | variables, 203 | )) 204 | } 205 | } 206 | } 207 | } 208 | } 209 | 210 | #[derive(Debug, Clone, PartialEq, Eq)] 211 | pub(crate) enum Formula { 212 | InfixOperator(LogicInfixOp, Box, Box), 213 | PrefixOperator(LogicPrefixOp, Box), 214 | Constant(bool), 215 | Predicate(Relation, Box, Box), 216 | } 217 | 218 | #[derive(Debug, Clone, PartialEq, Eq)] 219 | pub(crate) enum LogicInfixOp { 220 | And, 221 | Or, 222 | } 223 | 224 | #[derive(Debug, Clone, PartialEq, Eq)] 225 | pub(crate) enum LogicPrefixOp { 226 | Not, 227 | } 228 | 229 | impl Formula { 230 | pub(crate) fn physical( 231 | &self, 232 | physical_plan_creator: &mut PhysicalPlanCreator, 233 | ) -> PhysicalResult<(Box, common::Variables)> { 234 | match self { 235 | Formula::InfixOperator(op, left_formula, right_formula) => { 236 | let (left, left_variables) = left_formula.physical(physical_plan_creator)?; 237 | let (right, right_variables) = right_formula.physical(physical_plan_creator)?; 238 | let return_variables = common::merge(&left_variables, &right_variables); 239 | 240 | match op { 241 | LogicInfixOp::And => Ok((Box::new(execution::Formula::And(left, right)), return_variables)), 242 | LogicInfixOp::Or => Ok((Box::new(execution::Formula::Or(left, right)), return_variables)), 243 | } 244 | } 245 | Formula::PrefixOperator(op, child_formula) => match op { 246 | LogicPrefixOp::Not => { 247 | let (child, child_variables) = child_formula.physical(physical_plan_creator)?; 248 | Ok((Box::new(execution::Formula::Not(child)), child_variables)) 249 | } 250 | }, 251 | Formula::Constant(b) => { 252 | let node = Box::new(execution::Formula::Constant(*b)); 253 | let variables = common::Variables::default(); 254 | 255 | Ok((node, variables)) 256 | } 257 | Formula::Predicate(relation, left_expr, right_expr) => { 258 | let (left, left_variables) = left_expr.physical(physical_plan_creator)?; 259 | let (right, right_variables) = right_expr.physical(physical_plan_creator)?; 260 | let physical_relation = relation.physical()?; 261 | 262 | let return_variables = common::merge(&left_variables, &right_variables); 263 | Ok(( 264 | Box::new(execution::Formula::Predicate(physical_relation, left, right)), 265 | return_variables, 266 | )) 267 | } 268 | } 269 | } 270 | } 271 | 272 | #[derive(Debug, Clone, PartialEq, Eq)] 273 | pub(crate) struct PhysicalPlanCreator { 274 | counter: u32, 275 | data_source: DataSource, 276 | } 277 | 278 | impl PhysicalPlanCreator { 279 | pub(crate) fn new(data_source: DataSource) -> Self { 280 | PhysicalPlanCreator { 281 | counter: 0, 282 | data_source, 283 | } 284 | } 285 | 286 | pub(crate) fn new_constant_name(&mut self) -> VariableName { 287 | let constant_name = format!("const_{:09}", self.counter); 288 | self.counter += 1; 289 | constant_name 290 | } 291 | } 292 | 293 | #[derive(Debug, Clone, PartialEq, Eq)] 294 | pub(crate) struct NamedAggregate { 295 | pub(crate) aggregate: Aggregate, 296 | pub(crate) name_opt: Option, 297 | } 298 | 299 | impl NamedAggregate { 300 | pub(crate) fn new(aggregate: Aggregate, name_opt: Option) -> Self { 301 | NamedAggregate { aggregate, name_opt } 302 | } 303 | 304 | pub(crate) fn physical( 305 | &self, 306 | physical_plan_creator: &mut PhysicalPlanCreator, 307 | ) -> PhysicalResult<(execution::NamedAggregate, common::Variables)> { 308 | let (physical_aggregate, expr_variables) = self.aggregate.physical(physical_plan_creator)?; 309 | Ok(( 310 | execution::NamedAggregate::new(physical_aggregate, self.name_opt.clone()), 311 | expr_variables, 312 | )) 313 | } 314 | } 315 | 316 | #[derive(Debug, Clone, PartialEq, Eq)] 317 | pub(crate) enum Aggregate { 318 | Avg(Named), 319 | Count(Named), 320 | First(Named), 321 | Last(Named), 322 | Max(Named), 323 | Min(Named), 324 | Sum(Named), 325 | ApproxCountDistinct(Named), 326 | PercentileDisc(OrderedFloat, ast::PathExpr, Ordering), 327 | ApproxPercentile(OrderedFloat, ast::PathExpr, Ordering), 328 | GroupAsAggregate(Named), 329 | } 330 | 331 | impl Aggregate { 332 | pub(crate) fn physical( 333 | &self, 334 | physical_plan_creator: &mut PhysicalPlanCreator, 335 | ) -> PhysicalResult<(execution::Aggregate, common::Variables)> { 336 | match self { 337 | Aggregate::GroupAsAggregate(named) => { 338 | let mut variables = common::empty_variables(); 339 | 340 | let physical_named = match named { 341 | Named::Expression(expr, name) => { 342 | let (physical_expr, expr_variables) = expr.physical(physical_plan_creator)?; 343 | variables = common::merge(&variables, &expr_variables); 344 | execution::Named::Expression(*physical_expr, name.clone()) 345 | } 346 | Named::Star => { 347 | unreachable!(); 348 | } 349 | }; 350 | 351 | let group_as_aggregate = execution::GroupAsAggregate::new(); 352 | let aggregate = execution::Aggregate::GroupAs(group_as_aggregate, physical_named); 353 | Ok((aggregate, variables)) 354 | } 355 | Aggregate::Avg(named) => { 356 | let mut variables = common::empty_variables(); 357 | 358 | let physical_named = match named { 359 | Named::Expression(expr, name) => { 360 | let (physical_expr, expr_variables) = expr.physical(physical_plan_creator)?; 361 | variables = common::merge(&variables, &expr_variables); 362 | execution::Named::Expression(*physical_expr, name.clone()) 363 | } 364 | Named::Star => execution::Named::Star, 365 | }; 366 | 367 | let avg_aggregate = execution::AvgAggregate::new(); 368 | let aggregate = execution::Aggregate::Avg(avg_aggregate, physical_named); 369 | Ok((aggregate, variables)) 370 | } 371 | Aggregate::Count(named) => { 372 | let mut variables = common::empty_variables(); 373 | 374 | let physical_named = match named { 375 | Named::Expression(expr, name) => { 376 | let (physical_expr, expr_variables) = expr.physical(physical_plan_creator)?; 377 | variables = common::merge(&variables, &expr_variables); 378 | execution::Named::Expression(*physical_expr, name.clone()) 379 | } 380 | Named::Star => execution::Named::Star, 381 | }; 382 | 383 | let count_aggregate = execution::CountAggregate::new(); 384 | let aggregate = execution::Aggregate::Count(count_aggregate, physical_named); 385 | Ok((aggregate, variables)) 386 | } 387 | Aggregate::Sum(named) => { 388 | let mut variables = common::empty_variables(); 389 | 390 | let physical_named = match named { 391 | Named::Expression(expr, name) => { 392 | let (physical_expr, expr_variables) = expr.physical(physical_plan_creator)?; 393 | variables = common::merge(&variables, &expr_variables); 394 | execution::Named::Expression(*physical_expr, name.clone()) 395 | } 396 | Named::Star => execution::Named::Star, 397 | }; 398 | 399 | let sum_aggregate = execution::SumAggregate::new(); 400 | let aggregate = execution::Aggregate::Sum(sum_aggregate, physical_named); 401 | Ok((aggregate, variables)) 402 | } 403 | Aggregate::First(named) => { 404 | let mut variables = common::empty_variables(); 405 | 406 | let physical_named = match named { 407 | Named::Expression(expr, name) => { 408 | let (physical_expr, expr_variables) = expr.physical(physical_plan_creator)?; 409 | variables = common::merge(&variables, &expr_variables); 410 | execution::Named::Expression(*physical_expr, name.clone()) 411 | } 412 | Named::Star => execution::Named::Star, 413 | }; 414 | 415 | let first_aggregate = execution::FirstAggregate::new(); 416 | let aggregate = execution::Aggregate::First(first_aggregate, physical_named); 417 | Ok((aggregate, variables)) 418 | } 419 | Aggregate::Last(named) => { 420 | let mut variables = common::empty_variables(); 421 | 422 | let physical_named = match named { 423 | Named::Expression(expr, name) => { 424 | let (physical_expr, expr_variables) = expr.physical(physical_plan_creator)?; 425 | variables = common::merge(&variables, &expr_variables); 426 | execution::Named::Expression(*physical_expr, name.clone()) 427 | } 428 | Named::Star => execution::Named::Star, 429 | }; 430 | 431 | let last_aggregate = execution::LastAggregate::new(); 432 | let aggregate = execution::Aggregate::Last(last_aggregate, physical_named); 433 | Ok((aggregate, variables)) 434 | } 435 | Aggregate::Min(named) => { 436 | let mut variables = common::empty_variables(); 437 | 438 | let physical_named = match named { 439 | Named::Expression(expr, name) => { 440 | let (physical_expr, expr_variables) = expr.physical(physical_plan_creator)?; 441 | variables = common::merge(&variables, &expr_variables); 442 | execution::Named::Expression(*physical_expr, name.clone()) 443 | } 444 | Named::Star => execution::Named::Star, 445 | }; 446 | 447 | let min_aggregate = execution::MinAggregate::new(); 448 | let aggregate = execution::Aggregate::Min(min_aggregate, physical_named); 449 | Ok((aggregate, variables)) 450 | } 451 | Aggregate::Max(named) => { 452 | let mut variables = common::empty_variables(); 453 | 454 | let physical_named = match named { 455 | Named::Expression(expr, name) => { 456 | let (physical_expr, expr_variables) = expr.physical(physical_plan_creator)?; 457 | variables = common::merge(&variables, &expr_variables); 458 | execution::Named::Expression(*physical_expr, name.clone()) 459 | } 460 | Named::Star => execution::Named::Star, 461 | }; 462 | 463 | let max_aggregate = execution::MaxAggregate::new(); 464 | let aggregate = execution::Aggregate::Max(max_aggregate, physical_named); 465 | Ok((aggregate, variables)) 466 | } 467 | Aggregate::ApproxCountDistinct(named) => { 468 | let mut variables = common::empty_variables(); 469 | 470 | let physical_named = match named { 471 | Named::Expression(expr, name) => { 472 | let (physical_expr, expr_variables) = expr.physical(physical_plan_creator)?; 473 | variables = common::merge(&variables, &expr_variables); 474 | execution::Named::Expression(*physical_expr, name.clone()) 475 | } 476 | Named::Star => execution::Named::Star, 477 | }; 478 | 479 | let approx_count_distinct_aggregate = execution::ApproxCountDistinctAggregate::new(); 480 | let aggregate = 481 | execution::Aggregate::ApproxCountDistinct(approx_count_distinct_aggregate, physical_named); 482 | Ok((aggregate, variables)) 483 | } 484 | Aggregate::PercentileDisc(percentile, column_name, ordering) => { 485 | let variables = common::empty_variables(); 486 | let physical_ordering = ordering.physical()?; 487 | 488 | let percentile_disc_aggregate = execution::PercentileDiscAggregate::new(*percentile, physical_ordering); 489 | let aggregate = 490 | execution::Aggregate::PercentileDisc(percentile_disc_aggregate, column_name.unwrap_last()); 491 | Ok((aggregate, variables)) 492 | } 493 | Aggregate::ApproxPercentile(percentile, column_name, ordering) => { 494 | let variables = common::empty_variables(); 495 | let physical_ordering = ordering.physical()?; 496 | 497 | let approx_percentile_aggregate = 498 | execution::ApproxPercentileAggregate::new(*percentile, physical_ordering); 499 | let aggregate = 500 | execution::Aggregate::ApproxPercentile(approx_percentile_aggregate, column_name.unwrap_last()); 501 | Ok((aggregate, variables)) 502 | } 503 | } 504 | } 505 | } 506 | 507 | #[derive(Debug, Clone, PartialEq, Eq)] 508 | pub(crate) enum Relation { 509 | Equal, 510 | NotEqual, 511 | MoreThan, 512 | LessThan, 513 | GreaterEqual, 514 | LessEqual, 515 | } 516 | 517 | impl Relation { 518 | pub(crate) fn physical(&self) -> PhysicalResult { 519 | match self { 520 | Relation::Equal => Ok(execution::Relation::Equal), 521 | Relation::NotEqual => Ok(execution::Relation::NotEqual), 522 | Relation::MoreThan => Ok(execution::Relation::MoreThan), 523 | Relation::LessThan => Ok(execution::Relation::LessThan), 524 | Relation::GreaterEqual => Ok(execution::Relation::GreaterEqual), 525 | Relation::LessEqual => Ok(execution::Relation::LessEqual), 526 | } 527 | } 528 | } 529 | 530 | #[derive(Debug, PartialEq, Eq, Clone)] 531 | pub(crate) enum Ordering { 532 | Asc, 533 | Desc, 534 | } 535 | 536 | impl Ordering { 537 | pub(crate) fn physical(&self) -> PhysicalResult { 538 | match self { 539 | Ordering::Asc => Ok(execution::Ordering::Asc), 540 | Ordering::Desc => Ok(execution::Ordering::Desc), 541 | } 542 | } 543 | } 544 | 545 | #[cfg(test)] 546 | mod test { 547 | use super::*; 548 | use crate::syntax::ast::{PathExpr, PathSegment}; 549 | 550 | #[test] 551 | fn test_relation_gen_physical() { 552 | let rel = Relation::Equal; 553 | let ans = rel.physical().unwrap(); 554 | let expected = execution::Relation::Equal; 555 | 556 | assert_eq!(expected, ans); 557 | } 558 | 559 | #[test] 560 | fn test_formula_gen_physical() { 561 | let formula = Formula::InfixOperator( 562 | LogicInfixOp::And, 563 | Box::new(Formula::Constant(true)), 564 | Box::new(Formula::Constant(false)), 565 | ); 566 | let mut physical_plan_creator = 567 | PhysicalPlanCreator::new(DataSource::Stdin("jsonl".to_string(), "it".to_string())); 568 | let (physical_formula, variables) = formula.physical(&mut physical_plan_creator).unwrap(); 569 | let expected_formula = execution::Formula::And( 570 | Box::new(execution::Formula::Constant(true)), 571 | Box::new(execution::Formula::Constant(false)), 572 | ); 573 | 574 | let expected_variables = common::Variables::default(); 575 | 576 | assert_eq!(expected_formula, *physical_formula); 577 | assert_eq!(expected_variables, variables); 578 | } 579 | 580 | #[test] 581 | fn test_expression_gen_physical() { 582 | let path_expr_const = PathExpr::new(vec![PathSegment::AttrName("const_000000000".to_string())]); 583 | 584 | let expr = Expression::Constant(common::Value::Int(1)); 585 | let mut physical_plan_creator = 586 | PhysicalPlanCreator::new(DataSource::Stdin("jsonl".to_string(), "it".to_string())); 587 | let (physical_expr, variables) = expr.physical(&mut physical_plan_creator).unwrap(); 588 | let expected_formula = execution::Expression::Variable(path_expr_const.clone()); 589 | 590 | let mut expected_variables = common::Variables::default(); 591 | expected_variables.insert("const_000000000".to_string(), common::Value::Int(1)); 592 | assert_eq!(expected_formula, *physical_expr); 593 | assert_eq!(expected_variables, variables); 594 | } 595 | 596 | #[test] 597 | fn test_filter_with_map_gen_physical() { 598 | let path_expr_a = PathExpr::new(vec![PathSegment::AttrName("a".to_string())]); 599 | let path_expr_b = PathExpr::new(vec![PathSegment::AttrName("b".to_string())]); 600 | let path_expr_const = PathExpr::new(vec![PathSegment::AttrName("const_000000000".to_string())]); 601 | 602 | let filtered_formula = Formula::Predicate( 603 | Relation::Equal, 604 | Box::new(Expression::Variable(path_expr_a.clone())), 605 | Box::new(Expression::Constant(common::Value::Int(1))), 606 | ); 607 | 608 | let path_expr = PathExpr::new(vec![PathSegment::AttrName("it".to_string())]); 609 | let _binding = common::Binding { 610 | path_expr, 611 | name: "e".to_string(), 612 | idx_name: None, 613 | }; 614 | 615 | let filter = Node::Filter( 616 | Box::new(filtered_formula), 617 | Box::new(Node::Map( 618 | vec![ 619 | Named::Expression(Expression::Variable(path_expr_a.clone()), Some("a".to_string())), 620 | Named::Expression(Expression::Variable(path_expr_b.clone()), Some("b".to_string())), 621 | ], 622 | Box::new(Node::DataSource( 623 | DataSource::Stdin("jsonl".to_string(), "it".to_string()), 624 | vec![], 625 | )), 626 | )), 627 | ); 628 | 629 | let mut physical_plan_creator = 630 | PhysicalPlanCreator::new(DataSource::Stdin("jsonl".to_string(), "it".to_string())); 631 | let (physical_formula, variables) = filter.physical(&mut physical_plan_creator).unwrap(); 632 | 633 | let expected_filtered_formula = execution::Formula::Predicate( 634 | execution::Relation::Equal, 635 | Box::new(execution::Expression::Variable(path_expr_a.clone())), 636 | Box::new(execution::Expression::Variable(path_expr_const.clone())), 637 | ); 638 | 639 | let path_expr = PathExpr::new(vec![PathSegment::AttrName("it".to_string())]); 640 | let _binding = common::Binding { 641 | path_expr, 642 | name: "e".to_string(), 643 | idx_name: None, 644 | }; 645 | let expected_source = execution::Node::Map( 646 | vec![ 647 | execution::Named::Expression( 648 | execution::Expression::Variable(path_expr_a.clone()), 649 | Some("a".to_string()), 650 | ), 651 | execution::Named::Expression( 652 | execution::Expression::Variable(path_expr_b.clone()), 653 | Some("b".to_string()), 654 | ), 655 | ], 656 | Box::new(execution::Node::DataSource( 657 | DataSource::Stdin("jsonl".to_string(), "it".to_string()), 658 | vec![], 659 | )), 660 | ); 661 | 662 | let expected_filter = execution::Node::Filter(Box::new(expected_source), Box::new(expected_filtered_formula)); 663 | 664 | let mut expected_variables = common::Variables::default(); 665 | expected_variables.insert("const_000000000".to_string(), common::Value::Int(1)); 666 | 667 | assert_eq!(expected_filter, *physical_formula); 668 | assert_eq!(expected_variables, variables); 669 | } 670 | 671 | #[test] 672 | fn test_group_by_gen_physical() { 673 | let path_expr_a = PathExpr::new(vec![PathSegment::AttrName("a".to_string())]); 674 | let path_expr_b = PathExpr::new(vec![PathSegment::AttrName("b".to_string())]); 675 | let path_expr_const = PathExpr::new(vec![PathSegment::AttrName("const_000000000".to_string())]); 676 | 677 | let filtered_formula = Formula::Predicate( 678 | Relation::Equal, 679 | Box::new(Expression::Variable(path_expr_a.clone())), 680 | Box::new(Expression::Constant(common::Value::Int(1))), 681 | ); 682 | 683 | let path_expr = PathExpr::new(vec![PathSegment::AttrName("it".to_string())]); 684 | let _binding = common::Binding { 685 | path_expr, 686 | name: "e".to_string(), 687 | idx_name: None, 688 | }; 689 | let filter = Node::Filter( 690 | Box::new(filtered_formula), 691 | Box::new(Node::Map( 692 | vec![ 693 | Named::Expression(Expression::Variable(path_expr_a.clone()), Some("a".to_string())), 694 | Named::Expression(Expression::Variable(path_expr_b.clone()), Some("b".to_string())), 695 | ], 696 | Box::new(Node::DataSource( 697 | DataSource::Stdin("jsonl".to_string(), "it".to_string()), 698 | vec![], 699 | )), 700 | )), 701 | ); 702 | 703 | let named_aggregates = vec![ 704 | NamedAggregate::new( 705 | Aggregate::Avg(Named::Expression( 706 | Expression::Variable(path_expr_a.clone()), 707 | Some("a".to_string()), 708 | )), 709 | None, 710 | ), 711 | NamedAggregate::new( 712 | Aggregate::Count(Named::Expression( 713 | Expression::Variable(path_expr_b.clone()), 714 | Some("b".to_string()), 715 | )), 716 | None, 717 | ), 718 | ]; 719 | 720 | let fields = vec![path_expr_b.clone()]; 721 | let group_by = Node::GroupBy(fields, named_aggregates, Box::new(filter)); 722 | 723 | let mut physical_plan_creator = 724 | PhysicalPlanCreator::new(DataSource::Stdin("jsonl".to_string(), "it".to_string())); 725 | let (physical_formula, variables) = group_by.physical(&mut physical_plan_creator).unwrap(); 726 | 727 | let expected_filtered_formula = execution::Formula::Predicate( 728 | execution::Relation::Equal, 729 | Box::new(execution::Expression::Variable(path_expr_a.clone())), 730 | Box::new(execution::Expression::Variable(path_expr_const.clone())), 731 | ); 732 | 733 | let path_expr = PathExpr::new(vec![PathSegment::AttrName("it".to_string())]); 734 | let _binding = common::Binding { 735 | path_expr, 736 | name: "e".to_string(), 737 | idx_name: None, 738 | }; 739 | 740 | let expected_source = execution::Node::Map( 741 | vec![ 742 | execution::Named::Expression( 743 | execution::Expression::Variable(path_expr_a.clone()), 744 | Some("a".to_string()), 745 | ), 746 | execution::Named::Expression( 747 | execution::Expression::Variable(path_expr_b.clone()), 748 | Some("b".to_string()), 749 | ), 750 | ], 751 | Box::new(execution::Node::DataSource( 752 | DataSource::Stdin("jsonl".to_string(), "it".to_string()), 753 | vec![], 754 | )), 755 | ); 756 | 757 | let expected_filter = execution::Node::Filter(Box::new(expected_source), Box::new(expected_filtered_formula)); 758 | let expected_group_by = execution::Node::GroupBy( 759 | vec![path_expr_b.clone()], 760 | vec![ 761 | execution::NamedAggregate::new( 762 | execution::Aggregate::Avg( 763 | execution::AvgAggregate::new(), 764 | execution::Named::Expression( 765 | execution::Expression::Variable(path_expr_a.clone()), 766 | Some("a".to_string()), 767 | ), 768 | ), 769 | None, 770 | ), 771 | execution::NamedAggregate::new( 772 | execution::Aggregate::Count( 773 | execution::CountAggregate::new(), 774 | execution::Named::Expression( 775 | execution::Expression::Variable(path_expr_b.clone()), 776 | Some("b".to_string()), 777 | ), 778 | ), 779 | None, 780 | ), 781 | ], 782 | Box::new(expected_filter), 783 | ); 784 | 785 | let mut expected_variables = common::Variables::default(); 786 | expected_variables.insert("const_000000000".to_string(), common::Value::Int(1)); 787 | 788 | assert_eq!(expected_group_by, *physical_formula); 789 | assert_eq!(expected_variables, variables); 790 | } 791 | } 792 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate failure; 3 | extern crate chrono; 4 | extern crate nom; 5 | extern crate prettytable; 6 | #[macro_use] 7 | extern crate lazy_static; 8 | extern crate pdatastructs; 9 | 10 | mod app; 11 | mod common; 12 | mod execution; 13 | mod logical; 14 | mod syntax; 15 | 16 | use crate::app::AppError; 17 | use clap::load_yaml; 18 | use clap::App; 19 | use prettytable::{Cell, Row, Table}; 20 | use regex::Regex; 21 | use std::path::Path; 22 | use std::str::FromStr; 23 | 24 | lazy_static! { 25 | //FIXME: use different type for string hostname and Ipv4 26 | static ref TABLE_SPEC_REGEX: Regex = Regex::new(r#"([0-9a-zA-Z]+):([a-zA-Z]+)=([^=\s"':]+)"#).unwrap(); 27 | } 28 | 29 | fn main() { 30 | let yaml = load_yaml!("cli.yml"); 31 | let app_m = App::from_yaml(yaml).get_matches(); 32 | 33 | match app_m.subcommand() { 34 | ("query", Some(sub_m)) => { 35 | if let Some(query_str) = sub_m.value_of("query") { 36 | let lower_case_query_str = query_str.to_ascii_lowercase(); 37 | let output_mode = if let Some(output_format) = sub_m.value_of("output") { 38 | match app::OutputMode::from_str(output_format) { 39 | Ok(output_mode) => output_mode, 40 | Err(e) => { 41 | eprintln!("{}", e); 42 | std::process::exit(1); 43 | } 44 | } 45 | } else { 46 | app::OutputMode::Table 47 | }; 48 | 49 | let result = if let Some(table_spec_string) = sub_m.value_of("table") { 50 | if let Some(cap) = TABLE_SPEC_REGEX.captures(table_spec_string) { 51 | let table_name = cap.get(1).map_or("", |m| m.as_str()).to_string(); 52 | let file_format = cap.get(2).map_or("", |m| m.as_str()).to_string(); 53 | let file_path = cap.get(3).map_or("", |m| m.as_str()).to_string(); 54 | 55 | if !["elb", "alb", "squid", "s3", "jsonl"].contains(&&*file_format) { 56 | Err(AppError::InvalidLogFileFormat) 57 | } else { 58 | if file_path == "stdin" { 59 | let data_source = common::types::DataSource::Stdin(file_format, table_name); 60 | app::run(&*lower_case_query_str, data_source, output_mode) 61 | } else { 62 | let path = Path::new(&file_path); 63 | let data_source = 64 | common::types::DataSource::File(path.to_path_buf(), file_format, table_name); 65 | app::run(&*lower_case_query_str, data_source, output_mode) 66 | } 67 | } 68 | } else { 69 | Err(AppError::InvalidTableSpecString) 70 | } 71 | } else { 72 | Err(AppError::InvalidTableSpecString) 73 | }; 74 | 75 | if let Err(e) = result { 76 | println!("{}", e); 77 | } 78 | } else { 79 | println!("{}", sub_m.usage()); 80 | } 81 | } 82 | ("explain", Some(sub_m)) => { 83 | if let Some(query_str) = sub_m.value_of("query") { 84 | let lower_case_query_str = query_str.to_ascii_lowercase(); 85 | let data_source = common::types::DataSource::Stdin("jsonl".to_string(), "it".to_string()); 86 | let result = app::explain(&*lower_case_query_str, data_source); 87 | 88 | if let Err(e) = result { 89 | println!("{}", e); 90 | } 91 | } else { 92 | println!("{}", sub_m.usage()); 93 | } 94 | } 95 | ("schema", Some(sub_m)) => { 96 | if let Some(type_str) = sub_m.value_of("type") { 97 | if type_str == "elb" { 98 | let schema = execution::datasource::ClassicLoadBalancerLogField::schema(); 99 | let mut table = Table::new(); 100 | for (field, datatype) in schema.iter() { 101 | table.add_row(Row::new(vec![ 102 | Cell::new(&*field.to_string()), 103 | Cell::new(&*datatype.to_string()), 104 | ])); 105 | } 106 | table.printstd(); 107 | } else if type_str == "alb" { 108 | let schema = execution::datasource::ApplicationLoadBalancerLogField::schema(); 109 | let mut table = Table::new(); 110 | for (field, datatype) in schema.iter() { 111 | table.add_row(Row::new(vec![ 112 | Cell::new(&*field.to_string()), 113 | Cell::new(&*datatype.to_string()), 114 | ])); 115 | } 116 | table.printstd(); 117 | } else if type_str == "s3" { 118 | let schema = execution::datasource::S3Field::schema(); 119 | let mut table = Table::new(); 120 | for (field, datatype) in schema.iter() { 121 | table.add_row(Row::new(vec![ 122 | Cell::new(&*field.to_string()), 123 | Cell::new(&*datatype.to_string()), 124 | ])); 125 | } 126 | table.printstd(); 127 | } else if type_str == "squid" { 128 | let schema = execution::datasource::SquidLogField::schema(); 129 | let mut table = Table::new(); 130 | for (field, datatype) in schema.iter() { 131 | table.add_row(Row::new(vec![ 132 | Cell::new(&*field.to_string()), 133 | Cell::new(&*datatype.to_string()), 134 | ])); 135 | } 136 | table.printstd(); 137 | } else { 138 | eprintln!("Unknown log format"); 139 | } 140 | } else { 141 | println!("The supported log format"); 142 | println!("* elb"); 143 | println!("* alb"); 144 | println!("* squid"); 145 | println!("* s3"); 146 | } 147 | } 148 | _ => { 149 | println!("{}", app_m.usage()); 150 | } 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /src/syntax/ast.rs: -------------------------------------------------------------------------------- 1 | use crate::common::types::VariableName; 2 | use ordered_float::OrderedFloat; 3 | use std::fmt; 4 | use std::result; 5 | use std::str::FromStr; 6 | 7 | #[derive(Debug, PartialEq, Eq, Clone)] 8 | pub(crate) struct SelectStatement { 9 | pub(crate) select_clause: SelectClause, 10 | pub(crate) table_references: Vec, 11 | pub(crate) where_expr_opt: Option, 12 | pub(crate) group_by_exprs_opt: Option, 13 | pub(crate) having_expr_opt: Option, 14 | pub(crate) order_by_expr_opt: Option, 15 | pub(crate) limit_expr_opt: Option, 16 | } 17 | 18 | impl SelectStatement { 19 | pub fn new( 20 | select_clause: SelectClause, 21 | table_references: Vec, 22 | where_expr_opt: Option, 23 | group_by_exprs_opt: Option, 24 | having_expr_opt: Option, 25 | order_by_expr_opt: Option, 26 | limit_expr_opt: Option, 27 | ) -> Self { 28 | SelectStatement { 29 | select_clause, 30 | table_references: table_references, 31 | where_expr_opt, 32 | group_by_exprs_opt, 33 | having_expr_opt, 34 | order_by_expr_opt, 35 | limit_expr_opt, 36 | } 37 | } 38 | } 39 | 40 | impl fmt::Display for SelectStatement { 41 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 42 | match &self.select_clause { 43 | SelectClause::SelectExpressions(select_exprs) => { 44 | let select_exprs_str: Vec = select_exprs 45 | .iter() 46 | .map(|field| match field { 47 | SelectExpression::Star => "".to_string(), 48 | SelectExpression::Expression(e, name_opt) => format!("{:?} as {:?}", e, name_opt), 49 | }) 50 | .collect(); 51 | write!(f, "{:?}", select_exprs_str) 52 | } 53 | SelectClause::ValueConstructor(_vc) => { 54 | unimplemented!() 55 | } 56 | } 57 | } 58 | } 59 | 60 | #[derive(Debug, PartialEq, Eq, Clone, Hash, PartialOrd, Ord)] 61 | pub(crate) enum PathSegment { 62 | AttrName(String), 63 | ArrayIndex(String, usize), 64 | } 65 | 66 | #[derive(Debug, PartialEq, Eq, Clone, Hash, PartialOrd, Ord)] 67 | pub(crate) struct PathExpr { 68 | pub(crate) path_segments: Vec, 69 | } 70 | 71 | impl PathExpr { 72 | pub fn new(path_segments: Vec) -> Self { 73 | PathExpr { path_segments } 74 | } 75 | 76 | pub fn unwrap_last(&self) -> VariableName { 77 | match &self.path_segments.last().unwrap() { 78 | PathSegment::AttrName(s) => s.clone(), 79 | PathSegment::ArrayIndex(s, _idx) => s.clone(), 80 | } 81 | } 82 | } 83 | 84 | #[derive(Debug, PartialEq, Eq, Clone)] 85 | pub(crate) struct TableReference { 86 | pub(crate) path_expr: PathExpr, 87 | pub(crate) as_clause: Option, 88 | pub(crate) at_clause: Option, 89 | } 90 | 91 | impl TableReference { 92 | pub fn new(path_expr: PathExpr, as_clause: Option, at_clause: Option) -> Self { 93 | TableReference { 94 | path_expr, 95 | as_clause, 96 | at_clause, 97 | } 98 | } 99 | } 100 | 101 | #[derive(Debug, PartialEq, Eq, Clone)] 102 | pub(crate) struct TupleConstructor { 103 | pub(crate) key_values: Vec<(String, Expression)>, 104 | } 105 | 106 | #[derive(Debug, PartialEq, Eq, Clone)] 107 | pub(crate) struct ArrayConstructor { 108 | pub(crate) values: Vec, 109 | } 110 | 111 | #[derive(Debug, PartialEq, Eq, Clone)] 112 | pub(crate) enum SelectClause { 113 | ValueConstructor(ValueConstructor), 114 | SelectExpressions(Vec), 115 | } 116 | 117 | #[derive(Debug, PartialEq, Eq, Clone)] 118 | pub(crate) enum ValueConstructor { 119 | Expression(Expression), 120 | TupleConstructor(TupleConstructor), 121 | ArrayConstructor(ArrayConstructor), 122 | } 123 | 124 | #[derive(Debug, PartialEq, Eq, Clone)] 125 | pub(crate) enum SelectExpression { 126 | Star, 127 | Expression(Box, Option), 128 | } 129 | 130 | #[derive(Debug, PartialEq, Eq, Clone)] 131 | pub(crate) struct CaseWhenExpression { 132 | pub(crate) condition: Box, 133 | pub(crate) then_expr: Box, 134 | pub(crate) else_expr: Option>, 135 | } 136 | 137 | #[derive(Debug, PartialEq, Eq, Clone)] 138 | pub(crate) enum Expression { 139 | Column(PathExpr), 140 | Value(Value), 141 | BinaryOperator(BinaryOperator, Box, Box), 142 | UnaryOperator(UnaryOperator, Box), 143 | FuncCall(FuncName, Vec, Option), 144 | CaseWhenExpression(CaseWhenExpression), 145 | } 146 | 147 | pub(crate) type FuncName = String; 148 | 149 | #[derive(Debug, PartialEq, Eq, Clone)] 150 | pub(crate) enum BinaryOperator { 151 | Plus, 152 | Minus, 153 | Times, 154 | Divide, 155 | Equal, 156 | NotEqual, 157 | MoreThan, 158 | LessThan, 159 | GreaterEqual, 160 | LessEqual, 161 | And, 162 | Or, 163 | } 164 | 165 | impl FromStr for BinaryOperator { 166 | type Err = String; 167 | 168 | fn from_str(s: &str) -> result::Result { 169 | match s { 170 | "+" => Ok(BinaryOperator::Plus), 171 | "-" => Ok(BinaryOperator::Minus), 172 | "*" => Ok(BinaryOperator::Times), 173 | "/" => Ok(BinaryOperator::Divide), 174 | "=" => Ok(BinaryOperator::Equal), 175 | "!=" => Ok(BinaryOperator::NotEqual), 176 | ">" => Ok(BinaryOperator::MoreThan), 177 | "<" => Ok(BinaryOperator::LessThan), 178 | ">=" => Ok(BinaryOperator::GreaterEqual), 179 | "<=" => Ok(BinaryOperator::LessEqual), 180 | "and" => Ok(BinaryOperator::And), 181 | "or" => Ok(BinaryOperator::Or), 182 | _ => Err("unknown binary operator".to_string()), 183 | } 184 | } 185 | } 186 | 187 | impl fmt::Display for BinaryOperator { 188 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 189 | write!(f, "{:?}", self) 190 | } 191 | } 192 | 193 | #[derive(Debug, PartialEq, Eq, Clone)] 194 | pub(crate) enum UnaryOperator { 195 | Not, 196 | } 197 | 198 | impl fmt::Display for UnaryOperator { 199 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 200 | write!(f, "{:?}", self) 201 | } 202 | } 203 | 204 | #[derive(Debug, PartialEq, Eq, Clone)] 205 | pub enum Value { 206 | Integral(i32), 207 | Float(OrderedFloat), 208 | StringLiteral(String), 209 | Boolean(bool), 210 | } 211 | 212 | #[derive(Debug, PartialEq, Eq, Clone)] 213 | pub(crate) struct WhereExpression { 214 | pub(crate) expr: Expression, 215 | } 216 | 217 | impl WhereExpression { 218 | pub(crate) fn new(expr: Expression) -> Self { 219 | WhereExpression { expr } 220 | } 221 | } 222 | 223 | #[derive(Debug, PartialEq, Eq, Clone)] 224 | pub(crate) struct GroupByReference { 225 | pub(crate) column_expr: Expression, 226 | pub(crate) as_clause: Option, 227 | } 228 | 229 | impl GroupByReference { 230 | pub fn new(column_expr: Expression, as_clause: Option) -> Self { 231 | GroupByReference { column_expr, as_clause } 232 | } 233 | } 234 | 235 | #[derive(Debug, PartialEq, Eq, Clone)] 236 | pub(crate) struct GroupByExpression { 237 | pub(crate) exprs: Vec, 238 | pub(crate) group_as_clause: Option, 239 | } 240 | 241 | impl GroupByExpression { 242 | pub(crate) fn new(exprs: Vec, group_as_clause: Option) -> Self { 243 | GroupByExpression { exprs, group_as_clause } 244 | } 245 | } 246 | 247 | #[derive(Debug, PartialEq, Eq, Clone)] 248 | pub(crate) struct LimitExpression { 249 | pub(crate) row_count: u32, 250 | } 251 | 252 | impl LimitExpression { 253 | pub(crate) fn new(row_count: u32) -> Self { 254 | LimitExpression { row_count } 255 | } 256 | } 257 | 258 | #[derive(Debug, PartialEq, Eq, Clone)] 259 | pub(crate) enum Ordering { 260 | Asc, 261 | Desc, 262 | } 263 | 264 | impl FromStr for Ordering { 265 | type Err = String; 266 | 267 | fn from_str(s: &str) -> result::Result { 268 | match s { 269 | "asc" => Ok(Ordering::Asc), 270 | "desc" => Ok(Ordering::Desc), 271 | _ => Err("unknown ordering".to_string()), 272 | } 273 | } 274 | } 275 | 276 | #[derive(Debug, PartialEq, Eq, Clone)] 277 | pub(crate) struct OrderingTerm { 278 | pub(crate) column_name: PathExpr, 279 | pub(crate) ordering: Ordering, 280 | } 281 | 282 | impl OrderingTerm { 283 | pub(crate) fn new(column_name: PathExpr, ordering: &str) -> Self { 284 | OrderingTerm { 285 | column_name, 286 | ordering: Ordering::from_str(ordering).unwrap(), 287 | } 288 | } 289 | } 290 | 291 | #[derive(Debug, PartialEq, Eq, Clone)] 292 | pub(crate) struct OrderByExpression { 293 | pub(crate) ordering_terms: Vec, 294 | } 295 | 296 | impl OrderByExpression { 297 | pub(crate) fn new(ordering_terms: Vec) -> Self { 298 | OrderByExpression { ordering_terms } 299 | } 300 | } 301 | 302 | #[derive(Debug, Clone)] 303 | pub(crate) struct FuncCallExpression { 304 | pub(crate) func_name: String, 305 | pub(crate) arguments: Vec, 306 | } 307 | 308 | #[derive(Debug, PartialEq, Eq, Clone)] 309 | pub(crate) struct WithinGroupClause { 310 | pub(crate) ordering_term: OrderingTerm, 311 | } 312 | 313 | impl WithinGroupClause { 314 | pub(crate) fn new(order_by_expr: OrderByExpression) -> Self { 315 | WithinGroupClause { 316 | ordering_term: order_by_expr.ordering_terms[0].clone(), 317 | } 318 | } 319 | } 320 | -------------------------------------------------------------------------------- /src/syntax/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod ast; 2 | pub mod parser; 3 | -------------------------------------------------------------------------------- /tests/exists-queries.txt: -------------------------------------------------------------------------------- 1 | 2 | SELECT * FROM employees e WHERE exists(SELECT id FROM eotm_dyn d WHERE d.employeeID = e.id) 3 | SELECT * FROM employees e WHERE not exists ( SELECT id FROM eotm_dyn d WHERE d.employeeID = e.id) 4 | SELECT * FROM employees e WHERE not (exists ( SELECT id FROM eotm_dyn d WHERE d.employeeID = e.id)) 5 | SELECT * FROM employees e WHERE x > 3 and not exists (SELECT id FROM eotm_dyn d WHERE d.employeeID = e.id ) and y < 3 6 | 7 | -------------------------------------------------------------------------------- /tests/select.txt: -------------------------------------------------------------------------------- 1 | 2 | select a + b from c; 3 | select a + 2 from c; 4 | select a+ 2 from c; 5 | select a+2 from c; 6 | 7 | select a from db1.table1; 8 | select table1.a from db1.table1; 9 | select table1.a from db1.table1 as d; 10 | 11 | SELECT n+10 FROM tens WHERE n+10 >= 100; 12 | SELECT n+10 FROM tens WHERE n+10 < 100; 13 | SELECT n+10 FROM tens WHERE n+10 > 100; 14 | SELECT n+10 FROM tens WHERE n+10<= 100; 15 | SELECT n+10 FROM tens WHERE n+10 = 100; 16 | 17 | SELECT n+10 FROM tens WHERE (n+10) >= 100; 18 | SELECT n+10 FROM tens WHERE (n+10 )< 100; 19 | SELECT n+10 FROM tens WHERE (n+10) > 100; 20 | SELECT n+10 FROM tens WHERE (n+10 )<= 100; 21 | SELECT n+10 FROM tens WHERE ( n+10 ) = 100; 22 | 23 | SELECT n+10 FROM tens WHERE 100 >= (n+10); 24 | SELECT n+10 FROM tens WHERE 100 >(n+10 ) ; 25 | SELECT n+10 FROM tens WHERE 100<( n+10) ; 26 | SELECT n+10 FROM tens WHERE 100>=(n+10 ) ; 27 | SELECT n+10 FROM tens WHERE 100 = ( n+10 ); 28 | 29 | SELECT n+10 FROM tens WHERE n >= 100; 30 | SELECT n+10 FROM tens WHERE n <100; 31 | SELECT n+10 FROM tens WHERE n >100; 32 | SELECT n+10 FROM tens WHERE n<= 100; 33 | SELECT n+10 FROM tens WHERE n= 100; 34 | -------------------------------------------------------------------------------- /tests/tpc-w-queries.txt: -------------------------------------------------------------------------------- 1 | # getName 2 | SELECT c_fname,c_lname FROM customer WHERE c_id = ?; 3 | 4 | # getBook 5 | SELECT * FROM item,author WHERE item.i_a_id = author.a_id AND i_id = ?; 6 | 7 | # getCustomer 8 | SELECT * FROM customer, address, country WHERE customer.c_addr_id = address.addr_id AND address.addr_co_id = country.co_id AND customer.c_uname = ?; 9 | 10 | # doSubjectSearch 11 | SELECT * FROM item, author WHERE item.i_a_id = author.a_id AND item.i_subject = ? ORDER BY item.i_title limit 50; 12 | 13 | # doTitleSearch 14 | -- SELECT * FROM item, author WHERE item.i_a_id = author.a_id AND substring(soundex(item.i_title),0,4)=substring(soundex(?),0,4) ORDER BY item.i_title limit 50; 15 | -- SELECT * FROM item, author WHERE item.i_a_id = author.a_id AND substring(soundex(item.i_title),1,4)=substring(soundex(?),1,4) ORDER BY item.i_title limit 50; 16 | -- SELECT * FROM item, author WHERE item.i_a_id = author.a_id AND item.i_title LIKE ? ORDER BY item.i_title limit 50; 17 | 18 | # doAuthorSearch 19 | -- SELECT * FROM author, item WHERE substring(soundex(author.a_lname),0,4)=substring(soundex(?),0,4) AND item.i_a_id = author.a_id ORDER BY item.i_title limit 50; 20 | -- SELECT * FROM author, item WHERE substring(soundex(author.a_lname),1,4)=substring(soundex(?),1,4) AND item.i_a_id = author.a_id ORDER BY item.i_title limit 50; 21 | -- SELECT * FROM author, item WHERE author.a_lname LIKE ? AND item.i_a_id = author.a_id ORDER BY item.i_title limit 50; 22 | 23 | # getNewProducts 24 | SELECT i_id, i_title, a_fname, a_lname FROM item, author WHERE item.i_a_id = author.a_id AND item.i_subject = ? ORDER BY item.i_pub_date DESC,item.i_title limit 50; 25 | 26 | # getBestSellers 27 | SELECT i_id, i_title, a_fname, a_lname FROM item, author, order_line WHERE item.i_id = order_line.ol_i_id AND item.i_a_id = author.a_id AND order_line.ol_o_id > (SELECT MAX(o_id)-3333 FROM orders) AND item.i_subject = ? GROUP BY i_id, i_title, a_fname, a_lname ORDER BY SUM(ol_qty) DESC limit 50; 28 | 29 | # getRelated 30 | SELECT J.i_id,J.i_thumbnail from item I, item J where (I.i_related1 = J.i_id or I.i_related2 = J.i_id or I.i_related3 = J.i_id or I.i_related4 = J.i_id or I.i_related5 = J.i_id) and I.i_id = ?; 31 | 32 | # adminUpdate 33 | UPDATE item SET i_cost = ?, i_image = ?, i_thumbnail = ?, i_pub_date = CURRENT_DATE WHERE i_id = ?; 34 | # adminUpdate.related 35 | SELECT ol_i_id FROM orders, order_line WHERE orders.o_id = order_line.ol_o_id AND NOT (order_line.ol_i_id = ?) AND orders.o_c_id IN (SELECT o_c_id FROM orders, order_line WHERE orders.o_id = order_line.ol_o_id AND orders.o_id > (SELECT MAX(o_id)-10000 FROM orders) AND order_line.ol_i_id = ?) GROUP BY ol_i_id ORDER BY SUM(ol_qty) DESC limit 5; 36 | # adminUpdate.related1 37 | UPDATE item SET i_related1 = ?, i_related2 = ?, i_related3 = ?, i_related4 = ?, i_related5 = ? WHERE i_id = ?; 38 | 39 | # getUserName 40 | SELECT c_uname FROM customer WHERE c_id = ?; 41 | 42 | # getPassword 43 | SELECT c_passwd FROM customer WHERE c_uname = ?; 44 | 45 | # getRelated1 46 | SELECT i_related1 FROM item where i_id = ?; 47 | 48 | # getMostRecentOrder.id 49 | SELECT o_id FROM customer, orders WHERE customer.c_id = orders.o_c_id AND c_uname = ? ORDER BY o_date, orders.o_id DESC limit 1; 50 | 51 | # getMostRecentOrder.order 52 | SELECT orders.*, customer.*, cc_xacts.cx_type, ship.addr_street1 AS ship_addr_street1, ship.addr_street2 AS ship_addr_street2, ship.addr_state AS ship_addr_state, ship.addr_zip AS ship_addr_zip, ship_co.co_name AS ship_co_name, bill.addr_street1 AS bill_addr_street1, bill.addr_street2 AS bill_addr_street2, bill.addr_state AS bill_addr_state, bill.addr_zip AS bill_addr_zip, bill_co.co_name AS bill_co_name FROM customer, orders, cc_xacts, address AS ship, country AS ship_co, address AS bill, country AS bill_co WHERE orders.o_id = ? AND cx_o_id = orders.o_id AND customer.c_id = orders.o_c_id AND orders.o_bill_addr_id = bill.addr_id AND bill.addr_co_id = bill_co.co_id AND orders.o_ship_addr_id = ship.addr_id AND ship.addr_co_id = ship_co.co_id AND orders.o_c_id = customer.c_id; 53 | # getMostRecentOrder.lines 54 | SELECT * FROM order_line, item WHERE ol_o_id = ? AND ol_i_id = i_id; 55 | 56 | # createEmptyCart 57 | SELECT COUNT(*) FROM shopping_cart; 58 | # createEmptyCart.insert 59 | -- INSERT into shopping_cart (sc_id, sc_time) VALUES ((SELECT COUNT(*) FROM shopping_cart), CURRENT_TIMESTAMP); 60 | # createEmptyCart.insert.v2 61 | INSERT into shopping_cart (sc_id, sc_time) VALUES (?, CURRENT_TIMESTAMP); 62 | 63 | # addItem 64 | SELECT scl_qty FROM shopping_cart_line WHERE scl_sc_id = ? AND scl_i_id = ?; 65 | # addItem.update 66 | UPDATE shopping_cart_line SET scl_qty = ? WHERE scl_sc_id = ? AND scl_i_id = ?; 67 | # addItem.put 68 | INSERT into shopping_cart_line (scl_sc_id, scl_qty, scl_i_id) VALUES (?,?,?); 69 | 70 | # refreshCArt.remove 71 | DELETE FROM shopping_cart_line WHERE scl_sc_id = ? AND scl_i_id = ?; 72 | # refreshCart.update 73 | UPDATE shopping_cart_line SET scl_qty = ? WHERE scl_sc_id = ? AND scl_i_id = ?; 74 | 75 | # addRandomItemToCartIfNecessary 76 | SELECT COUNT(*) from shopping_cart_line where scl_sc_id = ?; 77 | 78 | # resetCartTime 79 | UPDATE shopping_cart SET sc_time = CURRENT_TIMESTAMP WHERE sc_id = ?; 80 | 81 | # getCart 82 | SELECT * FROM shopping_cart_line, item WHERE scl_i_id = item.i_id AND scl_sc_id = ?; 83 | 84 | # refreshSession 85 | -- UPDATE customer SET c_login = NOW(), c_expiration = (CURRENT_TIMESTAMP + INTERVAL 2 HOUR) WHERE c_id = ?; 86 | 87 | # createNewCustomer 88 | INSERT into customer (c_id, c_uname, c_passwd, c_fname, c_lname, c_addr_id, c_phone, c_email, c_since, c_last_login, c_login, c_expiration, c_discount, c_balance, c_ytd_pmt, c_birthdate, c_data) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); 89 | # createNewCustomer.maxId 90 | SELECT max(c_id) FROM customer; 91 | 92 | # getCDiscount 93 | SELECT c_discount FROM customer WHERE customer.c_id = ?; 94 | 95 | # getCAddrId 96 | SELECT c_addr_id FROM customer WHERE customer.c_id = ?; 97 | 98 | # getCAddr 99 | SELECT c_addr_id FROM customer WHERE customer.c_id = ?; 100 | 101 | # enterCCXact 102 | -- INSERT into cc_xacts (cx_o_id, cx_type, cx_num, cx_name, cx_expire, cx_xact_amt, cx_xact_date, cx_co_id) VALUES (?, ?, ?, ?, ?, ?, CURRENT_DATE, (SELECT co_id FROM address, country WHERE addr_id = ? AND addr_co_id = co_id)); 103 | 104 | # clearCart 105 | DELETE FROM shopping_cart_line WHERE scl_sc_id = ?; 106 | 107 | # enterAddress.id 108 | SELECT co_id FROM country WHERE co_name = ?; 109 | # enterAddress.match 110 | SELECT addr_id FROM address WHERE addr_street1 = ? AND addr_street2 = ? AND addr_city = ? AND addr_state = ? AND addr_zip = ? AND addr_co_id = ?; 111 | # enterAddress.insert 112 | INSERT into address (addr_id, addr_street1, addr_street2, addr_city, addr_state, addr_zip, addr_co_id) VALUES (?, ?, ?, ?, ?, ?, ?); 113 | # enterAddress.maxId 114 | SELECT max(addr_id) FROM address; 115 | 116 | # enterOrder.insert 117 | -- INSERT into orders (o_id, o_c_id, o_date, o_sub_total, o_tax, o_total, o_ship_type, o_ship_date, o_bill_addr_id, o_ship_addr_id, o_status) VALUES (?, ?, CURRENT_DATE, ?, 8.25, ?, ?, CURRENT_DATE + INTERVAL ? DAY, ?, ?, 'Pending'); 118 | # enterOrder.maxId 119 | SELECT count(o_id) FROM orders; 120 | 121 | # addOrderLine 122 | INSERT into order_line (ol_id, ol_o_id, ol_i_id, ol_qty, ol_discount, ol_comments) VALUES (?, ?, ?, ?, ?, ?); 123 | 124 | # getStock 125 | SELECT i_stock FROM item WHERE i_id = ?; 126 | 127 | # setStock 128 | UPDATE item SET i_stock = ? WHERE i_id = ?; 129 | 130 | # verifyDBConsistency.custId 131 | SELECT c_id FROM customer; 132 | # verifyDBConsistency.itemId 133 | SELECT i_id FROM item; 134 | # verifyDBConsistency.addrId 135 | SELECT addr_id FROM address; 136 | --------------------------------------------------------------------------------