[
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: harelba\n"
  },
  {
    "path": ".github/workflows/build-and-package.yaml",
    "content": "name: BuildAndPackage\n\non:\n  push:\n    tags:\n      - \"v*\"\n    branches: master\n  pull_request:\n    branches: master\n    paths-ignore:\n      - \"*.md\"\n      - \"*.markdown\"\n      - \"mkdocs/**/*\"\n    tags-ignore:\n      - \"*\"\n\njobs:\n  version_info:\n    runs-on: ubuntu-18.04\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v2\n      - id: vars\n        run: |\n          set -x -e\n\n          echo \"github event ref is ${{ github.ref }}\"\n\n          if [ \"x${{ startsWith(github.ref, 'refs/tags/v') }}\" == \"xtrue\" ]\n          then\n            echo \"Trigger was a version tag - ${{ github.ref }}\"\n            echo ::set-output name=q_version::${GITHUB_REF#refs/tags/v}\n            echo ::set-output name=is_release::true\n          else\n            # For testing version propagation inside the PR\n            echo \"Either branch of a non-version tag - setting version to 0.0.0\"\n            echo ::set-output name=q_version::0.0.0\n            echo ::set-output name=is_release::false\n          fi\n\n    outputs:\n      q_version: ${{ steps.vars.outputs.q_version }}\n      is_release: ${{ steps.vars.outputs.is_release }}\n\n  check_version_info:\n    runs-on: ubuntu-18.04\n    needs: version_info\n    steps:\n      - name: test q_version\n        run: |\n          set -e -x\n\n          echo \"outputs: ${{ toJson(needs.version_info) }}\"\n\n  create-man:\n    runs-on: ubuntu-18.04\n    steps:\n    - name: Checkout\n      uses: actions/checkout@v2\n    - name: Install Ruby\n      uses: ruby/setup-ruby@v1\n      with:\n        ruby-version: '2.6'\n    - name: Create man page\n      run: |\n        set -x -e\n        gem install ronn\n\n        ronn doc/USAGE.markdown\n        # Must be gzipped, otherwise debian does not install it\n        gzip doc/USAGE\n    - name: Upload man page\n      uses: actions/upload-artifact@v1.0.0\n      with:\n        name: q-man-page\n        path: doc/USAGE.gz\n\n  build-linux:\n    runs-on: ubuntu-18.04\n    steps:\n    - name: Checkout\n      uses: actions/checkout@v2\n    - name: Cache pyox\n      uses: actions/cache@v2\n      with:\n        path: |\n          ~/.cache/pyoxidizer\n        key: ${{ runner.os }}-pyox\n    - name: Install pyoxidizer\n      run: |\n        set -e -x\n\n        sudo apt-get update\n        sudo apt-get install -y zip sqlite3 rpm\n\n        curl -o pyoxidizer.zip -L \"https://github.com/indygreg/PyOxidizer/releases/download/pyoxidizer%2F0.17/pyoxidizer-0.17.0-linux_x86_64.zip\"\n        unzip pyoxidizer.zip\n        chmod +x ./pyoxidizer\n    - name: Create Q Executable - Linux\n      run: |\n        set -e -x\n\n        ./pyoxidizer build --release\n\n        export Q_EXECUTABLE=./build/x86_64-unknown-linux-gnu/release/install/q\n        chmod 755 $Q_EXECUTABLE\n\n        seq 1 100 | $Q_EXECUTABLE -c 1 \"select sum(c1),count(*) from -\" -S test.sqlite\n\n        mkdir -p packages/linux/\n        cp $Q_EXECUTABLE packages/linux/linux-q\n    - name: Upload Linux Executable\n      uses: actions/upload-artifact@v1.0.0\n      with:\n        name: linux-q\n        path: packages/linux/linux-q\n\n  test-linux:\n    needs: build-linux\n    runs-on: ubuntu-18.04\n    steps:\n    - name: Checkout\n      uses: actions/checkout@v2\n    - name: Install Python for Testing\n      uses: actions/setup-python@v2\n      with:\n        python-version: '3.8.12'\n        architecture: 'x64'\n    - name: Prepare Testing\n      run: |\n        set -e -x\n\n        pip3 install -r test-requirements.txt\n    - name: Download Linux Executable\n      uses: actions/download-artifact@v2\n      with:\n        name: linux-q\n    - name: Run Tests on Linux Executable\n      run: |\n        set -x -e\n\n        find ./ -ls\n\n        chmod 755 ./linux-q\n\n        Q_EXECUTABLE=`pwd`/linux-q Q_SKIP_EXECUTABLE_VALIDATION=true ./run-tests.sh -v\n\n  package-linux-deb:\n    needs: [test-linux, create-man, version_info]\n    runs-on: ubuntu-18.04\n    steps:\n    - name: Checkout\n      uses: actions/checkout@v2\n    - name: Install Ruby\n      uses: ruby/setup-ruby@v1\n      with:\n        ruby-version: '2.6'\n    - name: Downoad man page\n      uses: actions/download-artifact@v2\n      with:\n        name: q-man-page\n    - name: Download Linux Executable\n      uses: actions/download-artifact@v2\n      with:\n        name: linux-q\n    - name: Build DEB Package\n      run: |\n        set -e -x\n\n        mkdir -p packages/linux/\n\n        find ./ -ls\n\n        chmod 755 ./linux-q\n\n        export q_version=${{ needs.version_info.outputs.q_version }}\n\n        gem install fpm\n        cp dist/fpm-config ~/.fpm\n        fpm -s dir -t deb --deb-use-file-permissions -p packages/linux/q-text-as-data-${q_version}-1.x86_64.deb --version ${q_version} ./linux-q=/usr/bin/q USAGE.gz=/usr/share/man/man1/q.1.gz\n    - name: Upload DEB Package\n      uses: actions/upload-artifact@v1.0.0\n      with:\n        name: q-text-as-data-${{ needs.version_info.outputs.q_version }}-1.x86_64.deb\n        path: packages/linux/q-text-as-data-${{ needs.version_info.outputs.q_version }}-1.x86_64.deb\n\n  test-deb-packaging:\n    runs-on: ubuntu-18.04\n    needs: [package-linux-deb, version_info]\n    steps:\n    - name: Checkout\n      uses: actions/checkout@v2\n    - name: Download DEB\n      uses: actions/download-artifact@v2\n      with:\n        name: q-text-as-data-${{ needs.version_info.outputs.q_version }}-1.x86_64.deb\n    - name: Install Python for Testing\n      uses: actions/setup-python@v2\n      with:\n        python-version: '3.8.12'\n        architecture: 'x64'\n    - name: Prepare Testing\n      run: |\n        set -e -x\n\n        pip3 install -r test-requirements.txt\n    - name: Test DEB Package Installation\n      run: ./dist/test-using-deb.sh ./q-text-as-data-${{ needs.version_info.outputs.q_version }}-1.x86_64.deb\n\n  package-linux-rpm:\n    needs: [test-linux, create-man, version_info]\n    runs-on: ubuntu-18.04\n    steps:\n    - name: Checkout\n      uses: actions/checkout@v2\n    - name: Install Ruby\n      uses: ruby/setup-ruby@v1\n      with:\n        ruby-version: '2.6'\n    - name: Download man page\n      uses: actions/download-artifact@v2\n      with:\n        name: q-man-page\n    - name: Download Linux Executable\n      uses: actions/download-artifact@v2\n      with:\n        name: linux-q\n    - name: Build RPM Package\n      run: |\n        set -e -x\n\n        mkdir -p packages/linux\n\n\n        chmod 755 ./linux-q\n\n        export q_version=${{ needs.version_info.outputs.q_version }}\n\n        gem install fpm\n        cp dist/fpm-config ~/.fpm\n        fpm -s dir -t rpm --rpm-use-file-permissions -p packages/linux/q-text-as-data-${q_version}.x86_64.rpm --version ${q_version} ./linux-q=/usr/bin/q USAGE.gz=/usr/share/man/man1/q.1.gz\n    - name: Upload RPM Package\n      uses: actions/upload-artifact@v1.0.0\n      with:\n        name: q-text-as-data-${{ needs.version_info.outputs.q_version }}.x86_64.rpm\n        path: packages/linux/q-text-as-data-${{ needs.version_info.outputs.q_version }}.x86_64.rpm\n\n  test-rpm-packaging:\n    runs-on: ubuntu-18.04\n    needs: [package-linux-rpm, version_info]\n    steps:\n    - name: Checkout\n      uses: actions/checkout@v2\n    - name: Download RPM\n      uses: actions/download-artifact@v2\n      with:\n        name: q-text-as-data-${{ needs.version_info.outputs.q_version }}.x86_64.rpm\n    - name: Retest using RPM\n      run: ./dist/test-using-rpm.sh ./q-text-as-data-${{ needs.version_info.outputs.q_version }}.x86_64.rpm\n\n  build-mac:\n    runs-on: macos-11\n    steps:\n    - name: Checkout\n      uses: actions/checkout@v2\n    - name: Cache pyox\n      uses: actions/cache@v2\n      with:\n        path: |\n          ~/.cache/pyoxidizer\n        key: ${{ runner.os }}-pyox\n    - name: Install pyoxidizer\n      run: |\n        set -e -x\n\n        curl -o  pyoxidizer.zip -L \"https://github.com/indygreg/PyOxidizer/releases/download/pyoxidizer%2F0.17/pyoxidizer-0.17.0-macos-universal.zip\"\n        unzip pyoxidizer.zip\n        mv macos-universal/pyoxidizer ./pyoxidizer\n\n        chmod +x ./pyoxidizer\n    - name: Create Q Executable - Mac\n      run: |\n        set -e -x\n\n        ./pyoxidizer build --release\n\n        export Q_EXECUTABLE=./build/x86_64-apple-darwin/release/install/q\n        chmod 755 $Q_EXECUTABLE\n\n        seq 1 100 | $Q_EXECUTABLE -c 1 \"select sum(c1),count(*) from -\" -S test.sqlite\n\n        mkdir -p packages/macos/\n        cp $Q_EXECUTABLE packages/macos/macos-q\n    - name: Upload MacOS Executable\n      uses: actions/upload-artifact@v1.0.0\n      with:\n        name: macos-q\n        path: packages/macos/macos-q\n\n  test-mac:\n    needs: build-mac\n    runs-on: macos-11\n    steps:\n    - name: Checkout\n      uses: actions/checkout@v2\n    - name: Install Python for Testing\n      uses: actions/setup-python@v2\n      with:\n        python-version: '3.8.12'\n        architecture: 'x64'\n    - name: Prepare Testing\n      run: |\n        set -e -x\n\n        pip3 install wheel\n\n        pip3 install -r test-requirements.txt\n    - name: Download MacOS Executable\n      uses: actions/download-artifact@v2\n      with:\n        name: macos-q\n    - name: Run Tests on MacOS Executable\n      run: |\n        set -e -x\n\n        chmod 755 ./macos-q\n\n        Q_EXECUTABLE=`pwd`/macos-q Q_SKIP_EXECUTABLE_VALIDATION=true ./run-tests.sh -v\n\n  not-package-mac:\n    # create-man is not needed, as it's generated inside the brew formula independently\n    needs: [test-mac]\n    runs-on: macos-11\n    steps:\n    - name: Checkout\n      uses: actions/checkout@v2\n    - name: Not Packaging Mac\n      run: |\n        echo \"homebrew mac cannot be packaged from the source code itself, due to the package build process of homebrew. See https://github.com/harelba/homebrew-q\"\n\n  not-test-mac-packaging:\n    needs: not-package-mac\n    runs-on: macos-11\n    steps:\n    - name: Checkout\n      uses: actions/checkout@v2\n    - name: Not Testing Mac Packaging\n      run: |\n        echo \"homebrew mac packaging cannot be tested here, due to the package build process of homebrew. See https://github.com/harelba/homebrew-q\"\n\n  build-windows:\n    runs-on: windows-latest\n    needs: version_info\n    steps:\n    - name: Checkout\n      uses: actions/checkout@v2\n    - name: Install MSVC build tools\n      uses: ilammy/msvc-dev-cmd@v1\n    - name: Install Python\n      uses: actions/setup-python@v2\n      with:\n        python-version: '3.8.10'\n        architecture: 'x64'\n    - name: Install pyoxidizer\n      shell: bash\n      run: |\n        set -x -e\n\n        python3 -V\n        pip3 -V\n\n        pip3 install pyoxidizer\n    - name: Create Q Executable - Windows\n      shell: bash\n      run: |\n        set -e -x\n\n        pyoxidizer build --release --var Q_VERSION ${{ needs.version_info.outputs.q_version }}\n\n        export Q_EXECUTABLE=./build/x86_64-pc-windows-msvc/release/install/q\n        chmod 755 $Q_EXECUTABLE\n\n        seq 1 100 | $Q_EXECUTABLE -c 1 \"select sum(c1),count(*) from -\" -S test.sqlite\n\n        mkdir -p packages/windows/\n        cp $Q_EXECUTABLE packages/windows/win-q.exe\n\n        find ./ -ls\n    - name: Upload Linux Executable\n      uses: actions/upload-artifact@v1.0.0\n      with:\n        name: win-q.exe\n        path: packages/windows/win-q.exe\n\n  not-really-test-windows:\n    needs: build-windows\n    runs-on: windows-latest\n    steps:\n    - name: Checkout\n      uses: actions/checkout@v2\n    - name: Install Python for Testing\n      uses: actions/setup-python@v2\n      with:\n        python-version: '3.8'\n        architecture: 'x64'\n    - name: Download Windows Executable\n      uses: actions/download-artifact@v2\n      with:\n        name: win-q.exe\n    - name: Not-Really-Test Windows\n      shell: bash\n      continue-on-error: true\n      run: |\n        echo \"Tests are not compatible with Windows (path separators, tmp folder names etc.). Only a sanity wil be tested\"\n\n        chmod +x ./win-q.exe\n\n        seq 1 10000 | ./win-q.exe -c 1 \"select sum(c1),count(*) from -\" -S some-db.sqlite\n\n  package-windows:\n    needs: [create-man, not-really-test-windows, version_info]\n    runs-on: windows-latest\n    steps:\n    - name: Checkout\n      uses: actions/checkout@v2\n    - name: Install MSVC build tools\n      uses: ilammy/msvc-dev-cmd@v1\n    - name: Install Python\n      uses: actions/setup-python@v2\n      with:\n        python-version: '3.8.10'\n        architecture: 'x64'\n    - name: Install pyoxidizer\n      shell: bash\n      run: |\n        set -x -e\n\n        python3 -V\n        pip3 -V\n\n        pip3 install pyoxidizer\n    - name: Create Q MSI - Windows\n      shell: bash\n      run: |\n        set -e -x\n\n        pyoxidizer build --release msi_installer --var Q_VERSION ${{ needs.version_info.outputs.q_version }}\n\n        export Q_MSI=./build/x86_64-pc-windows-msvc/release/msi_installer/q-text-as-data-${{ needs.version_info.outputs.q_version }}.msi\n        chmod 755 $Q_MSI\n\n        mkdir -p packages/windows/\n        cp $Q_MSI packages/windows/q-text-as-data-${{ needs.version_info.outputs.q_version }}.msi\n\n    - name: Upload Windows MSI\n      uses: actions/upload-artifact@v1.0.0\n      with:\n        name: q-text-as-data-${{ needs.version_info.outputs.q_version }}.msi\n        path: packages/windows/q-text-as-data-${{ needs.version_info.outputs.q_version }}.msi\n\n  test-windows-packaging:\n    needs: [package-windows, version_info]\n    runs-on: windows-latest\n    steps:\n    - name: Checkout\n      uses: actions/checkout@v2\n    - name: Download Windows Package\n      uses: actions/download-artifact@v2\n      with:\n        name: q-text-as-data-${{ needs.version_info.outputs.q_version }}.msi\n    - name: Test Install of MSI\n      continue-on-error: true\n      shell: powershell\n      run: |\n        $process = Start-Process msiexec.exe -ArgumentList \"/i q-text-as-data-${{ needs.version_info.outputs.q_version }}.msi -l* msi-install.log /norestart /quiet\" -PassThru -Wait\n        $process.ExitCode\n        gc msi-install.log\n\n        exit $process.ExitCode\n    - name: Test Uninstall of MSI\n      continue-on-error: true\n      shell: powershell\n      run: |\n        $process = Start-Process msiexec.exe -ArgumentList \"/u q-text-as-data-${{ needs.version_info.outputs.q_version }}.msi /norestart /quiet\" -PassThru -Wait\n        $process.ExitCode\n        exit $process.ExitCode\n\n  perform-prerelease:\n    # We'd like artifacts to be uploaded regardless of tests succeeded or not,\n    # this is why the dependency here is not on test-X-packaging jobs\n    needs: [package-linux-deb, package-linux-rpm, not-package-mac, package-windows, version_info]\n    runs-on: ubuntu-latest\n    if: needs.version_info.outputs.is_release == 'false'\n    steps:\n    - name: Download All Artifacts\n      uses: actions/download-artifact@v2\n      with:\n        path: artifacts/\n    - name: Timestamp pre-release\n      run: |\n        set -e -x\n\n        echo \"Workflow finished at $(date)\" >> artifacts/workflow-finish-time.txt\n    - name: Create pre-release\n      uses: \"marvinpinto/action-automatic-releases@v1.2.1\"\n      with:\n        repo_token: \"${{ secrets.GITHUB_TOKEN }}\"\n        automatic_release_tag: \"latest\"\n        prerelease: true\n        title: \"Next Release Development Build\"\n        files: |\n          artifacts/**/*\n\n  perform-release:\n    needs: [not-test-mac-packaging, test-deb-packaging, test-rpm-packaging, test-windows-packaging, version_info]\n    runs-on: ubuntu-latest\n    if: needs.version_info.outputs.is_release == 'true'\n    steps:\n    - name: Download All Artifacts\n      uses: actions/download-artifact@v2\n      with:\n        path: artifacts/\n    - uses: \"marvinpinto/action-automatic-releases@v1.2.1\"\n      with:\n        repo_token: \"${{ secrets.GITHUB_TOKEN }}\"\n        prerelease: false\n        files: |\n          artifacts/**/*\n"
  },
  {
    "path": ".gitignore",
    "content": "build\nq.spec\nq.1\n*.pyc\n.vagrant\nrpm_build_area\n*.deb\nsetup.exe\nwin_output\nwin_build\npackages\n.idea/\ndist/windows/\ngenerated-site/\nbenchmark_data.tar.gz\n_benchmark_data/\nq.egg-info/\n.pytest_cache/\n*.qsql\nhtmlcov/\n*.sqlite\n*.tar.gz\n.coverage\n.DS_Store\n*.egg\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "QSQL-NOTES.md",
    "content": "\n## Major changes and additions in the new `3.x` version\nThis is the list of new/changed functionality in this version. Large changes, please make sure to read the details if you're already using q.\n\n* **Automatic Immutable Caching** - Automatic caching of data files (into `<my-csv-filename>.qsql` files), with huge speedups for medium/large files. Enabled through `-C readwrite` or `-C read`\n* **Direct querying of standard sqlite databases** - Just use it as a table name in the query. Format is `select ... from <sqlitedb_filename>:::<table_name>`, or just `<sqlitedb_filename>` if the database contains only one table. Multiple separate sqlite databases are fully supported in the same query.\n* **Direct querying of the `qsql` cache files** - The user can query directly from the `qsql` files, removing the need for the original files. Just use `select ... from <my-csv-filename>.qsql`. Please wait until the non-beta version is out before thinking about deleting any of your original files...\n* **Revamped `.qrc` mechanism** - allows opting-in to caching without specifying it in every query. By default, caching is **disabled**, for backward compatibility and for finding usability issues.\n* **Save-to-db is now reusable for queries** - `--save-db-to-disk` option (`-S`) has been enhanced to match the new capabilities. You can query the resulting file directly through q, using the method mentioned above (it's just a standard sqlite database).\n* **Only python3 is supported from now on** - Shouldn't be an issue, since q is a self-contained binary executable which has its own python embedded in it. Internally, q is now packaged with Python 3.8. After everything cools down, I'll probably bump this to 3.9/3.10.\n* **Minimal Linux Version Bumped** - Works with CentOS 8, Ubuntu 18.04+, Debian 10+. Currently only for x86_64. Depends on glibc version 2.25+. Haven't tested it on other architectures. Issuing other architectures will be possible later on\n* **Completely revamped binary packaging** - Using [pyoxidizer](https://github.com/indygreg/PyOxidizer)\n\nThe following sections provide the details of each of the new functionalities in this major version.\n\n## Automatic caching of data files\nSpeeding up subsequent reads from the same file by several orders of magnitude by automatically creating an immutable cache file for each tabular text file.  \n\nFor example, reading a 0.9GB file with 1M rows and 100 columns without caching takes ~50 seconds. When the cache exists, querying the same file will take around ~1-2 seconds. Obviously, the cache can be used in order to perform any query and not just the original query that was used for creating the cache.\n\nWhen caching is enabled, the cache is created on the first read of a file, and used automatically when reading it in other queries. A separate cache is being created for each file that is being used, allowing reuse in multiple use-cases. For example, if two csv files each have their own cache file from previous queries, then running a query that JOINs these two files would use the caches as well (without loading the data into memory), speeding it up considerably.\n\nThe tradeoff for using cache files is disk space - A new file with the postfix `.qsql` is created and automatically detected and used in queries as needed. This file is essentially a standard sqlite file (with some additional metadata tables), and can be used directly by any standard sqlite tool later on.\n\nFor backward compatibility, the caching option is not turned on by default. You'd need to use the new `-C <mode>` to determine the caching mode. Available options are as follows:\n* `none` - The default,  provides the original q's behaviour without caching\n* `read` - Only reads cache files if they exists, but doesn't create any new ones\n* `readwrite` - Uses cache files if they exists, or creates new ones if they don't. Writing new cache files doesn't interfere with the actual run of the query, so this option can be used in order to dynamically create the cache files if they don't exist\n\nContent signatures are being stored in the caches, allowing to detect a state where the original file has been modified after the cache has been created. q will issue an error if this happens. For now, just delete the `.qsql` file in order to recreate the cache. In the future, another `-C` option would be added to automatically recreate the updated cache in such a case. Notice that the content signature contains various q flags which affect parsing, so make sure to use the same parameters to q when performing the queries, otherwise q will issue an error.\n\nNotice that when running with `-A`, the cache is not written, even when `-C` is set to `readwrite`. This is due to the fact that `-A` does not really read the entire content of the files. For now, if you'd like to just prepare the cache without running the actual query, you can run it with a `select 1` query or something, although in terms of speed it will mostly not matter. If there's demand for adding an explicit `prepare caches only` option, I'll consider adding it.\n\n## Revamped `.qrc` mechanism\nAdding `-C <mode>` for each query can be cumbersome at some point, so the `.qrc` file has been revamped for easy addition of default parameters. \n\nFor example, if you want the caching behaviour to be `read` all the time, then just add a `~/.qrc` file, and set the following in it:\n```\n[options]\ncaching_mode=read\n```\n\nAll other flags and parameters to q can be controlled by the `.qrc` file. To see the proper names for each parameter, run `q --dump-defaults` and it will dump a default `.qrc` file that contains all parameters to `stdout`.\n\n## Direct querying of standard sqlite databases\nq now supports direct querying of standard sqlite databases. The syntax for accessing a table inside an sqlite database is `<sqlite-filename>:::<table_name>`. A query can contain any mix of sqlite files, qsql files or regular delimited files.\n\nFor example, this command joins two tables from two separate sqlite databases:\n```\n$ q \"select count(*) from mydatabase1.sqlite:::mytable1 a left join mydatabase2.sqlite:::mytable2 b on (a.c1 = b.c1)\"\n```\n\nRunning queries on sqlite databases does not usually entail loading the data into memory. Databases are attached to a virtual database and queried directly from disk. This means that querying speed is practically identical to standard sqlite access. This is also true when multiple sqlite databases are used in a single query. The same mechanism is being used by q whenever it uses a qsql file (either directly or as a cache of a delimited fild). \n\nsqlite itself does have a pre-compiled limit of the number of databases that can be attached simultanously. If this limit is reached, then q will attach as many databases as possible, and then continue processing by loading additional tables into memory in order to execute the query. The standard limit in sqlite3 (unless compiled specifically with another limit) is 10 databases. This allows q to access as many as 8 user databases without having to load any data into memory (2 databases are always used for q's internal logic). Using more databases in a single query than this pre-compiled sqlite limit would slow things down, since some of the data would go into memory, but the query should still provide correct results.\n\nWhenever the sqlite database file contains only one table, the table name part can be ommitted, and the user can specify only the sqlite-filename as the table name. For example, querying an sqlite database `mydatabase.sqlite` that only has one table `mytable` is possible with `q \"SELECT ... FROM mydatabase.sqlite\"`. There's no need to specify the table name in this case.\n\nSince `.qsql` files are also standard sqlite files, they can be queried directly as well. This allows the user to actually delete the original CSV file and use the caches as if they were the original files. For example:\n\n```\n$ q \"select count(*) from myfile.csv.qsql\"\n```\n\nNotice that there's no need to write the `:::<table-name>` as part of the table name, since `qsql` files that are created as caches contain only one table (e.g. the table matching the original file).\n\nRunning a query that uses an sqlite/qsql database without specifying a table name will fail if there is more than one table in the database, showing the list of existing tables. This can be used in order to detect which tables exist in the database without resorting to other tools. For example:\n```\n$ q \"select * from chinook.db:::blah\"\nTable blah could not be found in sqlite file chinook.db . Existing table names: albums,sqlite_sequence,artists,customers,employees,genres,invoices,invoice_items,media_types,playlists,playlist_track,tracks,sqlite_stat1\n```\n\n## Storing source data into a disk database\nThe `-S` option (`--save-db-to-disk`) has been modified to match the new capabilities. It works with all types of input tables/files, and writes the output database as a standard sqlite database. I've considered making the output a multi-table `qsql` file (e.g. with the additional metadata that q uses), but some things still need to be ironed out in order to make these qsql files work seamlessly with all other aspects of q. This will probably happen in the next version.  \n\nThis database can be accessed directly by q later on, by providing `<sqlite-database>:::<table-name>` as the table name in the query. The table names that are chosen match the original file names, but go through the following process:\n* The names are normalised in order to by compatible with sqlite restrictions (e.g. `x.csv` is normalised to `x_dot_csv`)\n* duplicate table names are de-deduped by adding `_<sequence-number>` to their names (e.g. two different csv files in separate folders which both have the name `companies` will be written to the file as `companies` and `companies_2`)\n\nThis table-name normalisation happens also inside `.qsql` cache files, but in most cases there won't be any need to know these table names, since q automatically detects table names for databases which have a single-table.\n\n## File-concatenation and wildcard-matching features - Breaking change\nFile concatenation using '+' has been removed in this version, which is a breaking change.\n\nThis was a controversial feature anyway, and can be done using standard SQL relatively easily. It also complicated the caching implementation significantly, and it seemed that it was not worth it. If there's demand for bringing this feature back, please write to me and I'll consider re-adding it. \n\nIf you have a case of using file concatenation, you can use the following SQL instead:\n```\n# Instead of writing\n$ q \"select * from myfile1+myfile2\"\n# Use the following:\n$ q \"select * from (select * from myfile1 UNION ALL select * from myfile2)\"\n```\n\nThis will provide the same results, but the error checking is a bit less robust, so be mindful on whether you're performing the right query on the right files.\n\nConceptually, this is similar to wildcard matching (e.g. `select * from myfolder/myfile*`), but I have decided to leave wildcard-matching intact, since it seems to be a more common use-case. Cache creation and use is limited for now when using wildcards. Use the same method as described above for file concatenation if you wanna make sure that caches are being used.\n\nAfter this version is fully stabilised, I'll make more efforts to consolidate wildcard (and perhaps concatenation) to fully utilise caching seamlessly.\n\n## Code runs only on python 3\nRemoved the dual py2/py3 support. Since q is packaged as a self-contained executable, along with python 3.8 itself, then this is not needed anymore.\n\nUsers which for some reason still use q's main source code file directly and use python 2 would need to stay with the latest 2.0.19 release. In some next version, q's code structure is going to change significantly anyway in order to become a standard python module, so using the main source code file directly would not be possible.\n\nIf you are such a user, and this decision hurts you considerably, please ping me.\n"
  },
  {
    "path": "README.markdown",
    "content": "[![Build and Package](https://github.com/harelba/q/workflows/BuildAndPackage/badge.svg?branch=master)](https://github.com/harelba/q/actions?query=branch%3Amaster)\n\n# q - Text as Data\nq's purpose is to bring SQL expressive power to the Linux command line and to provide easy access to text as actual data.\n\nq allows the following:\n\n* Performing SQL-like statements directly on tabular text data, auto-caching the data in order to accelerate additional querying on the same file. \n* Performing SQL statements directly on multi-file sqlite3 databases, without having to merge them or load them into memory\n\nThe following table shows the impact of using caching:\n\n|    Rows   | Columns | File Size | Query time without caching | Query time with caching | Speed Improvement |\n|:---------:|:-------:|:---------:|:--------------------------:|:-----------------------:|:-----------------:|\n| 5,000,000 |   100   |   4.8GB   |    4 minutes, 47 seconds   |       1.92 seconds      |        x149       |\n| 1,000,000 |   100   |   983MB   |        50.9 seconds        |      0.461 seconds      |        x110       |\n| 1,000,000 |    50   |   477MB   |        27.1 seconds        |      0.272 seconds      |        x99        |\n|  100,000  |   100   |    99MB   |         5.2 seconds        |      0.141 seconds      |        x36        |\n|  100,000  |    50   |    48MB   |         2.7 seconds        |      0.105 seconds      |        x25        |\n\nNotice that for the current version, caching is **not enabled** by default, since the caches take disk space. Use `-C readwrite` or `-C read` to enable it for a query, or add `caching_mode` to `.qrc` to set a new default.\n \nq's web site is [https://harelba.github.io/q/](https://harelba.github.io/q/) or [https://q.textasdata.wiki](https://q.textasdata.wiki) It contains everything you need to download and use q immediately.\n\n\n## Usage Examples\nq treats ordinary files as database tables, and supports all SQL constructs, such as `WHERE`, `GROUP BY`, `JOIN`s, etc. It supports automatic column name and type detection, and provides full support for multiple character encodings.\n\nHere are some example commands to get the idea:\n\n```bash\n$ q \"SELECT COUNT(*) FROM ./clicks_file.csv WHERE c3 > 32.3\"\n\n$ ps -ef | q -H \"SELECT UID, COUNT(*) cnt FROM - GROUP BY UID ORDER BY cnt DESC LIMIT 3\"\n\n$ q \"select count(*) from some_db.sqlite3:::albums a left join another_db.sqlite3:::tracks t on (a.album_id = t.album_id)\"\n```\n\nDetailed examples are in [here](https://harelba.github.io/q/#examples)\n\n## Installation.\n**New Major Version `3.1.6` is out with a lot of significant additions.**\n\nInstructions for all OSs are [here](https://harelba.github.io/q/#installation).\n\nThe previous version `2.0.19` Can still be downloaded from [here](https://github.com/harelba/q/releases/tag/2.0.19)  \n\n## Contact\nAny feedback/suggestions/complaints regarding this tool would be much appreciated. Contributions are most welcome as well, of course.\n\nLinkedin: [Harel Ben Attia](https://www.linkedin.com/in/harelba/)\n\nTwitter [@harelba](https://twitter.com/harelba)\n\nEmail [harelba@gmail.com](mailto:harelba@gmail.com)\n\nq on twitter: [#qtextasdata](https://twitter.com/hashtag/qtextasdata?src=hashtag_click)\n\nPatreon: [harelba](https://www.patreon.com/harelba) - All the money received is donated to the [Center for the Prevention and Treatment of Domestic Violence](https://www.gov.il/he/departments/bureaus/molsa-almab-ramla) in my hometown - Ramla, Israel.\n\n\n"
  },
  {
    "path": "benchmark-config.sh",
    "content": "#!/bin/bash\n\nBENCHMARK_PYTHON_VERSIONS=(3.8.5)\n"
  },
  {
    "path": "bin/.qrc",
    "content": "#\n# q options ini file. Put either in your home folder as .qrc or in the working directory \n#   (both will be merged in that order)\n#\n# All options should reside in an [options] section\n#\n# Available options:\n# * delimiter - escaped string (e.g. use \\t for tab or \\x20 for space)\n# * outputdelimiter - escaped string (e.g. use \\t for tab or \\x20 for space)\n# * gzipped - boolean True or False\n# * beautify - boolean True or False\n# * header_skip - integer number of lines to skip at the beginning of the file\n# * formatting - regular string - post-query formatting - see docs for details\n# * encoding - regular string - required encoding.\n#\n# All options have a matching command line option. See --help for details on defaults\n\n[options]\n#delimiter: \\t\n#output_delimiter: \\t\n#gzipped: False\n#beautify: True\n#skip_header: False\n#formatting: 1=%4.3f,2=%4.3f\n#encoding: UTF-8\n"
  },
  {
    "path": "bin/__init__.py",
    "content": "#!/usr/bin/env python\n\n"
  },
  {
    "path": "bin/q.bat",
    "content": "@echo off\n\nsetlocal\nif exist \"%~dp0..\\python.exe\" ( \"%~dp0..\\python\" \"%~dp0q\" %* ) else ( python \"%~dp0q\" %* )\nendlocal\n"
  },
  {
    "path": "bin/q.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n#   Copyright (C) 2012-2021 Harel Ben-Attia\n#\n#   This program is free software; you can redistribute it and/or modify\n#   it under the terms of the GNU General Public License as published by\n#   the Free Software Foundation; either version 3, or (at your option)\n#   any later version.\n#\n#   This program is distributed in the hope that it will be useful,\n#   but WITHOUT ANY WARRANTY; without even the implied warranty of\n#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n#   GNU General Public License for more details (doc/LICENSE contains\n#   a copy of it)\n#\n#\n# Name      : q (With respect to The Q Continuum)\n# Author    : Harel Ben-Attia - harelba@gmail.com, harelba @ github, @harelba on twitter\n#\n#\n# q allows performing SQL-like statements on tabular text data.\n#\n# Its purpose is to bring SQL expressive power to manipulating text data using the Linux command line.\n#\n# Full Documentation and details in https://harelba.github.io/q/\n#\n# Run with --help for command line details\n#\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom collections import OrderedDict\nfrom sqlite3.dbapi2 import OperationalError\nfrom uuid import uuid4\n\nq_version = '3.1.6'\n\n#__all__ = [ 'QTextAsData' ]\n\nimport os\nimport sys\nimport sqlite3\nimport glob\nfrom argparse import ArgumentParser\nimport codecs\nimport locale\nimport time\nimport re\nfrom six.moves import configparser, range, filter\nimport traceback\nimport csv\nimport uuid\nimport math\nimport six\nimport io\nimport json\nimport datetime\nimport hashlib\n\nif six.PY2:\n    assert False, 'Python 2 is not longer supported by q'\n\nlong = int\nunicode = six.text_type\n\nDEBUG = bool(os.environ.get('Q_DEBUG', None)) or '-V' in sys.argv\nSQL_DEBUG = False\n\nif DEBUG:\n    def xprint(*args,**kwargs):\n        print(datetime.datetime.utcnow().isoformat(),\" DEBUG \",*args,file=sys.stderr,**kwargs)\n\n    def iprint(*args,**kwargs):\n        print(datetime.datetime.utcnow().isoformat(),\" INFO \",*args,file=sys.stderr,**kwargs)\n\n    def sqlprint(*args,**kwargs):\n        pass\nelse:\n    def xprint(*args,**kwargs): pass\n    def iprint(*args,**kwargs): pass\n    def sqlprint(*args,**kwargs): pass\n\nif SQL_DEBUG:\n    def sqlprint(*args,**kwargs):\n        print(datetime.datetime.utcnow().isoformat(), \" SQL \", *args, file=sys.stderr, **kwargs)\n\n\ndef get_stdout_encoding(encoding_override=None):\n    if encoding_override is not None and encoding_override != 'none':\n       return encoding_override\n\n    if sys.stdout.isatty():\n        return sys.stdout.encoding\n    else:\n        return locale.getpreferredencoding()\n\nSHOW_SQL = False\n\nsha_algorithms = {\n    1 : hashlib.sha1,\n    224: hashlib.sha224,\n    256: hashlib.sha256,\n    386: hashlib.sha384,\n    512: hashlib.sha512\n}\n\ndef sha(data,algorithm,encoding):\n    try:\n        f = sha_algorithms[algorithm]\n        return f(six.text_type(data).encode(encoding)).hexdigest()\n    except Exception as e:\n        print(e)\n\n# For backward compatibility only (doesn't handle encoding well enough)\ndef sha1(data):\n    return hashlib.sha1(six.text_type(data).encode('utf-8')).hexdigest()\n\n# TODO Add caching of compiled regexps - Will be added after benchmarking capability is baked in\ndef regexp(regular_expression, data):\n    if data is not None:\n        if not isinstance(data, str) and not isinstance(data, unicode):\n            data = str(data)\n        return re.search(regular_expression, data) is not None\n    else:\n        return False\n\ndef regexp_extract(regular_expression, data,group_number):\n    if data is not None:\n        if not isinstance(data, str) and not isinstance(data, unicode):\n            data = str(data)\n        m = re.search(regular_expression, data)\n        if m is not None:\n            return m.groups()[group_number]\n    else:\n        return False\n\ndef md5(data,encoding):\n    m = hashlib.md5()\n    m.update(six.text_type(data).encode(encoding))\n    return m.hexdigest()\n\ndef sqrt(data):\n    return math.sqrt(data)\n\ndef power(data,p):\n    return data**p\n\ndef file_ext(data):\n    if data is None:\n        return None\n\n    return os.path.splitext(data)[1]\n\ndef file_folder(data):\n    if data is None:\n        return None\n    return os.path.split(data)[0]\n\ndef file_basename(data):\n    if data is None:\n        return None\n    return os.path.split(data)[1]\n    \ndef file_basename_no_ext(data):\n    if data is None:\n        return None\n\n    return os.path.split(os.path.splitext(data)[0])[-1]\n\ndef percentile(l, p):\n    # TODO Alpha implementation, need to provide multiple interpolation methods, and add tests\n    if not l:\n        return None\n    k = p*(len(l) - 1)\n    f = math.floor(k)\n    c = math.ceil(k)\n    if c == f:\n        return l[int(k)]\n    return (c-k) * l[int(f)] + (k-f) * l[int(c)]\n\n# TODO Streaming Percentile to prevent memory consumption blowup for large datasets\nclass StrictPercentile(object):\n    def __init__(self):\n        self.values = []\n        self.p = None\n\n    def step(self,value,p):\n        if self.p is None:\n          self.p = p\n        self.values.append(value)\n\n    def finalize(self):\n        if len(self.values) == 0 or (self.p < 0 or self.p > 1):\n            return None\n        else:\n            return percentile(sorted(self.values),self.p)\n\nclass StdevPopulation(object):\n    def __init__(self):\n        self.M = 0.0\n        self.S = 0.0\n        self.k = 0\n\n    def step(self, value):\n        try:\n            # Ignore nulls\n            if value is None:\n                return\n            val = float(value) # if fails, skips this iteration, which also ignores nulls\n            tM = self.M\n            self.k += 1\n            self.M += ((val - tM) / self.k)\n            self.S += ((val - tM) * (val - self.M))\n        except ValueError:\n            # TODO propagate udf errors to console\n            raise Exception(\"Data is not numeric when calculating stddev (%s)\" % value)\n\n    def finalize(self):\n        if self.k <= 1: # avoid division by zero\n            return None\n        else:\n            return math.sqrt(self.S / (self.k))\n\nclass StdevSample(object):\n    def __init__(self):\n        self.M = 0.0\n        self.S = 0.0\n        self.k = 0\n\n    def step(self, value):\n        try:\n            # Ignore nulls\n            if value is None:\n                return\n            val = float(value) # if fails, skips this iteration, which also ignores nulls\n            tM = self.M\n            self.k += 1\n            self.M += ((val - tM) / self.k)\n            self.S += ((val - tM) * (val - self.M))\n        except ValueError:\n            # TODO propagate udf errors to console\n            raise Exception(\"Data is not numeric when calculating stddev (%s)\" % value)\n\n    def finalize(self):\n        if self.k <= 1: # avoid division by zero\n            return None\n        else:\n            return math.sqrt(self.S / (self.k-1))\n\nclass FunctionType(object):\n    REGULAR = 1\n    AGG = 2\n\nclass UserFunctionDef(object):\n    def __init__(self,func_type,name,usage,description,func_or_obj,param_count):\n        self.func_type = func_type\n        self.name = name\n        self.usage = usage\n        self.description = description\n        self.func_or_obj = func_or_obj\n        self.param_count = param_count\n\nuser_functions = [\n    UserFunctionDef(FunctionType.REGULAR,\n                    \"regexp\",\"regexp(<regular_expression>,<expr>) = <1|0>\",\n                    \"Find regexp in string expression. Returns 1 if found or 0 if not\",\n                    regexp,\n                    2),\n    UserFunctionDef(FunctionType.REGULAR,\n                    \"regexp_extract\",\"regexp_extract(<regular_expression>,<expr>,group_number) = <substring|null>\",\n                    \"Get regexp capture group content\",\n                    regexp_extract,\n                    3),\n    UserFunctionDef(FunctionType.REGULAR,\n                    \"sha\",\"sha(<expr>,<encoding>,<algorithm>) = <hex-string-of-sha>\",\n                    \"Calculate sha of some expression. Algorithm can be one of 1,224,256,384,512. For now encoding must be manually provided. Will use the input encoding automatically in the future.\",\n                    sha,\n                    3),\n    UserFunctionDef(FunctionType.REGULAR,\n                    \"sha1\",\"sha1(<expr>) = <hex-string-of-sha>\",\n                    \"Exists for backward compatibility only, since it doesn't handle encoding properly. Calculates sha1 of some expression\",\n                    sha1,\n                    1),\n    UserFunctionDef(FunctionType.REGULAR,\n                    \"md5\",\"md5(<expr>,<encoding>) = <hex-string-of-md5>\",\n                    \"Calculate md5 of expression. Returns a hex-string of the result. Currently requires to manually provide the encoding of the data. Will be taken automatically from the input encoding in the future.\",\n                    md5,\n                    2),\n    UserFunctionDef(FunctionType.REGULAR,\n                    \"sqrt\",\"sqrt(<expr>) = <square-root>\",\n                    \"Calculate the square root of the expression\",\n                    sqrt,\n                    1),\n    UserFunctionDef(FunctionType.REGULAR,\n                    \"power\",\"power(<expr1>,<expr2>) = <expr1-to-the-power-of-expr2>\",\n                    \"Raise expr1 to the power of expr2\",\n                    power,\n                    2),\n    UserFunctionDef(FunctionType.REGULAR,\n                    \"file_ext\",\"file_ext(<expr>) = <filename-extension-or-empty-string>\",\n                    \"Get the extension of a filename\",\n                    file_ext,\n                    1),\n    UserFunctionDef(FunctionType.REGULAR,\n                    \"file_folder\",\"file_folder(<expr>) = <folder-name-of-filename>\",\n                    \"Get the folder part of a filename\",\n                    file_folder,\n                    1),\n    UserFunctionDef(FunctionType.REGULAR,\n                    \"file_basename\",\"file_basename(<expr>) = <basename-of-filename-including-extension>\",\n                    \"Get the basename of a filename, including extension if any\",\n                    file_basename,\n                    1),\n    UserFunctionDef(FunctionType.REGULAR,\n                    \"file_basename_no_ext\",\"file_basename_no_ext(<expr>) = <basename-of-filename-without-extension>\",\n                    \"Get the basename of a filename, without the extension if there is one\",\n                    file_basename_no_ext,\n                    1),\n    UserFunctionDef(FunctionType.AGG,\n                    \"percentile\",\"percentile(<expr>,<percentile-in-the-range-0-to-1>) = <percentile-value>\",\n                    \"Calculate the strict percentile of a set of a values.\",\n                    StrictPercentile,\n                    2),\n    UserFunctionDef(FunctionType.AGG,\n                    \"stddev_pop\",\"stddev_pop(<expr>) = <stddev-value>\",\n                    \"Calculate the population standard deviation of a set of values\",\n                    StdevPopulation,\n                    1),\n    UserFunctionDef(FunctionType.AGG,\n                    \"stddev_sample\",\"stddev_sample(<expr>) = <stddev-value>\",\n                    \"Calculate the sample standard deviation of a set of values\",\n                    StdevSample,\n                    1)\n]\n\ndef print_user_functions():\n    for udf in user_functions:\n        print(\"Function: %s\" % udf.name)\n        print(\"     Usage: %s\" % udf.usage)\n        print(\"     Description: %s\" % udf.description)\n\nclass Sqlite3DBResults(object):\n    def __init__(self,query_column_names,results):\n        self.query_column_names = query_column_names\n        self.results = results\n\n    def __str__(self):\n        return \"Sqlite3DBResults<result_count=%d,query_column_names=%s>\" % (len(self.results),str(self.query_column_names))\n    __repr__ = __str__\n\ndef get_sqlite_type_affinity(sqlite_type):\n    sqlite_type = sqlite_type.upper()\n    if 'INT' in sqlite_type:\n        return 'INTEGER'\n    elif 'CHAR' in sqlite_type or 'TEXT' in sqlite_type or 'CLOB' in sqlite_type:\n        return 'TEXT'\n    elif 'BLOB' in sqlite_type:\n        return 'BLOB'\n    elif 'REAL' in sqlite_type or 'FLOA' in sqlite_type or 'DOUB' in sqlite_type:\n        return 'REAL'\n    else:\n        return 'NUMERIC'\n\ndef sqlite_type_to_python_type(sqlite_type):\n    SQLITE_AFFINITY_TO_PYTHON_TYPE_NAMES = {\n        'INTEGER': long,\n        'TEXT': unicode,\n        'BLOB': bytes,\n        'REAL': float,\n        'NUMERIC': float\n    }\n    return SQLITE_AFFINITY_TO_PYTHON_TYPE_NAMES[get_sqlite_type_affinity(sqlite_type)]\n\n\nclass Sqlite3DB(object):\n    # TODO Add metadata table with qsql file version\n\n    QCATALOG_TABLE_NAME = '_qcatalog'\n    NUMERIC_COLUMN_TYPES =  {int, long, float}\n    PYTHON_TO_SQLITE_TYPE_NAMES = { str: 'TEXT', int: 'INT', long : 'INT' , float: 'REAL', None: 'TEXT' }\n\n\n    def __str__(self):\n        return \"Sqlite3DB<url=%s>\" % self.sqlite_db_url\n    __repr__ = __str__\n\n    def __init__(self, db_id, sqlite_db_url, sqlite_db_filename, create_qcatalog, show_sql=SHOW_SQL):\n        self.show_sql = show_sql\n        self.create_qcatalog = create_qcatalog\n\n        self.db_id = db_id\n        # TODO Is this needed anymore?\n        self.sqlite_db_filename = sqlite_db_filename\n        self.sqlite_db_url = sqlite_db_url\n        self.conn = sqlite3.connect(self.sqlite_db_url, uri=True)\n        self.last_temp_table_id = 10000\n        self.cursor = self.conn.cursor()\n        self.add_user_functions()\n\n        if create_qcatalog:\n            self.create_qcatalog_table()\n        else:\n            xprint('Not creating qcatalog for db_id %s' % db_id)\n\n    def retrieve_all_table_names(self):\n        return [x[0] for x in self.execute_and_fetch(\"select tbl_name from sqlite_master where type='table'\").results]\n\n    def get_sqlite_table_info(self,table_name):\n        return self.execute_and_fetch('PRAGMA table_info(%s)' % table_name).results\n\n    def get_sqlite_database_list(self):\n        return self.execute_and_fetch('pragma database_list').results\n\n    def find_new_table_name(self,planned_table_name):\n        existing_table_names = self.retrieve_all_table_names()\n\n        possible_indices = range(1,1000)\n\n        for index in possible_indices:\n            if index == 1:\n                suffix = ''\n            else:\n                suffix = '_%s' % index\n\n            table_name_attempt = '%s%s' % (planned_table_name,suffix)\n\n            if table_name_attempt not in existing_table_names:\n                xprint(\"Found free table name %s in db %s for planned table name %s\" % (table_name_attempt,self.db_id,planned_table_name))\n                return table_name_attempt\n\n        # TODO Add test for this\n        raise Exception('Cannot find free table name in db %s for planned table name %s' % (self.db_id,planned_table_name))\n\n    def create_qcatalog_table(self):\n        if not self.qcatalog_table_exists():\n            xprint(\"qcatalog table does not exist. Creating it\")\n            r = self.conn.execute(\"\"\"CREATE TABLE %s ( \n                               qcatalog_entry_id text not null primary key,\n                               content_signature_key text,\n                               temp_table_name text,\n                               content_signature text,\n                               creation_time text,\n                               source_type text,\n                               source text)\"\"\" % self.QCATALOG_TABLE_NAME).fetchall()\n        else:\n            xprint(\"qcatalog table already exists. No need to create it\")\n\n    def qcatalog_table_exists(self):\n        return sqlite_table_exists(self.conn,self.QCATALOG_TABLE_NAME)\n\n    def calculate_content_signature_key(self,content_signature):\n        assert type(content_signature) == OrderedDict\n        pp = json.dumps(content_signature,sort_keys=True)\n        xprint(\"Calculating content signature for:\",pp,six.b(pp))\n        return hashlib.sha1(six.b(pp)).hexdigest()\n\n    def add_to_qcatalog_table(self, temp_table_name, content_signature, creation_time,source_type, source):\n        assert source is not None\n        assert source_type is not None\n        content_signature_key = self.calculate_content_signature_key(content_signature)\n        xprint(\"db_id: %s Adding to qcatalog table: %s. Calculated signature key %s\" % (self.db_id, temp_table_name,content_signature_key))\n        r = self.execute_and_fetch(\n            'INSERT INTO %s (qcatalog_entry_id,content_signature_key, temp_table_name,content_signature,creation_time,source_type,source) VALUES (?,?,?,?,?,?,?)' % self.QCATALOG_TABLE_NAME,\n                              (str(uuid4()),content_signature_key,temp_table_name,json.dumps(content_signature),creation_time,source_type,source))\n        # Ensure transaction is completed\n        self.conn.commit()\n\n    def get_from_qcatalog(self, content_signature):\n        content_signature_key = self.calculate_content_signature_key(content_signature)\n        xprint(\"Finding table in db_id %s that matches content signature key %s\" % (self.db_id,content_signature_key))\n\n        field_names = [\"content_signature_key\", \"temp_table_name\", \"content_signature\", \"creation_time\",\"source_type\",\"source\",\"qcatalog_entry_id\"]\n\n        q = \"SELECT %s FROM %s where content_signature_key = ?\" % (\",\".join(field_names),self.QCATALOG_TABLE_NAME)\n        r = self.execute_and_fetch(q,(content_signature_key,))\n\n        if r is None:\n            return None\n\n        if len(r.results) == 0:\n            return None\n\n        if len(r.results) > 1:\n            raise Exception(\"Bug - Exactly one result should have been provided: %s\" % str(r.results))\n\n        d = dict(zip(field_names,r.results[0]))\n        return d\n\n    def get_from_qcatalog_using_table_name(self, temp_table_name):\n        xprint(\"getting from qcatalog using table name\")\n\n        field_names = [\"content_signature\", \"temp_table_name\",\"creation_time\",\"source_type\",\"source\",\"content_signature_key\",\"qcatalog_entry_id\"]\n\n        q = \"SELECT %s FROM %s where temp_table_name = ?\" % (\",\".join(field_names),self.QCATALOG_TABLE_NAME)\n        xprint(\"Query from qcatalog %s params %s\" % (q,str(temp_table_name,)))\n        r = self.execute_and_fetch(q,(temp_table_name,))\n        xprint(\"results: \",r.results)\n\n        if r is None:\n            return None\n\n        if len(r.results) == 0:\n            return None\n\n        if len(r.results) > 1:\n            raise Exception(\"Bug - Exactly one result should have been provided: %s\" % str(r.results))\n\n        d = dict(zip(field_names,r.results[0]))\n        # content_signature should be the first in the list of field_names\n        cs = OrderedDict(json.loads(r.results[0][0]))\n        if self.calculate_content_signature_key(cs) != d['content_signature_key']:\n            raise Exception('Table contains an invalid entry - content signature key is not matching the actual content signature')\n        return d\n\n    def get_all_from_qcatalog(self):\n        xprint(\"getting from qcatalog using table name\")\n\n        field_names = [\"temp_table_name\", \"content_signature\", \"creation_time\",\"source_type\",\"source\",\"qcatalog_entry_id\"]\n\n        q = \"SELECT %s FROM %s\" % (\",\".join(field_names),self.QCATALOG_TABLE_NAME)\n        xprint(\"Query from qcatalog %s\" % q)\n        r = self.execute_and_fetch(q)\n\n        if r is None:\n            return None\n\n        def convert(res):\n            d = dict(zip(field_names, res))\n            cs = OrderedDict(json.loads(res[1]))\n            d['content_signature_key'] = self.calculate_content_signature_key(cs)\n            return d\n\n        rr = [convert(r) for r in r.results]\n\n        return rr\n\n    def done(self):\n        xprint(\"Closing database %s\" % self.db_id)\n        try:\n            self.conn.commit()\n            self.conn.close()\n            xprint(\"Database %s closed\" % self.db_id)\n        except Exception as e:\n            xprint(\"Could not close database %s\" % self.db_id)\n            raise\n\n    def add_user_functions(self):\n        for udf in user_functions:\n            if type(udf.func_or_obj) == type(object):\n                self.conn.create_aggregate(udf.name,udf.param_count,udf.func_or_obj)\n            elif type(udf.func_or_obj) == type(md5):\n                self.conn.create_function(udf.name,udf.param_count,udf.func_or_obj)\n            else:\n                raise Exception(\"Invalid user function definition %s\" % str(udf))\n\n    def is_numeric_type(self, column_type):\n        return column_type in Sqlite3DB.NUMERIC_COLUMN_TYPES\n\n    def update_many(self, sql, params):\n        try:\n            sqlprint(sql, \" params: \" + str(params))\n            self.cursor.executemany(sql, params)\n            _ = self.cursor.fetchall()\n        finally:\n            pass  # cursor.close()\n\n    def execute_and_fetch(self, q,params = None):\n        try:\n            try:\n                if self.show_sql:\n                    print(repr(q))\n                if params is None:\n                    r = self.cursor.execute(q)\n                else:\n                    r = self.cursor.execute(q,params)\n                if self.cursor.description is not None:\n                    # we decode the column names, so they can be encoded to any output format later on\n                    query_column_names = [c[0] for c in self.cursor.description]\n                else:\n                    query_column_names = None\n                result = self.cursor.fetchall()\n            finally:\n                pass  # cursor.close()\n        except OperationalError as e:\n            raise SqliteOperationalErrorException(\"Failed executing sqlite query %s with params %s . error: %s\" % (q,params,str(e)),e)\n        return Sqlite3DBResults(query_column_names,result)\n\n    def _get_as_list_str(self, l):\n        return \",\".join(['\"%s\"' % x.replace('\"', '\"\"') for x in l])\n\n    def generate_insert_row(self, table_name, column_names):\n        col_names_str = self._get_as_list_str(column_names)\n        question_marks = \", \".join([\"?\" for i in range(0, len(column_names))])\n        return 'INSERT INTO %s (%s) VALUES (%s)' % (table_name, col_names_str, question_marks)\n\n    # Get a list of column names so order will be preserved (Could have used OrderedDict, but\n    # then we would need python 2.7)\n    def generate_create_table(self, table_name, column_names, column_dict):\n        # Convert dict from python types to db types\n        column_name_to_db_type = dict(\n            (n, Sqlite3DB.PYTHON_TO_SQLITE_TYPE_NAMES[t]) for n, t in six.iteritems(column_dict))\n        column_defs = ','.join(['\"%s\" %s' % (\n            n.replace('\"', '\"\"'), column_name_to_db_type[n]) for n in column_names])\n        return 'CREATE TABLE %s (%s)' % (table_name, column_defs)\n\n    def generate_temp_table_name(self):\n        # WTF - From my own past mutable-self\n        self.last_temp_table_id += 1\n        tn = \"temp_table_%s\" % self.last_temp_table_id\n        return tn\n\n    def generate_drop_table(self, table_name):\n        return \"DROP TABLE %s\" % table_name\n\n    def drop_table(self, table_name):\n        return self.execute_and_fetch(self.generate_drop_table(table_name))\n\n    def attach_and_copy_table(self, from_db, relevant_table,stop_after_analysis):\n        xprint(\"Attaching %s into db %s and copying table %s into it\" % (from_db,self,relevant_table))\n        temp_db_id = 'temp_db_id'\n        q = \"attach '%s' as %s\" % (from_db.sqlite_db_url,temp_db_id)\n        xprint(\"Attach query: %s\" % q)\n        c = self.execute_and_fetch(q)\n\n        new_temp_table_name = 'temp_table_%s' % (self.last_temp_table_id + 1)\n        fully_qualified_table_name = '%s.%s' % (temp_db_id,relevant_table)\n\n        if stop_after_analysis:\n            limit = ' limit 100'\n        else:\n            limit = ''\n\n        copy_query = 'create table %s as select * from %s %s' % (new_temp_table_name,fully_qualified_table_name,limit)\n        copy_results = self.execute_and_fetch(copy_query)\n        xprint(\"Copied %s.%s into %s in db_id %s. Results %s\" % (temp_db_id,relevant_table,new_temp_table_name,self.db_id,copy_results))\n        self.last_temp_table_id += 1\n\n        xprint(\"Copied table into %s. Detaching db that was attached temporarily\" % self.db_id)\n\n        q = \"detach database %s\" % temp_db_id\n        xprint(\"detach query: %s\" % q)\n        c = self.execute_and_fetch(q)\n        xprint(c)\n        return new_temp_table_name\n\n\nclass CouldNotConvertStringToNumericValueException(Exception):\n\n    def __init__(self, msg):\n        self.msg = msg\n\n    def __str(self):\n        return repr(self.msg)\n\nclass SqliteOperationalErrorException(Exception):\n\n    def __init__(self, msg,original_error):\n        self.msg = msg\n        self.original_error = original_error\n\n    def __str(self):\n        return repr(self.msg) + \"//\" + repr(self.original_error)\n\nclass IncorrectDefaultValueException(Exception):\n\n    def __init__(self, option_type,option,actual_value):\n        self.option_type = option_type\n        self.option = option\n        self.actual_value = actual_value\n\n    def __str__(self):\n        return repr(self)\n\nclass NonExistentTableNameInQsql(Exception):\n\n    def __init__(self, qsql_filename,table_name,existing_table_names):\n        self.qsql_filename = qsql_filename\n        self.table_name = table_name\n        self.existing_table_names = existing_table_names\n\nclass NonExistentTableNameInSqlite(Exception):\n\n    def __init__(self, qsql_filename,table_name,existing_table_names):\n        self.qsql_filename = qsql_filename\n        self.table_name = table_name\n        self.existing_table_names = existing_table_names\n\nclass TooManyTablesInQsqlException(Exception):\n\n    def __init__(self, qsql_filename,existing_table_names):\n        self.qsql_filename = qsql_filename\n        self.existing_table_names = existing_table_names\n\nclass NoTableInQsqlExcption(Exception):\n\n    def __init__(self, qsql_filename):\n        self.qsql_filename = qsql_filename\n\nclass TooManyTablesInSqliteException(Exception):\n\n    def __init__(self, qsql_filename,existing_table_names):\n        self.qsql_filename = qsql_filename\n        self.existing_table_names = existing_table_names\n\nclass NoTablesInSqliteException(Exception):\n\n    def __init__(self, sqlite_filename):\n        self.sqlite_filename = sqlite_filename\n\nclass ColumnMaxLengthLimitExceededException(Exception):\n\n    def __init__(self, msg):\n        self.msg = msg\n\n    def __str(self):\n        return repr(self.msg)\n\nclass CouldNotParseInputException(Exception):\n\n    def __init__(self, msg):\n        self.msg = msg\n\n    def __str(self):\n        return repr(self.msg)\n\nclass BadHeaderException(Exception):\n\n    def __init__(self, msg):\n        self.msg = msg\n\n    def __str(self):\n        return repr(self.msg)\n\nclass EncodedQueryException(Exception):\n\n    def __init__(self, msg):\n        self.msg = msg\n\n    def __str(self):\n        return repr(self.msg)\n\n\nclass CannotUnzipDataStreamException(Exception):\n\n    def __init__(self):\n        pass\n\nclass UniversalNewlinesExistException(Exception):\n\n    def __init__(self):\n        pass\n\nclass EmptyDataException(Exception):\n\n    def __init__(self):\n        pass\n\nclass MissingHeaderException(Exception):\n\n    def __init__(self,msg):\n        self.msg = msg\n\nclass InvalidQueryException(Exception):\n\n    def __init__(self,msg):\n        self.msg = msg\n\nclass TooManyAttachedDatabasesException(Exception):\n\n    def __init__(self,msg):\n        self.msg = msg\n\nclass FileNotFoundException(Exception):\n\n    def __init__(self, msg):\n        self.msg = msg\n\n    def __str(self):\n        return repr(self.msg)\n\nclass UnknownFileTypeException(Exception):\n\n    def __init__(self, msg):\n        self.msg = msg\n\n    def __str(self):\n        return repr(self.msg)\n\n\nclass ColumnCountMismatchException(Exception):\n\n    def __init__(self, msg):\n        self.msg = msg\n\nclass ContentSignatureNotFoundException(Exception):\n\n    def __init__(self, msg):\n        self.msg = msg\n\nclass StrictModeColumnCountMismatchException(Exception):\n\n    def __init__(self,atomic_fn, expected_col_count,actual_col_count,lines_read):\n        self.atomic_fn = atomic_fn\n        self.expected_col_count = expected_col_count\n        self.actual_col_count = actual_col_count\n        self.lines_read = lines_read\n\nclass FluffyModeColumnCountMismatchException(Exception):\n\n    def __init__(self,atomic_fn, expected_col_count,actual_col_count,lines_read):\n        self.atomic_fn = atomic_fn\n        self.expected_col_count = expected_col_count\n        self.actual_col_count = actual_col_count\n        self.lines_read = lines_read\n\nclass ContentSignatureDiffersException(Exception):\n\n    def __init__(self,original_filename, other_filename, filenames_str,key,source_value,signature_value):\n        self.original_filename = original_filename\n        self.other_filename = other_filename\n        self.filenames_str = filenames_str\n        self.key = key\n        self.source_value = source_value\n        self.signature_value = signature_value\n\n\nclass ContentSignatureDataDiffersException(Exception):\n\n    def __init__(self,msg):\n        self.msg = msg\n\n\nclass InvalidQSqliteFileException(Exception):\n\n    def __init__(self,msg):\n        self.msg = msg\n\n\nclass MaximumSourceFilesExceededException(Exception):\n\n    def __init__(self,msg):\n        self.msg = msg\n\n\n\n# Simplistic Sql \"parsing\" class... We'll eventually require a real SQL parser which will provide us with a parse tree\n#\n# A \"qtable\" is a filename which behaves like an SQL table...\nclass Sql(object):\n\n    def __init__(self, sql, data_streams):\n        # Currently supports only standard SELECT statements\n\n        # Holds original SQL\n        self.sql = sql\n        # Holds sql parts\n        self.sql_parts = sql.split()\n        self.data_streams = data_streams\n\n        self.qtable_metadata_dict = OrderedDict()\n\n        # Set of qtable names\n        self.qtable_names = []\n        # Dict from qtable names to their positions in sql_parts. Value here is a *list* of positions,\n        # since it is possible that the same qtable_name (file) is referenced in multiple positions\n        # and we don't want the database table to be recreated for each\n        # reference\n        self.qtable_name_positions = {}\n        # Dict from qtable names to their effective (actual database) table\n        # names\n        self.qtable_name_effective_table_names = {}\n\n        self.query_column_names = None\n\n        # Go over all sql parts\n        idx = 0\n        while idx < len(self.sql_parts):\n            # Get the part string\n            part = self.sql_parts[idx]\n            # If it's a FROM or a JOIN\n            if part.upper() in ['FROM', 'JOIN']:\n                # and there is nothing after it,\n                if idx == len(self.sql_parts) - 1:\n                    # Just fail\n                    raise InvalidQueryException(\n                        'FROM/JOIN is missing a table name after it')\n\n                qtable_name = self.sql_parts[idx + 1]\n                # Otherwise, the next part contains the qtable name. In most cases the next part will be only the qtable name.\n                # We handle one special case here, where this is a subquery as a column: \"SELECT (SELECT ... FROM qtable),100 FROM ...\".\n                # In that case, there will be an ending paranthesis as part of the name, and we want to handle this case gracefully.\n                # This is obviously a hack of a hack :) Just until we have\n                # complete parsing capabilities\n                if ')' in qtable_name:\n                    leftover = qtable_name[qtable_name.index(')'):]\n                    self.sql_parts.insert(idx + 2, leftover)\n                    qtable_name = qtable_name[:qtable_name.index(')')]\n                    self.sql_parts[idx + 1] = qtable_name\n\n                if qtable_name[0] != '(':\n                    normalized_qtable_name = self.normalize_qtable_name(qtable_name)\n                    xprint(\"Normalized qtable name for %s is %s\" % (qtable_name,normalized_qtable_name))\n                    self.qtable_names += [normalized_qtable_name]\n\n                    if normalized_qtable_name not in self.qtable_name_positions.keys():\n                        self.qtable_name_positions[normalized_qtable_name] = []\n\n                    self.qtable_name_positions[normalized_qtable_name].append(idx + 1)\n                    self.sql_parts[idx + 1] = normalized_qtable_name\n                    idx += 2\n                else:\n                    idx += 1\n            else:\n                idx += 1\n        xprint(\"Final sql parts: %s\" % self.sql_parts)\n\n    def normalize_qtable_name(self,qtable_name):\n        if self.data_streams.is_data_stream(qtable_name):\n            return qtable_name\n\n        if ':::' in qtable_name:\n            qsql_filename, table_name = qtable_name.split(\":::\", 1)\n            return '%s:::%s' % (os.path.realpath(os.path.abspath(qsql_filename)),table_name)\n        else:\n            return os.path.realpath(os.path.abspath(qtable_name))\n\n    def set_effective_table_name(self, qtable_name, effective_table_name):\n        if qtable_name in self.qtable_name_effective_table_names.keys():\n            if self.qtable_name_effective_table_names[qtable_name] != effective_table_name:\n                raise Exception(\n                    \"Already set effective table name for qtable %s. Trying to change the effective table name from %s to %s\" %\n                    (qtable_name,self.qtable_name_effective_table_names[qtable_name],effective_table_name))\n\n        xprint(\"Setting effective table name for %s - effective table name is set to %s\" % (qtable_name,effective_table_name))\n        self.qtable_name_effective_table_names[\n            qtable_name] = effective_table_name\n\n    def get_effective_sql(self,table_name_mapping=None):\n        if len(list(filter(lambda x: x is None, self.qtable_name_effective_table_names))) != 0:\n            assert False, 'There are qtables without effective tables'\n\n        effective_sql = [x for x in self.sql_parts]\n\n        xprint(\"Effective table names\",self.qtable_name_effective_table_names)\n        for qtable_name, positions in six.iteritems(self.qtable_name_positions):\n            xprint(\"Positions for qtable name %s are %s\" % (qtable_name,positions))\n            for pos in positions:\n                if table_name_mapping is not None:\n                    x = self.qtable_name_effective_table_names[qtable_name]\n                    effective_sql[pos] = table_name_mapping[x]\n                else:\n                    effective_sql[pos] = self.qtable_name_effective_table_names[qtable_name]\n\n        return \" \".join(effective_sql)\n\n    def get_qtable_name_effective_table_names(self):\n        return self.qtable_name_effective_table_names\n\n    def execute_and_fetch(self, db):\n        x = self.get_effective_sql()\n        xprint(\"Final query: %s\" % x)\n        db_results_obj = db.execute_and_fetch(x)\n        return db_results_obj\n\n    def materialize_using(self,loaded_table_structures_dict):\n        xprint(\"Materializing sql object: %s\" % str(self.qtable_names))\n        xprint(\"loaded table structures dict %s\" % loaded_table_structures_dict)\n        for qtable_name in self.qtable_names:\n            table_structure = loaded_table_structures_dict[qtable_name]\n\n            table_name_in_disk_db = table_structure.get_table_name_for_querying()\n\n            effective_table_name = '%s.%s' % (table_structure.db_id, table_name_in_disk_db)\n\n            # for a single file - no need to create a union, just use the table name\n            self.set_effective_table_name(qtable_name, effective_table_name)\n            xprint(\"Materialized filename %s to effective table name %s\" % (qtable_name,effective_table_name))\n\n\nclass TableColumnInferer(object):\n\n    def __init__(self, input_params):\n        self.inferred = False\n        self.mode = input_params.parsing_mode\n        self.rows = []\n        self.skip_header = input_params.skip_header\n        self.header_row = None\n        self.header_row_filename = None\n        self.expected_column_count = input_params.expected_column_count\n        self.input_delimiter = input_params.delimiter\n        self.disable_column_type_detection = input_params.disable_column_type_detection\n\n    def _generate_content_signature(self):\n        return OrderedDict({\n            \"inferred\": self.inferred,\n            \"mode\": self.mode,\n            \"rows\": \"\\n\".join([\",\".join(x) for x in self.rows]),\n            \"skip_header\": self.skip_header,\n            \"header_row\": self.header_row,\n            \"expected_column_count\": self.expected_column_count,\n            \"input_delimiter\": self.input_delimiter,\n            \"disable_column_type_detection\": self.disable_column_type_detection\n        })\n\n    def analyze(self, filename, col_vals):\n        if self.inferred:\n            assert False, \"Already inferred columns\"\n\n        if self.skip_header and self.header_row is None:\n            self.header_row = col_vals\n            self.header_row_filename = filename\n        else:\n            self.rows.append(col_vals)\n\n        if len(self.rows) < 100:\n            return False\n\n        self.do_analysis()\n        return True\n\n    def force_analysis(self):\n        # This method is called whenever there is no more data, and an analysis needs\n        # to be performed immediately, regardless of the amount of sample data that has\n        # been collected\n        self.do_analysis()\n\n    def determine_type_of_value(self, value):\n        if self.disable_column_type_detection:\n            return str\n\n        if value is not None:\n            value = value.strip()\n        if value == '' or value is None:\n            return None\n\n        try:\n            i = int(value)\n            if type(i) == long:\n                return long\n            else:\n                return int\n        except:\n            pass\n\n        try:\n            f = float(value)\n            return float\n        except:\n            pass\n\n        return str\n\n    def determine_type_of_value_list(self, value_list):\n        type_list = [self.determine_type_of_value(v) for v in value_list]\n        all_types = set(type_list)\n        if len(set(type_list)) == 1:\n            # all the sample lines are of the same type\n            return type_list[0]\n        else:\n            # check for the number of types without nulls,\n            type_list_without_nulls = list(filter(\n                lambda x: x is not None, type_list))\n            # If all the sample lines are of the same type,\n            if len(set(type_list_without_nulls)) == 1:\n                # return it\n                return type_list_without_nulls[0]\n            else:\n                # If there are only two types, one float an one int, then choose a float type\n                if len(set(type_list_without_nulls)) == 2 and float in type_list_without_nulls and int in type_list_without_nulls:\n                    return float\n                return str\n\n    def do_analysis(self):\n        if self.mode == 'strict':\n            self._do_strict_analysis()\n        elif self.mode in ['relaxed']:\n            self._do_relaxed_analysis()\n        else:\n            raise Exception('Unknown parsing mode %s' % self.mode)\n\n        if self.column_count == 1 and self.expected_column_count != 1 and self.expected_column_count is not None:\n            print(f\"Warning: column count is one (expected column count is {self.expected_column_count} - did you provide the correct delimiter?\", file=sys.stderr)\n\n        self.infer_column_types()\n        self.infer_column_names()\n        self.inferred = True\n\n    def validate_column_names(self, value_list):\n        column_name_errors = []\n        for v in value_list:\n            if v is None:\n                # we allow column names to be None, in relaxed mode it'll be filled with default names.\n                # RLRL\n                continue\n            if ',' in v:\n                column_name_errors.append(\n                    (v, \"Column name cannot contain commas\"))\n                continue\n            if self.input_delimiter in v:\n                column_name_errors.append(\n                    (v, \"Column name cannot contain the input delimiter. Please make sure you've set the correct delimiter\"))\n                continue\n            if '\\n' in v:\n                column_name_errors.append(\n                    (v, \"Column name cannot contain newline\"))\n                continue\n            if v != v.strip():\n                column_name_errors.append(\n                    (v, \"Column name contains leading/trailing spaces\"))\n                continue\n            try:\n                v.encode(\"utf-8\", \"strict\").decode(\"utf-8\")\n            except:\n                column_name_errors.append(\n                    (v, \"Column name must be UTF-8 Compatible\"))\n                continue\n            # We're checking for column duplication for each field in order to be able to still provide it along with other errors\n            if len(list(filter(lambda x: x == v,value_list))) > 1:\n                entry = (v, \"Column name is duplicated\")\n                # Don't duplicate the error report itself\n                if entry not in column_name_errors:\n                    column_name_errors.append(entry)\n                continue\n            nul_index = v.find(\"\\x00\")\n            if nul_index >= 0:\n                column_name_errors.append(\n                    (v, \"Column name cannot contain NUL\"))\n                continue\n            t = self.determine_type_of_value(v)\n            if t != str:\n                column_name_errors.append((v, \"Column name must be a string\"))\n        return column_name_errors\n\n    def infer_column_names(self):\n        if self.header_row is not None:\n            column_name_errors = self.validate_column_names(self.header_row)\n            if len(column_name_errors) > 0:\n                raise BadHeaderException(\"Header must contain only strings and not numbers or empty strings: '%s'\\n%s\" % (\n                    \",\".join(self.header_row), \"\\n\".join([\"'%s': %s\" % (x, y) for x, y in column_name_errors])))\n\n            # use header row in order to name columns\n            if len(self.header_row) < self.column_count:\n                if self.mode == 'strict':\n                    raise ColumnCountMismatchException(\"Strict mode. Header row contains less columns than expected column count(%s vs %s)\" % (\n                        len(self.header_row), self.column_count))\n                elif self.mode in ['relaxed']:\n                    # in relaxed mode, add columns to fill the missing ones\n                    self.header_row = self.header_row + \\\n                        ['c%s' % (x + len(self.header_row) + 1)\n                         for x in range(self.column_count - len(self.header_row))]\n            elif len(self.header_row) > self.column_count:\n                if self.mode == 'strict':\n                    raise ColumnCountMismatchException(\"Strict mode. Header row contains more columns than expected column count (%s vs %s)\" % (\n                        len(self.header_row), self.column_count))\n                elif self.mode in ['relaxed']:\n                    # In relaxed mode, just cut the extra column names\n                    self.header_row = self.header_row[:self.column_count]\n            self.column_names = self.header_row\n        else:\n            # Column names are cX starting from 1\n            self.column_names = ['c%s' % (i + 1)\n                                 for i in range(self.column_count)]\n\n    def _do_relaxed_analysis(self):\n        column_count_list = [len(col_vals) for col_vals in self.rows]\n\n        if len(self.rows) == 0:\n            if self.header_row is None:\n                self.column_count = 0\n            else:\n                self.column_count = len(self.header_row)\n        else:\n            if self.expected_column_count is not None:\n                self.column_count = self.expected_column_count\n            else:\n                # If not specified, we'll take the largest row in the sample rows\n                self.column_count = max(column_count_list)\n\n    def get_column_count_summary(self, column_count_list):\n        counts = {}\n        for column_count in column_count_list:\n            counts[column_count] = counts.get(column_count, 0) + 1\n        return six.u(\", \").join([six.u(\"{} rows with {} columns\".format(v, k)) for k, v in six.iteritems(counts)])\n\n    def _do_strict_analysis(self):\n        column_count_list = [len(col_vals) for col_vals in self.rows]\n\n        if len(set(column_count_list)) != 1:\n            raise ColumnCountMismatchException('Strict mode. Column Count is expected to identical. Multiple column counts exist at the first part of the file. Try to check your delimiter, or change to relaxed mode. Details: %s' % (\n                self.get_column_count_summary(column_count_list)))\n\n        self.column_count = len(self.rows[0])\n\n        if self.expected_column_count is not None and self.column_count != self.expected_column_count:\n            raise ColumnCountMismatchException('Strict mode. Column count is expected to be %s but is %s' % (\n                self.expected_column_count, self.column_count))\n\n        self.infer_column_types()\n\n    def infer_column_types(self):\n        assert self.column_count > -1\n        self.column_types = []\n        self.column_types2 = []\n        for column_number in range(self.column_count):\n            column_value_list = [\n                row[column_number] if column_number < len(row) else None for row in self.rows]\n            column_type = self.determine_type_of_value_list(column_value_list)\n            self.column_types.append(column_type)\n\n            column_value_list2 = [row[column_number] if column_number < len(\n                row) else None for row in self.rows[1:]]\n            column_type2 = self.determine_type_of_value_list(\n                column_value_list2)\n            self.column_types2.append(column_type2)\n\n        comparison = map(\n            lambda x: x[0] == x[1], zip(self.column_types, self.column_types2))\n        if False in comparison and not self.skip_header:\n            number_of_column_types = len(set(self.column_types))\n            if number_of_column_types == 1 and list(set(self.column_types))[0] == str:\n                print('Warning - There seems to be header line in the file, but -H has not been specified. All fields will be detected as text fields, and the header line will appear as part of the data', file=sys.stderr)\n\n    def get_column_dict(self):\n        return OrderedDict(zip(self.column_names, self.column_types))\n\n    def get_column_count(self):\n        return self.column_count\n\n    def get_column_names(self):\n        return self.column_names\n\n    def get_column_types(self):\n        return self.column_types\n\n\ndef py3_encoded_csv_reader(encoding, f, dialect,row_data_only=False,**kwargs):\n    try:\n        xprint(\"f is %s\" % str(f))\n        xprint(\"dialect is %s\" % dialect)\n        csv_reader = csv.reader(f, dialect, **kwargs)\n\n        if row_data_only:\n            for row in csv_reader:\n                yield row\n        else:\n            for row in csv_reader:\n                yield (f.filename(),f.isfirstline(),row)\n\n    except UnicodeDecodeError as e1:\n        raise CouldNotParseInputException(e1)\n    except ValueError as e:\n        # TODO Add test for this\n        if str(e) is not None and str(e).startswith('could not convert string to'):\n            raise CouldNotConvertStringToNumericValueException(str(e))\n        else:\n            raise CouldNotParseInputException(str(e))\n    except Exception as e:\n        if str(e).startswith(\"field larger than field limit\"):\n            raise ColumnMaxLengthLimitExceededException(str(e))\n        elif 'universal-newline' in str(e):\n            raise UniversalNewlinesExistException()\n        else:\n            raise\n\nencoded_csv_reader = py3_encoded_csv_reader\n\ndef normalized_filename(filename):\n    return filename\n\nclass TableCreatorState(object):\n    INITIALIZED = 'INITIALIZED'\n    ANALYZED = 'ANALYZED'\n    FULLY_READ = 'FULLY_READ'\n\nclass MaterializedStateType(object):\n    UNKNOWN = 'unknown'\n    DELIMITED_FILE = 'delimited-file'\n    QSQL_FILE = 'qsql-file'\n    SQLITE_FILE = 'sqlite-file'\n    DATA_STREAM = 'data-stream'\n\nclass TableSourceType(object):\n    DELIMITED_FILE = 'file'\n    DELIMITED_FILE_WITH_UNUSED_QSQL = 'file-with-unused-qsql'\n    QSQL_FILE = 'qsql-file'\n    QSQL_FILE_WITH_ORIGINAL = 'qsql-file-with-original'\n    SQLITE_FILE = 'sqlite-file'\n    DATA_STREAM = 'data-stream'\n\ndef skip_BOM(f):\n    try:\n        BOM = f.buffer.read(3)\n\n        if BOM != six.b('\\xef\\xbb\\xbf'):\n            # TODO Add test for this (propagates to try:except)\n            raise Exception('Value of BOM is not as expected - Value is \"%s\"' % str(BOM))\n    except Exception as e:\n        # TODO Add a test for this\n        raise Exception('Tried to skip BOM for \"utf-8-sig\" encoding and failed. Error message is ' + str(e))\n\ndef detect_qtable_name_source_info(qtable_name,data_streams,read_caching_enabled):\n    data_stream = data_streams.get_for_filename(qtable_name)\n    xprint(\"Found data stream %s\" % data_stream)\n\n    if data_stream is not None:\n        return MaterializedStateType.DATA_STREAM, TableSourceType.DATA_STREAM,(data_stream,)\n\n    if ':::' in qtable_name:\n        qsql_filename, table_name = qtable_name.split(\":::\", 1)\n        if not os.path.exists(qsql_filename):\n            raise FileNotFoundException(\"Could not find file %s\" % qsql_filename)\n\n        if is_qsql_file(qsql_filename):\n            return MaterializedStateType.QSQL_FILE, TableSourceType.QSQL_FILE, (qsql_filename, table_name,)\n        if is_sqlite_file(qsql_filename):\n            return MaterializedStateType.SQLITE_FILE, TableSourceType.SQLITE_FILE, (qsql_filename, table_name,)\n        raise UnknownFileTypeException(\"Cannot detect the type of table %s\" % qtable_name)\n    else:\n        if is_qsql_file(qtable_name):\n            return MaterializedStateType.QSQL_FILE, TableSourceType.QSQL_FILE, (qtable_name, None)\n        if is_sqlite_file(qtable_name):\n            return MaterializedStateType.SQLITE_FILE, TableSourceType.SQLITE_FILE, (qtable_name, None)\n        matching_qsql_file_candidate = qtable_name + '.qsql'\n\n        table_source_type = TableSourceType.DELIMITED_FILE\n        if is_qsql_file(matching_qsql_file_candidate):\n            if read_caching_enabled:\n                xprint(\"Found matching qsql file for original file %s (matching file %s) and read caching is enabled. Using it\" % (qtable_name,matching_qsql_file_candidate))\n                return MaterializedStateType.QSQL_FILE, TableSourceType.QSQL_FILE_WITH_ORIGINAL, (matching_qsql_file_candidate, None)\n            else:\n                xprint(\"Found matching qsql file for original file %s (matching file %s), but read caching is disabled. Not using it\" % (qtable_name,matching_qsql_file_candidate))\n                table_source_type = TableSourceType.DELIMITED_FILE_WITH_UNUSED_QSQL\n\n\n        return MaterializedStateType.DELIMITED_FILE,table_source_type ,(qtable_name, None)\n\n\ndef is_sqlite_file(filename):\n    if not os.path.exists(filename):\n        return False\n\n    f = open(filename,'rb')\n    magic = f.read(16)\n    f.close()\n    return magic == six.b(\"SQLite format 3\\x00\")\n\ndef sqlite_table_exists(cursor,table_name):\n    results = cursor.execute(\"select count(*) from sqlite_master where type='table' and tbl_name == '%s'\" % table_name).fetchall()\n    return results[0][0] == 1\n\ndef is_qsql_file(filename):\n    if not is_sqlite_file(filename):\n        return False\n\n    db = Sqlite3DB('check_qsql_db',filename,filename,create_qcatalog=False)\n    qcatalog_exists = db.qcatalog_table_exists()\n    db.done()\n    return qcatalog_exists\n\ndef normalize_filename_to_table_name(filename):\n    xprint(\"Normalizing filename %s\" % filename)\n    if filename[0].isdigit():\n        xprint(\"Filename starts with a digit, adding prefix\")\n        filename = 't_%s' % filename\n    if filename.lower().endswith(\".qsql\"):\n        filename = filename[:-5]\n    elif filename.lower().endswith('.sqlite'):\n        filename = filename[:-7]\n    elif filename.lower().endswith('.sqlite3'):\n        filename = filename[:-8]\n    return filename.replace(\"-\",\"_dash_\").replace(\".\",\"_dot_\").replace('?','_qm_').replace(\"/\",\"_slash_\").replace(\"\\\\\",\"_backslash_\").replace(\":\",\"_colon_\").replace(\" \",\"_space_\").replace(\"+\",\"_plus_\")\n\ndef validate_content_signature(original_filename, source_signature,other_filename, content_signature,scope=None,dump=False):\n    if dump:\n        xprint(\"Comparing: source value: %s target value: %s\" % (source_signature,content_signature))\n\n    s = \"%s vs %s:\" % (original_filename,other_filename)\n    if scope is None:\n        scope = []\n    for k in source_signature:\n        if type(source_signature[k]) == OrderedDict:\n            validate_content_signature(original_filename, source_signature[k],other_filename, content_signature[k],scope + [k])\n        else:\n            if k not in content_signature:\n                raise ContentSignatureDataDiffersException(\"%s Content Signatures differ. %s is missing from content signature\" % (s,k))\n            if source_signature[k] != content_signature[k]:\n                if k == 'rows':\n                    raise ContentSignatureDataDiffersException(\"%s Content Signatures differ at %s.%s (actual analysis data differs)\" % (s,\".\".join(scope),k))\n                else:\n                    raise ContentSignatureDiffersException(original_filename, other_filename, original_filename,\".\".join(scope + [k]),source_signature[k],content_signature[k])\n\nclass DelimitedFileReader(object):\n    def __init__(self,atomic_fns, input_params, dialect, f = None,external_f_name = None):\n        if f is not None:\n            assert len(atomic_fns) == 0\n\n        self.atomic_fns = atomic_fns\n        self.input_params = input_params\n        self.dialect = dialect\n\n        self.f = f\n        self.lines_read = 0\n        self.file_number = -1\n\n        self.skipped_bom = False\n\n        self.is_open = f is not None\n\n        self.external_f = f is not None\n        self.external_f_name = external_f_name\n\n    def get_lines_read(self):\n        return self.lines_read\n\n    def get_size_hash(self):\n        if self.atomic_fns is None or len(self.atomic_fns) == 0:\n            return \"data-stream-size\"\n        else:\n            return \",\".join(map(str,[os.stat(atomic_fn).st_size for atomic_fn in self.atomic_fns]))\n\n    def get_last_modification_time_hash(self):\n        if self.atomic_fns is None or len(self.atomic_fns) == 0:\n            return \"data stream-lmt\"\n        else:\n            x = \",\".join(map(lambda x: ':%s:' % x,[os.stat(x).st_mtime_ns for x in self.atomic_fns]))\n            res = hashlib.sha1(six.b(x)).hexdigest() + '///' + x\n            xprint(\"Hash of last modification time is %s\" % res)\n            return res\n\n    def open_file(self):\n        if self.external_f:\n            xprint(\"External f has been provided. No need to open the file\")\n            return\n\n        # TODO Support universal newlines for gzipped and stdin data as well\n\n        xprint(\"XX Opening file %s\" % \",\".join(self.atomic_fns))\n        import fileinput\n\n        def q_openhook(filename, mode):\n            if self.input_params.gzipped_input or filename.endswith('.gz'):\n                import gzip\n                f = gzip.open(filename,mode='rt',encoding=self.input_params.input_encoding)\n            else:\n                if six.PY3:\n                    if self.input_params.with_universal_newlines:\n                        f = io.open(filename, 'rU', newline=None, encoding=self.input_params.input_encoding)\n                    else:\n                        f = io.open(filename, 'r', newline=None, encoding=self.input_params.input_encoding)\n                else:\n                    if self.input_params.with_universal_newlines:\n                        file_opening_mode = 'rbU'\n                    else:\n                        file_opening_mode = 'rb'\n                    f = open(filename, file_opening_mode)\n\n            if self.input_params.input_encoding == 'utf-8-sig' and not self.skipped_bom:\n                skip_BOM(f)\n\n            return f\n\n        f = fileinput.input(self.atomic_fns,mode='rb',openhook=q_openhook)\n\n        self.f = f\n        self.is_open = True\n        xprint(\"Actually opened file %s\" % self.f)\n        return f\n\n    def close_file(self):\n        if not self.is_open:\n            # TODO Convert to assertion\n            raise Exception(\"Bug - file should already be open: %s\" % \",\".join(self.atomic_fns))\n\n        self.f.close()\n        xprint(\"XX Closed file %s\" % \",\".join(self.atomic_fns))\n\n    def generate_rows(self):\n        csv_reader = encoded_csv_reader(self.input_params.input_encoding, self.f, dialect=self.dialect,row_data_only=self.external_f)\n        try:\n            # TODO Some order with regard to separating data-streams for actual files\n            if self.external_f:\n                for col_vals in csv_reader:\n                    self.lines_read += 1\n                    yield self.external_f_name,0, self.lines_read == 0, col_vals\n            else:\n                for file_name,is_first_line,col_vals in csv_reader:\n                    if is_first_line:\n                        self.file_number = self.file_number + 1\n                    self.lines_read += 1\n                    yield file_name,self.file_number,is_first_line,col_vals\n        except ColumnMaxLengthLimitExceededException as e:\n            msg = \"Column length is larger than the maximum. Offending file is '%s' - Line is %s, counting from 1 (encoding %s). The line number is the raw line number of the file, ignoring whether there's a header or not\" % (\",\".join(self.atomic_fns),self.lines_read + 1,self.input_params.input_encoding)\n            raise ColumnMaxLengthLimitExceededException(msg)\n        except UniversalNewlinesExistException as e2:\n            # No need to translate the exception, but we want it to be explicitly defined here for clarity\n            raise UniversalNewlinesExistException()\n\nclass MaterializedState(object):\n    def __init__(self, table_source_type,qtable_name, engine_id):\n        xprint(\"Creating new MS: %s %s\" % (id(self), qtable_name))\n\n        self.table_source_type = table_source_type\n\n        self.qtable_name = qtable_name\n        self.engine_id = engine_id\n\n        self.db_to_use = None\n        self.db_id = None\n\n        self.source_type = None\n        self.source = None\n\n        self.mfs_structure = None\n\n        self.start_time = None\n        self.end_time = None\n        self.duration = None\n\n        self.effective_table_name = None\n\n\n    def get_materialized_state_type(self):\n        return MaterializedStateType.UNKNOWN\n\n    def get_planned_table_name(self):\n        assert False, 'not implemented'\n\n    def autodetect_table_name(self):\n        xprint(\"Autodetecting table name. db_to_use=%s\" % self.db_to_use)\n        existing_table_names = self.db_to_use.retrieve_all_table_names()\n        xprint(\"Existing table names: %s\" % existing_table_names)\n\n        possible_indices = range(1,1000)\n\n        for index in possible_indices:\n            if index == 1:\n                suffix = ''\n            else:\n                suffix = '_%s' % index\n\n            table_name_attempt = '%s%s' % (self.get_planned_table_name(),suffix)\n            xprint(\"Table name attempt: index=%s name=%s\" % (index,table_name_attempt))\n\n            if table_name_attempt not in existing_table_names:\n                xprint(\"Found free table name %s for source type %s source %s\" % (table_name_attempt,self.source_type,self.source))\n                return table_name_attempt\n\n        raise Exception('Cannot find free table name for source type %s source %s' % (self.source_type,self.source))\n\n    def initialize(self):\n        self.start_time = time.time()\n\n    def finalize(self):\n        self.end_time = time.time()\n        self.duration = self.end_time - self.start_time\n\n    def choose_db_to_use(self,forced_db_to_use=None,stop_after_analysis=False):\n        assert False, 'not implemented'\n\n    def make_data_available(self,stop_after_analysis):\n        assert False, 'not implemented'\n\nclass MaterializedDelimitedFileState(MaterializedState):\n    def __init__(self, table_source_type,qtable_name, input_params, dialect_id,engine_id,target_table_name=None):\n        super().__init__(table_source_type,qtable_name,engine_id)\n\n        self.input_params = input_params\n        self.dialect_id = dialect_id\n        self.target_table_name = target_table_name\n\n        self.content_signature = None\n\n        self.atomic_fns = None\n\n        self.can_store_as_cached = None\n\n    def get_materialized_state_type(self):\n        return MaterializedStateType.DELIMITED_FILE\n\n    def initialize(self):\n        super(MaterializedDelimitedFileState, self).initialize()\n\n        self.atomic_fns = self.materialize_file_list(self.qtable_name)\n        self.delimited_file_reader = DelimitedFileReader(self.atomic_fns,self.input_params,self.dialect_id)\n\n        self.source_type = self.table_source_type\n        self.source = \",\".join(self.atomic_fns)\n\n        return\n\n    def materialize_file_list(self,qtable_name):\n        materialized_file_list = []\n\n        unfound_files = []\n        # First check if the file exists without globbing. This will ensure that we don't support non-existent files\n        if os.path.exists(qtable_name):\n            # If it exists, then just use it\n            found_files = [qtable_name]\n        else:\n            # If not, then try with globs (and sort for predictability)\n            found_files = list(sorted(glob.glob(qtable_name)))\n            # If no files\n            if len(found_files) == 0:\n                unfound_files += [qtable_name]\n        materialized_file_list += found_files\n\n        # If there are no files to go over,\n        if len(unfound_files) == 1:\n            raise FileNotFoundException(\n                \"No files matching '%s' have been found\" % unfound_files[0])\n        elif len(unfound_files) > 1:\n            # TODO Add test for this\n            raise FileNotFoundException(\n                \"The following files have not been found for table %s: %s\" % (qtable_name,\",\".join(unfound_files)))\n\n        # deduplicate with matching qsql files\n        filtered_file_list = list(filter(lambda x: not x.endswith('.qsql'),materialized_file_list))\n        xprint(\"Filtered qsql files from glob search. Original file count: %s new file count: %s\" % (len(materialized_file_list),len(filtered_file_list)))\n\n        l = len(filtered_file_list)\n        # If this proves to be a problem for users in terms of usability, then we'll just materialize the files\n        # into the adhoc db, as with the db attach limit of sqlite\n        if l > 500:\n            msg = \"Maximum source files for table must be 500. Table is name is %s Number of actual files is %s\" % (qtable_name,l)\n            raise MaximumSourceFilesExceededException(msg)\n\n        absolute_path_list = [os.path.abspath(x) for x in filtered_file_list]\n        return absolute_path_list\n\n    def choose_db_to_use(self,forced_db_to_use=None,stop_after_analysis=False):\n        if forced_db_to_use is not None:\n            self.db_id = forced_db_to_use.db_id\n            self.db_to_use = forced_db_to_use\n            self.can_store_as_cached = False\n            assert self.target_table_name is None\n            self.target_table_name = self.autodetect_table_name()\n            return\n\n        self.can_store_as_cached = True\n\n        self.db_id = '%s' % self._generate_db_name(self.atomic_fns[0])\n        xprint(\"Database id is %s\" % self.db_id)\n        self.db_to_use = Sqlite3DB(self.db_id, 'file:%s?mode=memory&cache=shared' % self.db_id, 'memory<%s>' % self.db_id,create_qcatalog=True)\n\n        if self.target_table_name is None:\n            self.target_table_name = self.autodetect_table_name()\n\n\n    def __analyze_delimited_file(self,database_info):\n        xprint(\"Analyzing delimited file\")\n        if self.target_table_name is not None:\n            target_sqlite_table_name = self.target_table_name\n        else:\n            assert False\n\n        xprint(\"Target sqlite table name is %s\" % target_sqlite_table_name)\n        # Create the matching database table and populate it\n        table_creator = TableCreator(self.qtable_name, self.delimited_file_reader,self.input_params, sqlite_db=database_info.sqlite_db,\n                                     target_sqlite_table_name=target_sqlite_table_name)\n        table_creator.perform_analyze(self.dialect_id)\n        xprint(\"after perform_analyze\")\n        self.content_signature = table_creator._generate_content_signature()\n\n        now = datetime.datetime.utcnow().isoformat()\n\n        database_info.sqlite_db.add_to_qcatalog_table(target_sqlite_table_name,\n                                          self.content_signature,\n                                          now,\n                                          self.source_type,\n                                          self.source)\n        return table_creator\n\n    def _generate_disk_db_filename(self, filenames_str):\n        fn = '%s.qsql' % (os.path.abspath(filenames_str).replace(\"+\",\"__\"))\n        return fn\n\n\n    def _get_should_read_from_cache(self, disk_db_filename):\n        disk_db_file_exists = os.path.exists(disk_db_filename)\n\n        should_read_from_cache = self.input_params.read_caching and disk_db_file_exists\n\n        return should_read_from_cache\n\n    def calculate_should_read_from_cache(self):\n        # TODO cache filename is chosen according to first filename only, which makes multi-file (glob) caching difficult\n        #  cache writing is blocked for now in these cases. Will be added in the future (see save_cache_to_disk_if_needed)\n        disk_db_filename = self._generate_disk_db_filename(self.atomic_fns[0])\n        should_read_from_cache = self._get_should_read_from_cache(disk_db_filename)\n        xprint(\"should read from cache %s\" % should_read_from_cache)\n        return disk_db_filename,should_read_from_cache\n\n    def get_planned_table_name(self):\n        return normalize_filename_to_table_name(os.path.basename(self.atomic_fns[0]))\n\n    def make_data_available(self,stop_after_analysis):\n        xprint(\"In make_data_available. db_id %s db_to_use %s\" % (self.db_id,self.db_to_use))\n        assert self.db_id is not None\n\n        disk_db_filename, should_read_from_cache = self.calculate_should_read_from_cache()\n        xprint(\"disk_db_filename=%s should_read_from_cache=%s\" % (disk_db_filename,should_read_from_cache))\n\n        database_info = DatabaseInfo(self.db_id,self.db_to_use, needs_closing=True)\n        xprint(\"db %s (%s) has been added to the database list\" % (self.db_id, self.db_to_use))\n\n        self.delimited_file_reader.open_file()\n\n        table_creator = self.__analyze_delimited_file(database_info)\n\n        self.mfs_structure = MaterializedStateTableStructure(self.qtable_name, self.atomic_fns, self.db_id,\n                                                             table_creator.column_inferer.get_column_names(),\n                                                             table_creator.column_inferer.get_column_types(),\n                                                             None,\n                                                             self.target_table_name,\n                                                             self.source_type,\n                                                             self.source,\n                                                             self.get_planned_table_name())\n\n        content_signature = table_creator.content_signature\n        content_signature_key = self.db_to_use.calculate_content_signature_key(content_signature)\n        xprint(\"table creator signature key: %s\" % content_signature_key)\n\n        relevant_table = self.db_to_use.get_from_qcatalog(content_signature)['temp_table_name']\n\n        if not stop_after_analysis:\n            table_creator.perform_read_fully(self.dialect_id)\n\n            self.save_cache_to_disk_if_needed(disk_db_filename, table_creator)\n\n\n        self.delimited_file_reader.close_file()\n\n        return database_info, relevant_table\n\n    def save_cache_to_disk_if_needed(self, disk_db_filename, table_creator):\n        if len(self.atomic_fns) > 1:\n            xprint(\"Cannot save cache for multi-files for now, deciding auto-naming for cache is challenging. Will be added in the future.\")\n            return\n\n        effective_write_caching = self.input_params.write_caching\n        if effective_write_caching:\n            if self.can_store_as_cached:\n                assert self.table_source_type != TableSourceType.DELIMITED_FILE_WITH_UNUSED_QSQL\n                xprint(\"Going to write file cache for %s. Disk filename is %s\" % (\",\".join(self.atomic_fns), disk_db_filename))\n                self._store_qsql(table_creator.sqlite_db, disk_db_filename)\n            else:\n                xprint(\"Database has been provided externally. Skipping storing a cached version of the data\")\n\n    def _store_qsql(self, source_sqlite_db, disk_db_filename):\n        xprint(\"Storing data as disk db\")\n        disk_db_conn = sqlite3.connect(disk_db_filename)\n        with disk_db_conn:\n            source_sqlite_db.conn.backup(disk_db_conn)\n        xprint(\"Written db to disk: disk db filename %s\" % (disk_db_filename))\n        disk_db_conn.close()\n\n    def _generate_db_name(self, qtable_name):\n        return 'e_%s_fn_%s' % (self.engine_id,normalize_filename_to_table_name(qtable_name))\n\n\nclass MaterialiedDataStreamState(MaterializedDelimitedFileState):\n    def __init__(self, table_source_type, qtable_name, input_params, dialect_id, engine_id, data_stream, stream_target_db): ## should pass adhoc_db\n        assert data_stream is not None\n\n        super().__init__(table_source_type, qtable_name, input_params, dialect_id, engine_id,target_table_name=None)\n\n        self.data_stream = data_stream\n\n        self.stream_target_db = stream_target_db\n\n        self.target_table_name = None\n\n    def get_planned_table_name(self):\n        return 'data_stream_%s' % (normalize_filename_to_table_name(self.source))\n\n    def get_materialized_state_type(self):\n        return MaterializedStateType.DATA_STREAM\n\n    def initialize(self):\n        self.start_time = time.time()\n        if self.input_params.gzipped_input:\n            raise CannotUnzipDataStreamException()\n\n        self.source_type = self.table_source_type\n        self.source = self.data_stream.stream_id\n\n        self.delimited_file_reader = DelimitedFileReader([], self.input_params, self.dialect_id, f=self.data_stream.stream,external_f_name=self.source)\n\n    def choose_db_to_use(self,forced_db_to_use=None,stop_after_analysis=False):\n        assert forced_db_to_use is None\n\n        self.db_id = self.stream_target_db.db_id\n        self.db_to_use = self.stream_target_db\n\n        self.target_table_name = self.autodetect_table_name()\n\n        return\n\n    def calculate_should_read_from_cache(self):\n        # No disk_db_filename, and no reading from cache when reading a datastream\n        return None, False\n\n    def finalize(self):\n        super(MaterialiedDataStreamState, self).finalize()\n\n    def save_cache_to_disk_if_needed(self, disk_db_filename, table_creator):\n        xprint(\"Saving to cache is disabled for data streams\")\n        return\n\n\nclass MaterializedSqliteState(MaterializedState):\n    def __init__(self,table_source_type,qtable_name,sqlite_filename,table_name, engine_id):\n        super(MaterializedSqliteState, self).__init__(table_source_type,qtable_name,engine_id)\n        self.sqlite_filename = sqlite_filename\n        self.table_name = table_name\n\n        self.table_name_autodetected = None\n\n    def initialize(self):\n        super(MaterializedSqliteState, self).initialize()\n\n        self.table_name_autodetected = False\n        if self.table_name is None:\n            self.table_name = self.autodetect_table_name()\n            self.table_name_autodetected = True\n            return\n\n        self.validate_table_name()\n\n    def get_planned_table_name(self):\n        if self.table_name_autodetected:\n            return normalize_filename_to_table_name(os.path.basename(self.qtable_name))\n        else:\n            return self.table_name\n\n\n    def autodetect_table_name(self):\n        db = Sqlite3DB('temp_db','file:%s?immutable=1' % self.sqlite_filename,self.sqlite_filename,create_qcatalog=False)\n        try:\n            table_names = list(sorted(db.retrieve_all_table_names()))\n            if len(table_names) == 1:\n                return table_names[0]\n            elif len(table_names) == 0:\n                raise NoTablesInSqliteException(self.sqlite_filename)\n            else:\n                raise TooManyTablesInSqliteException(self.sqlite_filename,table_names)\n        finally:\n            db.done()\n\n    def validate_table_name(self):\n        db = Sqlite3DB('temp_db', 'file:%s?immutable=1' % self.sqlite_filename, self.sqlite_filename,\n                       create_qcatalog=False)\n        try:\n            table_names = list(db.retrieve_all_table_names())\n            if self.table_name.lower() not in map(lambda x:x.lower(),table_names):\n                raise NonExistentTableNameInSqlite(self.sqlite_filename, self.table_name, table_names)\n        finally:\n            db.done()\n\n    def finalize(self):\n        super(MaterializedSqliteState, self).finalize()\n\n    def get_materialized_state_type(self):\n        return MaterializedStateType.SQLITE_FILE\n\n    def _generate_qsql_only_db_name__temp(self, filenames_str):\n        return 'e_%s_fn_%s' % (self.engine_id,hashlib.sha1(six.b(filenames_str)).hexdigest())\n\n    def choose_db_to_use(self,forced_db_to_use=None,stop_after_analysis=False):\n        self.source = self.sqlite_filename\n        self.source_type = self.table_source_type\n\n        self.db_id = '%s' % self._generate_qsql_only_db_name__temp(self.qtable_name)\n\n        x = 'file:%s?immutable=1' % self.sqlite_filename\n        self.db_to_use = Sqlite3DB(self.db_id, x, self.sqlite_filename,create_qcatalog=False)\n\n        if forced_db_to_use:\n            xprint(\"Forced sqlite db_to_use %s\" % forced_db_to_use)\n            new_table_name = forced_db_to_use.attach_and_copy_table(self.db_to_use,self.table_name,stop_after_analysis)\n            self.table_name = new_table_name\n            self.db_id = forced_db_to_use.db_id\n            self.db_to_use = forced_db_to_use\n\n        return\n\n    def make_data_available(self,stop_after_analysis):\n        xprint(\"db %s (%s) has been added to the database list\" % (self.db_id, self.db_to_use))\n\n        database_info,relevant_table = DatabaseInfo(self.db_id,self.db_to_use, needs_closing=True), self.table_name\n\n        column_names, column_types, sqlite_column_types = self._extract_information()\n\n        self.mfs_structure = MaterializedStateTableStructure(self.qtable_name, [self.qtable_name], self.db_id,\n                                                             column_names, column_types, sqlite_column_types,\n                                                             self.table_name,\n                                                             self.source_type,self.source,\n                                                             self.get_planned_table_name())\n        return database_info, relevant_table\n\n    def _extract_information(self):\n        table_list = self.db_to_use.retrieve_all_table_names()\n        if len(table_list) == 1:\n            table_name = table_list[0][0]\n            xprint(\"Only one table in sqlite database, choosing it: %s\" % table_name)\n        else:\n            # self.table_name has either beein autodetected, or validated as an existing table up the stack\n            table_name = self.table_name\n            xprint(\"Multiple tables in sqlite file. Using provided table name %s\" % self.table_name)\n\n        table_info = self.db_to_use.get_sqlite_table_info(table_name)\n        xprint('Table info is %s' % table_info)\n        column_names = list(map(lambda x: x[1], table_info))\n        sqlite_column_types = list(map(lambda x: x[2].lower(),table_info))\n        column_types = list(map(lambda x: sqlite_type_to_python_type(x[2]), table_info))\n        xprint(\"Column names and types for table %s: %s\" % (table_name, list(zip(column_names, zip(sqlite_column_types,column_types)))))\n        self.content_signature = OrderedDict()\n\n        return column_names, column_types, sqlite_column_types\n\n\nclass MaterializedQsqlState(MaterializedState):\n    def __init__(self,table_source_type,qtable_name,qsql_filename,table_name, engine_id,input_params,dialect_id):\n        super(MaterializedQsqlState, self).__init__(table_source_type,qtable_name,engine_id)\n        self.qsql_filename = qsql_filename\n        self.table_name = table_name\n\n        # These are for cases where the qsql file is just a cache and the original is still there, used for content\n        # validation\n        self.input_params = input_params\n        self.dialect_id = dialect_id\n\n        self.table_name_autodetected = None\n\n    def initialize(self):\n        super(MaterializedQsqlState, self).initialize()\n\n        self.table_name_autodetected = False\n        if self.table_name is None:\n            self.table_name = self.autodetect_table_name()\n            self.table_name_autodetected = True\n            return\n\n        self.validate_table_name()\n\n    def get_planned_table_name(self):\n        if self.table_name_autodetected:\n            return normalize_filename_to_table_name(os.path.basename(self.qtable_name))\n        else:\n            return self.table_name\n\n\n    def autodetect_table_name(self):\n        db = Sqlite3DB('temp_db','file:%s?immutable=1' % self.qsql_filename,self.qsql_filename,create_qcatalog=False)\n        assert db.qcatalog_table_exists()\n        try:\n            qcatalog_entries = db.get_all_from_qcatalog()\n            if len(qcatalog_entries) == 0:\n                raise NoTableInQsqlExcption(self.qsql_filename)\n            elif len(qcatalog_entries) == 1:\n                return qcatalog_entries[0]['temp_table_name']\n            else:\n                # TODO Add a test for this\n                table_names = list(sorted([x['temp_table_name'] for x in qcatalog_entries]))\n                raise TooManyTablesInQsqlException(self.qsql_filename,table_names)\n        finally:\n            db.done()\n\n    def validate_table_name(self):\n        db = Sqlite3DB('temp_db', 'file:%s?immutable=1' % self.qsql_filename, self.qsql_filename,\n                       create_qcatalog=False)\n        assert db.qcatalog_table_exists()\n        try:\n            entry = db.get_from_qcatalog_using_table_name(self.table_name)\n            if entry is None:\n                qcatalog_entries = db.get_all_from_qcatalog()\n                table_names = list(sorted([x['temp_table_name'] for x in qcatalog_entries]))\n                raise NonExistentTableNameInQsql(self.qsql_filename,self.table_name,table_names)\n        finally:\n            db.done()\n\n    def finalize(self):\n        super(MaterializedQsqlState, self).finalize()\n\n    def get_materialized_state_type(self):\n        return MaterializedStateType.QSQL_FILE\n\n    def _generate_qsql_only_db_name__temp(self, filenames_str):\n        return 'e_%s_fn_%s' % (self.engine_id,hashlib.sha1(six.b(filenames_str)).hexdigest())\n\n    def choose_db_to_use(self,forced_db_to_use=None,stop_after_analysis=False):\n        self.source = self.qsql_filename\n        self.source_type = self.table_source_type\n\n        self.db_id = '%s' % self._generate_qsql_only_db_name__temp(self.qtable_name)\n\n        x = 'file:%s?immutable=1' % self.qsql_filename\n        self.db_to_use = Sqlite3DB(self.db_id, x, self.qsql_filename,create_qcatalog=False)\n\n        if forced_db_to_use:\n            xprint(\"Forced qsql to use forced_db: %s\" % forced_db_to_use)\n\n            # TODO RLRL Move query to Sqlite3DB\n            all_table_names = [(x[0],x[1]) for x in self.db_to_use.execute_and_fetch(\"select content_signature_key,temp_table_name from %s\" % self.db_to_use.QCATALOG_TABLE_NAME).results]\n            csk,t = list(filter(lambda x: x[1] == self.table_name,all_table_names))[0]\n            xprint(\"Copying table %s from db_id %s\" % (t,self.db_id))\n            d = self.db_to_use.get_from_qcatalog_using_table_name(t)\n\n            new_table_name = forced_db_to_use.attach_and_copy_table(self.db_to_use,self.table_name,stop_after_analysis)\n\n            xprint(\"CS\",d['content_signature'])\n            cs = OrderedDict(json.loads(d['content_signature']))\n            forced_db_to_use.add_to_qcatalog_table(new_table_name, cs, d['creation_time'],\n                                    d['source_type'], d['source'])\n\n            self.table_name = new_table_name\n            self.db_id = forced_db_to_use.db_id\n            self.db_to_use = forced_db_to_use\n\n        return\n\n    def make_data_available(self,stop_after_analysis):\n        xprint(\"db %s (%s) has been added to the database list\" % (self.db_id, self.db_to_use))\n\n        database_info,relevant_table = self._read_table_from_cache(stop_after_analysis)\n\n        column_names, column_types, sqlite_column_types = self._extract_information()\n\n        self.mfs_structure = MaterializedStateTableStructure(self.qtable_name, [self.qtable_name], self.db_id,\n                                                             column_names, column_types, sqlite_column_types,\n                                                             self.table_name,\n                                                             self.source_type,self.source,\n                                                             self.get_planned_table_name())\n        return database_info, relevant_table\n\n    def _extract_information(self):\n        assert self.db_to_use.qcatalog_table_exists()\n        table_info = self.db_to_use.get_sqlite_table_info(self.table_name)\n        xprint('table_name=%s Table info is %s' % (self.table_name,table_info))\n\n        x = self.db_to_use.get_from_qcatalog_using_table_name(self.table_name)\n\n        column_names = list(map(lambda x: x[1], table_info))\n        sqlite_column_types = list(map(lambda x: x[2].lower(),table_info))\n        column_types = list(map(lambda x: sqlite_type_to_python_type(x[2]), table_info))\n        self.content_signature = OrderedDict(\n            **json.loads(x['content_signature']))\n        xprint('Inferred column names and types from qsql: %s' % list(zip(column_names, zip(sqlite_column_types,column_types))))\n\n        return column_names, column_types, sqlite_column_types\n\n    def _backing_original_file_exists(self):\n        return '%s.qsql' % self.qtable_name == self.qsql_filename\n\n    def _read_table_from_cache(self, stop_after_analysis):\n        if self._backing_original_file_exists():\n            xprint(\"Found a matching source file for qsql file with qtable name %s. Checking content signature by creating a temp MFDS + analysis\" % self.qtable_name)\n            mdfs = MaterializedDelimitedFileState(TableSourceType.DELIMITED_FILE,self.qtable_name,self.input_params,self.dialect_id,self.engine_id,target_table_name=None)\n            mdfs.initialize()\n            mdfs.choose_db_to_use(forced_db_to_use=None,stop_after_analysis=stop_after_analysis)\n            _,_ = mdfs.make_data_available(stop_after_analysis=True)\n\n            original_file_content_signature = mdfs.content_signature\n            original_file_content_signature_key = self.db_to_use.calculate_content_signature_key(original_file_content_signature)\n\n            qcatalog_entry = self.db_to_use.get_from_qcatalog_using_table_name(self.table_name)\n\n            if qcatalog_entry is None:\n                raise Exception('missing content signature!')\n\n            xprint(\"Actual Signature Key: %s Expected Signature Key: %s\" % (qcatalog_entry['content_signature_key'],original_file_content_signature_key))\n            actual_content_signature = json.loads(qcatalog_entry['content_signature'])\n\n            xprint(\"Validating content signatures: original %s vs qsql %s\" % (original_file_content_signature,actual_content_signature))\n            validate_content_signature(self.qtable_name, original_file_content_signature, self.qsql_filename, actual_content_signature,dump=True)\n            mdfs.finalize()\n        return DatabaseInfo(self.db_id,self.db_to_use, needs_closing=True), self.table_name\n\n\nclass MaterializedStateTableStructure(object):\n    def __init__(self,qtable_name, atomic_fns, db_id, column_names, python_column_types, sqlite_column_types, table_name_for_querying,source_type,source,planned_table_name):\n        self.qtable_name = qtable_name\n        self.atomic_fns = atomic_fns\n        self.db_id = db_id\n        self.column_names = column_names\n        self.python_column_types = python_column_types\n        self.table_name_for_querying = table_name_for_querying\n        self.source_type = source_type\n        self.source = source\n        self.planned_table_name = planned_table_name\n\n        if sqlite_column_types is not None:\n            self.sqlite_column_types = sqlite_column_types\n        else:\n            self.sqlite_column_types = [Sqlite3DB.PYTHON_TO_SQLITE_TYPE_NAMES[t].lower() for t in python_column_types]\n\n    def get_table_name_for_querying(self):\n        return self.table_name_for_querying\n\n    def __str__(self):\n        return \"MaterializedStateTableStructure<%s>\" % self.__dict__\n    __repr__ = __str__\n\nclass TableCreator(object):\n    def __str__(self):\n        return \"TableCreator<%s>\" % str(self)\n    __repr__ = __str__\n\n    def __init__(self, qtable_name, delimited_file_reader,input_params,sqlite_db=None,target_sqlite_table_name=None):\n\n        self.qtable_name = qtable_name\n        self.delimited_file_reader = delimited_file_reader\n\n        self.db_id = sqlite_db.db_id\n\n        self.sqlite_db = sqlite_db\n        self.target_sqlite_table_name = target_sqlite_table_name\n\n        self.skip_header = input_params.skip_header\n        self.gzipped = input_params.gzipped_input\n        self.table_created = False\n\n        self.encoding = input_params.input_encoding\n        self.mode = input_params.parsing_mode\n        self.expected_column_count = input_params.expected_column_count\n        self.input_delimiter = input_params.delimiter\n        self.with_universal_newlines = input_params.with_universal_newlines\n\n        self.column_inferer = TableColumnInferer(input_params)\n\n        self.pre_creation_rows = []\n        self.buffered_inserts = []\n        self.effective_column_names = None\n\n        # Column type indices for columns that contain numeric types. Lazily initialized\n        # so column inferer can do its work before this information is needed\n        self.numeric_column_indices = None\n\n        self.state = TableCreatorState.INITIALIZED\n\n        self.content_signature = None\n\n    def _generate_content_signature(self):\n        if self.state != TableCreatorState.ANALYZED:\n            # TODO Change to assertion\n            raise Exception('Bug - Wrong state %s. Table needs to be analyzed before a content signature can be calculated' % self.state)\n\n        size = self.delimited_file_reader.get_size_hash()\n        last_modification_time = self.delimited_file_reader.get_last_modification_time_hash()\n\n        m = OrderedDict({\n            \"_signature_version\": \"v1\",\n            \"skip_header\": self.skip_header,\n            \"gzipped\": self.gzipped,\n            \"with_universal_newlines\": self.with_universal_newlines,\n            \"encoding\": self.encoding,\n            \"mode\": self.mode,\n            \"expected_column_count\": self.expected_column_count,\n            \"input_delimiter\": self.input_delimiter,\n            \"inferer\": self.column_inferer._generate_content_signature(),\n            \"original_file_size\": size,\n            \"last_modification_time\": last_modification_time\n        })\n\n        return m\n\n    def validate_extra_header_if_needed(self, file_number, filename,col_vals):\n        xprint(\"HHX validate\",file_number,filename,col_vals)\n        if not self.skip_header:\n            xprint(\"No need to validate header\")\n            return False\n\n        if file_number == 0:\n            xprint(\"First file, no need to validate extra header\")\n            return False\n\n        header_already_exists = self.column_inferer.header_row is not None\n\n        if header_already_exists:\n            xprint(\"Validating extra header\")\n            if tuple(self.column_inferer.header_row) != tuple(col_vals):\n                raise BadHeaderException(\"Extra header '{}' in file '{}' mismatches original header '{}' from file '{}'. Table name is '{}'\".format(\n                    \",\".join(col_vals),filename,\n                    \",\".join(self.column_inferer.header_row),\n                    self.column_inferer.header_row_filename,\n                    self.qtable_name))\n            xprint(\"header already exists: %s\" % self.column_inferer.header_row)\n        else:\n            xprint(\"Header doesn't already exist\")\n\n        return header_already_exists\n\n    def _populate(self,dialect,stop_after_analysis=False):\n        total_data_lines_read = 0\n        try:\n            try:\n                for file_name,file_number,is_first_line,col_vals in self.delimited_file_reader.generate_rows():\n                    if is_first_line:\n                        if self.validate_extra_header_if_needed(file_number,file_name,col_vals):\n                            continue\n                    self._insert_row(file_name, col_vals)\n                    if stop_after_analysis:\n                        if self.column_inferer.inferred:\n                            xprint(\"Stopping after analysis\")\n                            return\n                if self.delimited_file_reader.get_lines_read() == 0 and self.skip_header:\n                    raise MissingHeaderException(\"Header line is expected but missing in file %s\" % \",\".join(self.delimited_file_reader.atomic_fns))\n\n                total_data_lines_read += self.delimited_file_reader.lines_read - (1 if self.skip_header else 0)\n                xprint(\"Total Data lines read %s\" % total_data_lines_read)\n            except StrictModeColumnCountMismatchException as e:\n                raise ColumnCountMismatchException(\n                    'Strict mode - Expected %s columns instead of %s columns in file %s row %s. Either use relaxed modes or check your delimiter' % (\n                    e.expected_col_count, e.actual_col_count, normalized_filename(e.atomic_fn), e.lines_read))\n            except FluffyModeColumnCountMismatchException as e:\n                raise ColumnCountMismatchException(\n                    'Deprecated fluffy mode - Too many columns in file %s row %s (%s fields instead of %s fields). Consider moving to either relaxed or strict mode' % (\n                    normalized_filename(e.atomic_fn), e.lines_read, e.actual_col_count, e.expected_col_count))\n        finally:\n            self._flush_inserts()\n\n        if not self.table_created:\n            self.column_inferer.force_analysis()\n            self._do_create_table(self.qtable_name)\n\n        self.sqlite_db.conn.commit()\n\n    def perform_analyze(self, dialect):\n        xprint(\"Analyzing... %s\" % dialect)\n        if self.state == TableCreatorState.INITIALIZED:\n            self._populate(dialect,stop_after_analysis=True)\n            self.state = TableCreatorState.ANALYZED\n\n            self.content_signature = self._generate_content_signature()\n            content_signature_key = self.sqlite_db.calculate_content_signature_key(self.content_signature)\n            xprint(\"Setting content signature after analysis: %s\" % content_signature_key)\n        else:\n            # TODO Convert to assertion\n            raise Exception('Bug - Wrong state %s' % self.state)\n\n    def perform_read_fully(self, dialect):\n        if self.state == TableCreatorState.ANALYZED:\n            self._populate(dialect,stop_after_analysis=False)\n            self.state = TableCreatorState.FULLY_READ\n        else:\n            # TODO Convert to assertion\n            raise Exception('Bug - Wrong state %s' % self.state)\n\n    def _flush_pre_creation_rows(self, filename):\n        for i, col_vals in enumerate(self.pre_creation_rows):\n            if self.skip_header and i == 0:\n                # skip header line\n                continue\n            self._insert_row(filename, col_vals)\n        self._flush_inserts()\n        self.pre_creation_rows = []\n\n    def _insert_row(self, filename, col_vals):\n        # If table has not been created yet\n        if not self.table_created:\n            # Try to create it along with another \"example\" line of data\n            self.try_to_create_table(filename, col_vals)\n\n        # If the table is still not created, then we don't have enough data, just\n        # store the data and return\n        if not self.table_created:\n            self.pre_creation_rows.append(col_vals)\n            return\n\n\n        # The table already exists, so we can just add a new row\n        self._insert_row_i(col_vals)\n\n    def initialize_numeric_column_indices_if_needed(self):\n        # Lazy initialization of numeric column indices\n        if self.numeric_column_indices is None:\n            column_types = self.column_inferer.get_column_types()\n            self.numeric_column_indices = [idx for idx, column_type in enumerate(\n                column_types) if self.sqlite_db.is_numeric_type(column_type)]\n\n    def nullify_values_if_needed(self, col_vals):\n        new_vals = col_vals[:]\n        col_count = len(col_vals)\n        for i in self.numeric_column_indices:\n            if i >= col_count:\n                continue\n            v = col_vals[i]\n            if v == '':\n                new_vals[i] = None\n        return new_vals\n\n    def normalize_col_vals(self, col_vals):\n        # Make sure that numeric column indices are initializd\n        self.initialize_numeric_column_indices_if_needed()\n\n        col_vals = self.nullify_values_if_needed(col_vals)\n\n        expected_col_count = self.column_inferer.get_column_count()\n        actual_col_count = len(col_vals)\n        if self.mode == 'strict':\n            if actual_col_count != expected_col_count:\n                raise StrictModeColumnCountMismatchException(\",\".join(self.delimited_file_reader.atomic_fns), expected_col_count,actual_col_count,self.delimited_file_reader.get_lines_read())\n            return col_vals\n\n        # in all non strict mode, we add dummy data to missing columns\n\n        if actual_col_count < expected_col_count:\n            col_vals = col_vals + \\\n                [None for x in range(expected_col_count - actual_col_count)]\n\n        # in relaxed mode, we merge all extra columns to the last column value\n        if self.mode == 'relaxed':\n            if actual_col_count > expected_col_count:\n                xxx = col_vals[:expected_col_count - 1] + \\\n                    [self.input_delimiter.join([v if v  is not None else '' for v in\n                        col_vals[expected_col_count - 1:]])]\n                return xxx\n            else:\n                return col_vals\n\n        assert False, \"Unidentified parsing mode %s\" % self.mode\n\n    def _insert_row_i(self, col_vals):\n        col_vals = self.normalize_col_vals(col_vals)\n\n        if self.effective_column_names is None:\n            self.effective_column_names = self.column_inferer.column_names[:len(col_vals)]\n\n        if len(self.effective_column_names) > 0:\n            self.buffered_inserts.append(col_vals)\n        else:\n            self.buffered_inserts.append([\"\"])\n\n        if len(self.buffered_inserts) < 5000:\n            return\n        self._flush_inserts()\n\n    def _flush_inserts(self):\n        # If the table is still not created, then we don't have enough data\n        if not self.table_created:\n            return\n\n        if len(self.buffered_inserts) > 0:\n            insert_row_stmt = self.sqlite_db.generate_insert_row(\n                self.target_sqlite_table_name, self.effective_column_names)\n\n            self.sqlite_db.update_many(insert_row_stmt, self.buffered_inserts)\n        self.buffered_inserts = []\n\n    def try_to_create_table(self, filename, col_vals):\n        if self.table_created:\n            # TODO Convert to assertion\n            raise Exception('Table is already created')\n\n        # Add that line to the column inferer\n        result = self.column_inferer.analyze(filename, col_vals)\n        # If inferer succeeded,\n        if result:\n            self._do_create_table(filename)\n        else:\n            pass  # We don't have enough information for creating the table yet\n\n    def _do_create_table(self,filename):\n        # Get the column definition dict from the inferer\n        column_dict = self.column_inferer.get_column_dict()\n\n        # Guard against empty tables (instead of preventing the creation, just create with a dummy column)\n        if len(column_dict) == 0:\n            column_dict = { 'dummy_column_for_empty_tables' : str }\n            ordered_column_names = [ 'dummy_column_for_empty_tables' ]\n        else:\n            ordered_column_names = self.column_inferer.get_column_names()\n\n        # Create the CREATE TABLE statement\n        create_table_stmt = self.sqlite_db.generate_create_table(\n            self.target_sqlite_table_name, ordered_column_names, column_dict)\n        # And create the table itself\n        self.sqlite_db.execute_and_fetch(create_table_stmt)\n        # Mark the table as created\n        self.table_created = True\n        self._flush_pre_creation_rows(filename)\n\n\ndef determine_max_col_lengths(m,output_field_quoting_func,output_delimiter):\n    if len(m) == 0:\n        return []\n    max_lengths = [0 for x in range(0, len(m[0]))]\n    for row_index in range(0, len(m)):\n        for col_index in range(0, len(m[0])):\n            # TODO Optimize this\n            new_len = len(\"{}\".format(output_field_quoting_func(output_delimiter,m[row_index][col_index])))\n            if new_len > max_lengths[col_index]:\n                max_lengths[col_index] = new_len\n    return max_lengths\n\ndef print_credentials():\n    print(\"q version %s\" % q_version, file=sys.stderr)\n    print(\"Python: %s\" % \" // \".join([str(x).strip() for x in sys.version.split(\"\\n\")]), file=sys.stderr)\n    print(\"Copyright (C) 2012-2021 Harel Ben-Attia (harelba@gmail.com, @harelba on twitter)\", file=sys.stderr)\n    print(\"https://harelba.github.io/q/\", file=sys.stderr)\n    print(file=sys.stderr)\n\nclass QWarning(object):\n    def __init__(self,exception,msg):\n        self.exception = exception\n        self.msg = msg\n\nclass QError(object):\n    def __init__(self,exception,msg,errorcode):\n        self.exception = exception\n        self.msg = msg\n        self.errorcode = errorcode\n        self.traceback = traceback.format_exc()\n\n    def __str__(self):\n        return \"QError<errorcode=%s,msg=%s,exception=%s,traceback=%s>\" % (self.errorcode,self.msg,self.exception,str(self.traceback))\n    __repr__ = __str__\n\nclass QMetadata(object):\n    def __init__(self,table_structures={},new_table_structures={},output_column_name_list=None):\n        self.table_structures = table_structures\n        self.new_table_structures = new_table_structures\n        self.output_column_name_list = output_column_name_list\n\n    def __str__(self):\n        return \"QMetadata<%s\" % (self.__dict__)\n    __repr__ = __str__\n\nclass QOutput(object):\n    def __init__(self,data=None,metadata=None,warnings=[],error=None):\n        self.data = data\n        self.metadata = metadata\n\n        self.warnings = warnings\n        self.error = error\n        if error is None:\n            self.status = 'ok'\n        else:\n            self.status = 'error'\n\n    def __str__(self):\n        s = []\n        s.append('status=%s' % self.status)\n        if self.error is not None:\n            s.append(\"error=%s\" % self.error.msg)\n        if len(self.warnings) > 0:\n            s.append(\"warning_count=%s\" % len(self.warnings))\n        if self.data is not None:\n            s.append(\"row_count=%s\" % len(self.data))\n        else:\n            s.append(\"row_count=None\")\n        if self.metadata is not None:\n            s.append(\"metadata=<%s>\" % self.metadata)\n        else:\n            s.append(\"metadata=None\")\n        return \"QOutput<%s>\" % \",\".join(s)\n    __repr__ = __str__\n\nclass QInputParams(object):\n    def __init__(self,skip_header=False,\n            delimiter=' ',input_encoding='UTF-8',gzipped_input=False,with_universal_newlines=False,parsing_mode='relaxed',\n            expected_column_count=None,keep_leading_whitespace_in_values=False,\n            disable_double_double_quoting=False,disable_escaped_double_quoting=False,\n            disable_column_type_detection=False,\n            input_quoting_mode='minimal',stdin_file=None,stdin_filename='-',\n            max_column_length_limit=131072,\n            read_caching=False,\n            write_caching=False,\n            max_attached_sqlite_databases = 10):\n        self.skip_header = skip_header\n        self.delimiter = delimiter\n        self.input_encoding = input_encoding\n        self.gzipped_input = gzipped_input\n        self.with_universal_newlines = with_universal_newlines\n        self.parsing_mode = parsing_mode\n        self.expected_column_count = expected_column_count\n        self.keep_leading_whitespace_in_values = keep_leading_whitespace_in_values\n        self.disable_double_double_quoting = disable_double_double_quoting\n        self.disable_escaped_double_quoting = disable_escaped_double_quoting\n        self.input_quoting_mode = input_quoting_mode\n        self.disable_column_type_detection = disable_column_type_detection\n        self.max_column_length_limit = max_column_length_limit\n        self.read_caching = read_caching\n        self.write_caching = write_caching\n        self.max_attached_sqlite_databases = max_attached_sqlite_databases\n\n    def merged_with(self,input_params):\n        params = QInputParams(**self.__dict__)\n        if input_params is not None:\n            params.__dict__.update(**input_params.__dict__)\n        return params\n\n    def __str__(self):\n        return \"QInputParams<%s>\" % str(self.__dict__)\n\n    def __repr__(self):\n        return \"QInputParams(...)\"\n\nclass DataStream(object):\n    # TODO Can stream-id be removed?\n    def __init__(self,stream_id,filename,stream):\n        self.stream_id = stream_id\n        self.filename = filename\n        self.stream = stream\n\n    def __str__(self):\n        return \"QDataStream<stream_id=%s,filename=%s,stream=%s>\" % (self.stream_id,self.filename,self.stream)\n    __repr__ = __str__\n\n\nclass DataStreams(object):\n    def __init__(self, data_streams_dict):\n        assert type(data_streams_dict) == dict\n        self.validate(data_streams_dict)\n        self.data_streams_dict = data_streams_dict\n\n    def validate(self,d):\n        for k in d:\n            v = d[k]\n            if type(k) != str or type(v) != DataStream:\n                raise Exception('Bug - Invalid dict: %s' % str(d))\n\n    def get_for_filename(self, filename):\n        xprint(\"Data streams dict is %s. Trying to find %s\" % (self.data_streams_dict,filename))\n        x = self.data_streams_dict.get(filename)\n        return x\n\n    def is_data_stream(self,filename):\n        return filename in self.data_streams_dict\n\nclass DatabaseInfo(object):\n    def __init__(self,db_id,sqlite_db,needs_closing):\n        self.db_id = db_id\n        self.sqlite_db = sqlite_db\n        self.needs_closing = needs_closing\n\n    def __str__(self):\n        return \"DatabaseInfo<sqlite_db=%s,needs_closing=%s>\" % (self.sqlite_db,self.needs_closing)\n    __repr__ = __str__\n\nclass QTextAsData(object):\n    def __init__(self,default_input_params=QInputParams(),data_streams_dict=None):\n        self.engine_id = str(uuid.uuid4()).replace(\"-\",\"_\")\n\n        self.default_input_params = default_input_params\n        xprint(\"Default input params: %s\" % self.default_input_params)\n\n        self.loaded_table_structures_dict = OrderedDict()\n        self.databases = OrderedDict()\n\n        if data_streams_dict is not None:\n            self.data_streams = DataStreams(data_streams_dict)\n        else:\n            self.data_streams = DataStreams({})\n\n        # Create DB object\n        self.query_level_db_id = 'query_e_%s' % self.engine_id\n        self.query_level_db = Sqlite3DB(self.query_level_db_id,\n                                        'file:%s?mode=memory&cache=shared' % self.query_level_db_id,'<query-level-db>',create_qcatalog=True)\n        self.adhoc_db_id = 'adhoc_e_%s' % self.engine_id\n        self.adhoc_db_name = 'file:%s?mode=memory&cache=shared' % self.adhoc_db_id\n        self.adhoc_db = Sqlite3DB(self.adhoc_db_id,self.adhoc_db_name,'<adhoc-db>',create_qcatalog=True)\n        self.query_level_db.conn.execute(\"attach '%s' as %s\" % (self.adhoc_db_name,self.adhoc_db_id))\n\n        self.add_db_to_database_list(DatabaseInfo(self.query_level_db_id,self.query_level_db,needs_closing=True))\n        self.add_db_to_database_list(DatabaseInfo(self.adhoc_db_id,self.adhoc_db,needs_closing=True))\n\n    def done(self):\n        xprint(\"Inside done: Database list is %s\" % self.databases)\n        for db_id in reversed(self.databases.keys()):\n            database_info = self.databases[db_id]\n            if database_info.needs_closing:\n                xprint(\"Gonna close database %s - %s\" % (db_id,self.databases[db_id]))\n                self.databases[db_id].sqlite_db.done()\n                xprint(\"Database %s has been closed\" % db_id)\n            else:\n                xprint(\"No need to close database %s\" % db_id)\n        xprint(\"Closed all databases\")\n\n    input_quoting_modes = {   'minimal' : csv.QUOTE_MINIMAL,\n                        'all' : csv.QUOTE_ALL,\n                        # nonnumeric is not supported for input quoting modes, since we determine the data types\n                        # ourselves instead of letting the csv module try to identify the types\n                        'none' : csv.QUOTE_NONE }\n\n    def determine_proper_dialect(self,input_params):\n\n        input_quoting_mode_csv_numeral = QTextAsData.input_quoting_modes[input_params.input_quoting_mode]\n\n        if input_params.keep_leading_whitespace_in_values:\n            skip_initial_space = False\n        else:\n            skip_initial_space = True\n\n        dialect = {'skipinitialspace': skip_initial_space,\n                    'delimiter': input_params.delimiter, 'quotechar': '\"' }\n        dialect['quoting'] = input_quoting_mode_csv_numeral\n        dialect['doublequote'] = input_params.disable_double_double_quoting\n\n        if input_params.disable_escaped_double_quoting:\n            dialect['escapechar'] = '\\\\'\n\n        return dialect\n\n    def get_dialect_id(self,filename):\n        return 'q_dialect_%s' % filename\n\n    def _open_files_and_get_mfss(self,qtable_name,input_params,dialect):\n        materialized_file_dict = OrderedDict()\n\n        materialized_state_type,table_source_type,source_info = detect_qtable_name_source_info(qtable_name,self.data_streams,read_caching_enabled=input_params.read_caching)\n        xprint(\"Detected source type %s source info %s\" % (materialized_state_type,source_info))\n\n        if materialized_state_type == MaterializedStateType.DATA_STREAM:\n            (data_stream,) = source_info\n            ms = MaterialiedDataStreamState(table_source_type,qtable_name,input_params,dialect,self.engine_id,data_stream,stream_target_db=self.adhoc_db)\n            effective_qtable_name = data_stream.stream_id\n        elif materialized_state_type == MaterializedStateType.QSQL_FILE:\n            (qsql_filename,table_name) = source_info\n            ms = MaterializedQsqlState(table_source_type,qtable_name, qsql_filename=qsql_filename, table_name=table_name,\n                                       engine_id=self.engine_id, input_params=input_params, dialect_id=dialect)\n            effective_qtable_name = '%s:::%s' % (qsql_filename, table_name)\n        elif materialized_state_type == MaterializedStateType.SQLITE_FILE:\n            (sqlite_filename,table_name) = source_info\n            ms = MaterializedSqliteState(table_source_type,qtable_name, sqlite_filename=sqlite_filename, table_name=table_name,\n                                       engine_id=self.engine_id)\n            effective_qtable_name = '%s:::%s' % (sqlite_filename, table_name)\n        elif materialized_state_type == MaterializedStateType.DELIMITED_FILE:\n            (source_qtable_name,_) = source_info\n            ms = MaterializedDelimitedFileState(table_source_type,source_qtable_name, input_params, dialect, self.engine_id)\n            effective_qtable_name = source_qtable_name\n        else:\n            assert False, \"Unknown file type for qtable %s should have exited with an exception\" % (qtable_name)\n\n        assert effective_qtable_name not in materialized_file_dict\n        materialized_file_dict[effective_qtable_name] = ms\n\n        xprint(\"MS dict: %s\" % str(materialized_file_dict))\n\n        return list([item for item in materialized_file_dict.values()])\n\n    def _load_mfs(self,mfs,input_params,dialect_id,stop_after_analysis):\n        xprint(\"Loading MFS:\", mfs)\n\n        materialized_state_type = mfs.get_materialized_state_type()\n        xprint(\"Detected materialized state type for %s: %s\" % (mfs.qtable_name,materialized_state_type))\n\n        mfs.initialize()\n\n        if not materialized_state_type in [MaterializedStateType.DATA_STREAM]:\n            if stop_after_analysis or self.should_copy_instead_of_attach(input_params):\n                xprint(\"Should copy instead of attaching. Forcing db to use to adhoc db\")\n                forced_db_to_use = self.adhoc_db\n            else:\n                forced_db_to_use = None\n        else:\n            forced_db_to_use = None\n\n        mfs.choose_db_to_use(forced_db_to_use,stop_after_analysis)\n        xprint(\"Chosen db to use: source %s source_type %s db_id %s db_to_use %s\" % (mfs.source,mfs.source_type,mfs.db_id,mfs.db_to_use))\n\n        database_info,relevant_table = mfs.make_data_available(stop_after_analysis)\n\n        if not self.is_adhoc_db(mfs.db_to_use) and not self.should_copy_instead_of_attach(input_params):\n            if not self.already_attached_to_query_level_db(mfs.db_to_use):\n                self.attach_to_db(mfs.db_to_use, self.query_level_db)\n                self.add_db_to_database_list(database_info)\n            else:\n                xprint(\"DB %s is already attached to query level db. No need to attach it again.\")\n\n        mfs.finalize()\n\n        xprint(\"MFS Loaded\")\n\n        return mfs.source,mfs.source_type\n\n    def add_db_to_database_list(self,database_info):\n        db_id = database_info.db_id\n        assert db_id is not None\n        assert database_info.sqlite_db is not None\n        if db_id in self.databases:\n            # TODO Convert to assertion\n            if id(database_info.sqlite_db) != id(self.databases[db_id].sqlite_db):\n                raise Exception('Bug - database already in database list: db_id %s: old %s new %s' % (db_id,self.databases[db_id],database_info))\n            else:\n                return\n        self.databases[db_id] = database_info\n\n    def is_adhoc_db(self,db_to_use):\n        return db_to_use.db_id == self.adhoc_db_id\n\n    def should_copy_instead_of_attach(self,input_params):\n        attached_database_count = len(self.query_level_db.get_sqlite_database_list())\n        x = attached_database_count >= input_params.max_attached_sqlite_databases\n        xprint(\"should_copy_instead_of_attach: attached_database_count=%s should_copy=%s\" % (attached_database_count,x))\n        return x\n\n    def _load_data(self,qtable_name,input_params=QInputParams(),stop_after_analysis=False):\n        xprint(\"Attempting to load data for materialized file names %s\" % qtable_name)\n\n        q_dialect = self.determine_proper_dialect(input_params)\n        xprint(\"Dialect is %s\" % q_dialect)\n        dialect_id = self.get_dialect_id(qtable_name)\n        csv.register_dialect(dialect_id, **q_dialect)\n\n        xprint(\"qtable metadata for loading is %s\" % qtable_name)\n        mfss = self._open_files_and_get_mfss(qtable_name,\n                                             input_params,\n                                             dialect_id)\n        assert len(mfss) == 1, \"one MS now encapsulated an entire table\"\n        mfs = mfss[0]\n\n        xprint(\"MFS to load: %s\" % mfs)\n\n        if qtable_name in self.loaded_table_structures_dict.keys():\n            xprint(\"Atomic filename %s found. no need to load\" % qtable_name)\n            return None\n\n        xprint(\"qtable %s not found - loading\" % qtable_name)\n\n\n        self._load_mfs(mfs, input_params, dialect_id, stop_after_analysis)\n        xprint(\"Loaded: source-type %s source %s mfs_structure %s\" % (mfs.source_type, mfs.source, mfs.mfs_structure))\n\n        assert qtable_name not in self.loaded_table_structures_dict, \"loaded_table_structures_dict has been changed to have a non-list value\"\n        self.loaded_table_structures_dict[qtable_name] = mfs.mfs_structure\n\n        return mfs.mfs_structure\n\n    def already_attached_to_query_level_db(self,db_to_attach):\n        attached_dbs = list(map(lambda x:x[1],self.query_level_db.get_sqlite_database_list()))\n        return db_to_attach.db_id in attached_dbs\n\n    def attach_to_db(self, target_db, source_db):\n        q = \"attach '%s' as %s\" % (target_db.sqlite_db_url,target_db.db_id)\n        xprint(\"Attach query: %s\" % q)\n        try:\n            c = source_db.execute_and_fetch(q)\n        except SqliteOperationalErrorException as e:\n            if 'too many attached databases' in str(e):\n                raise TooManyAttachedDatabasesException('There are too many attached databases. Use a proper --max-attached-sqlite-databases parameter which is below the maximum. Original error: %s' % str(e))\n        except Exception as e1:\n            raise\n\n    def detach_from_db(self, target_db, source_db):\n        q = \"detach %s\" % (target_db.db_id)\n        xprint(\"Detach query: %s\" % q)\n        try:\n            c = source_db.execute_and_fetch(q)\n        except Exception as e1:\n            raise\n\n    def load_data(self,filename,input_params=QInputParams(),stop_after_analysis=False):\n        return self._load_data(filename,input_params,stop_after_analysis=stop_after_analysis)\n\n    def _ensure_data_is_loaded_for_sql(self,sql_object,input_params,data_streams=None,stop_after_analysis=False):\n        xprint(\"Ensuring Data load\")\n        new_table_structures = OrderedDict()\n\n        # For each \"table name\"\n        for qtable_name in sql_object.qtable_names:\n            tss = self._load_data(qtable_name,input_params,stop_after_analysis=stop_after_analysis)\n            if tss is not None:\n                xprint(\"New Table Structures:\",new_table_structures)\n                assert qtable_name not in new_table_structures, \"new_table_structures was changed not to contain a list as a value\"\n                new_table_structures[qtable_name] = tss\n\n        return new_table_structures\n\n    def materialize_query_level_db(self,save_db_to_disk_filename,sql_object):\n        # TODO More robust creation - Create the file in a separate folder and move it to the target location only after success\n\n        materialized_db = Sqlite3DB(\"materialized\",\"file:%s\" % save_db_to_disk_filename,save_db_to_disk_filename,create_qcatalog=False)\n        table_name_mapping = OrderedDict()\n\n        # For each table in the query\n        effective_table_names = sql_object.get_qtable_name_effective_table_names()\n\n        for i, qtable_name in enumerate(effective_table_names):\n            # table name, in the format db_id.table_name\n            effective_table_name_for_qtable_name = effective_table_names[qtable_name]\n\n            source_db_id, actual_table_name_in_db = effective_table_name_for_qtable_name.split(\".\", 1)\n            # The DatabaseInfo instance for this db\n            source_database = self.databases[source_db_id]\n            if source_db_id != self.query_level_db_id:\n                self.attach_to_db(source_database.sqlite_db,materialized_db)\n\n            ts = self.loaded_table_structures_dict[qtable_name]\n            proposed_new_table_name = ts.planned_table_name\n            xprint(\"Proposed table name is %s\" % proposed_new_table_name)\n\n            new_table_name = materialized_db.find_new_table_name(proposed_new_table_name)\n\n            xprint(\"Materializing\",source_db_id,actual_table_name_in_db,\"as\",new_table_name)\n            # Copy the table into the materialized database\n            xx = materialized_db.execute_and_fetch('CREATE TABLE %s AS SELECT * FROM %s' % (new_table_name,effective_table_name_for_qtable_name))\n\n            table_name_mapping[effective_table_name_for_qtable_name] = new_table_name\n\n            # TODO RLRL Preparation for writing materialized database as a qsql file\n            # if source_database.sqlite_db.qcatalog_table_exists():\n            #     qcatalog_entry = source_database.sqlite_db.get_from_qcatalog_using_table_name(actual_table_name_in_db)\n            #     # TODO RLRL Encapsulate dictionary transform inside qcatalog access methods\n            #     materialized_db.add_to_qcatalog_table(new_table_name,OrderedDict(json.loads(qcatalog_entry['content_signature'])),\n            #                                           qcatalog_entry['creation_time'],\n            #                                           qcatalog_entry['source_type'],\n            #                                           qcatalog_entry['source_type'])\n            #     xprint(\"PQX Added to qcatalog\",source_db_id,actual_table_name_in_db,'as',new_table_name)\n            # else:\n            #     xprint(\"PQX Skipped adding to qcatalog\",source_db_id,actual_table_name_in_db)\n\n            if source_db_id != self.query_level_db:\n                self.detach_from_db(source_database.sqlite_db,materialized_db)\n\n        return table_name_mapping\n\n    def validate_query(self,sql_object,table_structures):\n\n        for qtable_name in sql_object.qtable_names:\n            relevant_table_structures = [table_structures[qtable_name]]\n\n            column_names = None\n            column_types = None\n            for ts in relevant_table_structures:\n                names = ts.column_names\n                types = ts.python_column_types\n                xprint(\"Comparing column names: %s with %s\" % (column_names,names))\n                if column_names is None:\n                    column_names = names\n                else:\n                    if column_names != names:\n                        raise BadHeaderException(\"Column names differ for table %s: %s vs %s\" % (\n                            qtable_name, \",\".join(column_names), \",\".join(names)))\n\n                xprint(\"Comparing column types: %s with %s\" % (column_types,types))\n                if column_types is None:\n                    column_types = types\n                else:\n                    if column_types != types:\n                        raise BadHeaderException(\"Column types differ for table %s: %s vs %s\" % (\n                        qtable_name, \",\".join(column_types), \",\".join(types)))\n\n                xprint(\"All column names match for qtable name %s: column names: %s column types: %s\" % (ts.qtable_name,column_names,column_types))\n\n        xprint(\"Query validated\")\n\n    def _execute(self,query_str,input_params=None,data_streams=None,stop_after_analysis=False,save_db_to_disk_filename=None):\n        warnings = []\n        error = None\n        table_structures = []\n\n        db_results_obj = None\n\n        effective_input_params = self.default_input_params.merged_with(input_params)\n\n        if type(query_str) != unicode:\n            try:\n                # Heuristic attempt to auto convert the query to unicode before failing\n                query_str = query_str.decode('utf-8')\n            except:\n                error = QError(EncodedQueryException(''),\"Query should be in unicode. Please make sure to provide a unicode literal string or decode it using proper the character encoding.\",91)\n                return QOutput(error = error)\n\n\n        try:\n            # Create SQL statement\n            sql_object = Sql('%s' % query_str, self.data_streams)\n\n            load_start_time = time.time()\n            iprint(\"Going to ensure data is loaded. Currently loaded tables: %s\" % str(self.loaded_table_structures_dict))\n            new_table_structures = self._ensure_data_is_loaded_for_sql(sql_object,effective_input_params,data_streams,stop_after_analysis=stop_after_analysis)\n            iprint(\"Ensured data is loaded. loaded tables: %s\" % self.loaded_table_structures_dict)\n\n            self.validate_query(sql_object,self.loaded_table_structures_dict)\n\n            iprint(\"Query validated\")\n\n            sql_object.materialize_using(self.loaded_table_structures_dict)\n\n            iprint(\"Materialized sql object\")\n\n            if save_db_to_disk_filename is not None:\n                xprint(\"Saving query data to disk\")\n                dump_start_time = time.time()\n                table_name_mapping = self.materialize_query_level_db(save_db_to_disk_filename,sql_object)\n                print(\"Data has been saved into %s . Saving has taken %4.3f seconds\" % (save_db_to_disk_filename,time.time()-dump_start_time), file=sys.stderr)\n                effective_sql = sql_object.get_effective_sql(table_name_mapping)\n                print(\"Query to run on the database: %s;\" % effective_sql, file=sys.stderr)\n                command_line = 'echo \"%s\" | sqlite3 %s' % (effective_sql,save_db_to_disk_filename)\n                print(\"You can run the query directly from the command line using the following command: %s\" % command_line, file=sys.stderr)\n\n                # TODO Propagate dump results using a different output class instead of an empty one\n                return QOutput()\n\n            # Ensure that adhoc db is not in the middle of a transaction\n            self.adhoc_db.conn.commit()\n\n            all_databases = self.query_level_db.get_sqlite_database_list()\n            xprint(\"Query level db: databases %s\" % all_databases)\n\n            # Execute the query and fetch the data\n            db_results_obj = sql_object.execute_and_fetch(self.query_level_db)\n            iprint(\"Query executed\")\n\n            if len(db_results_obj.results) == 0:\n                warnings.append(QWarning(None, \"Warning - data is empty\"))\n\n            return QOutput(\n                data = db_results_obj.results,\n                metadata = QMetadata(\n                    table_structures=self.loaded_table_structures_dict,\n                    new_table_structures=new_table_structures,\n                    output_column_name_list=db_results_obj.query_column_names),\n                warnings = warnings,\n                error = error)\n        except InvalidQueryException as e:\n            error = QError(e,str(e),118)\n        except MissingHeaderException as e:\n            error = QError(e,e.msg,117)\n        except FileNotFoundException as e:\n            error = QError(e,e.msg,30)\n        except SqliteOperationalErrorException as e:\n            xprint(\"Sqlite Operational error: %s\" % e)\n            msg = str(e.original_error)\n            error = QError(e,\"query error: %s\" % msg,1)\n            if \"no such column\" in msg and effective_input_params.skip_header:\n                warnings.append(QWarning(e,'Warning - There seems to be a \"no such column\" error, and -H (header line) exists. Please make sure that you are using the column names from the header line and not the default (cXX) column names. Another issue might be that the file contains a BOM. Files that are encoded with UTF8 and contain a BOM can be read by specifying `-e utf-9-sig` in the command line. Support for non-UTF8 encoding will be provided in the future.'))\n        except ColumnCountMismatchException as e:\n            error = QError(e,e.msg,2)\n        except (UnicodeDecodeError, UnicodeError) as e:\n            error = QError(e,\"Cannot decode data. Try to change the encoding by setting it using the -e parameter. Error:%s\" % e,3)\n        except BadHeaderException as e:\n            error = QError(e,\"Bad header row: %s\" % e.msg,35)\n        except CannotUnzipDataStreamException as e:\n            error = QError(e,\"Cannot decompress standard input. Pipe the input through zcat in order to decompress.\",36)\n        except UniversalNewlinesExistException as e:\n            error = QError(e,\"Data contains universal newlines. Run q with -U to use universal newlines. Please note that q still doesn't support universal newlines for .gz files or for stdin. Route the data through a regular file to use -U.\",103)\n        # deprecated, but shouldn't be used:  error = QError(e,\"Standard Input must be provided in order to use it as a table\",61)\n        except CouldNotConvertStringToNumericValueException as e:\n            error = QError(e,\"Could not convert string to a numeric value. Did you use `-w nonnumeric` with unquoted string values? Error: %s\" % e.msg,58)\n        except CouldNotParseInputException as e:\n            error = QError(e,\"Could not parse the input. Please make sure to set the proper -w input-wrapping parameter for your input, and that you use the proper input encoding (-e). Error: %s\" % e.msg,59)\n        except ColumnMaxLengthLimitExceededException as e:\n            error = QError(e,e.msg,31)\n        # deprecated, but shouldn't be used: error = QError(e,e.msg,79)\n        except ContentSignatureDiffersException as e:\n            error = QError(e,\"%s vs %s: Content Signatures for table %s differ at %s (source value '%s' disk signature value '%s')\" %\n                           (e.original_filename,e.other_filename,e.filenames_str,e.key,e.source_value,e.signature_value),80)\n        except ContentSignatureDataDiffersException as e:\n            error = QError(e,e.msg,81)\n        except MaximumSourceFilesExceededException as e:\n            error = QError(e,e.msg,82)\n        except ContentSignatureNotFoundException as e:\n            error = QError(e,e.msg,83)\n        except NonExistentTableNameInQsql as e:\n            msg = \"Table %s could not be found in qsql file %s . Existing table names: %s\" % (e.table_name,e.qsql_filename,\",\".join(e.existing_table_names))\n            error = QError(e,msg,84)\n        except NonExistentTableNameInSqlite as e:\n            msg = \"Table %s could not be found in sqlite file %s . Existing table names: %s\" % (e.table_name,e.qsql_filename,\",\".join(e.existing_table_names))\n            error = QError(e,msg,85)\n        except TooManyTablesInQsqlException as e:\n            msg = \"Could not autodetect table name in qsql file. Existing Tables %s\" % \",\".join(e.existing_table_names)\n            error = QError(e,msg,86)\n        except NoTableInQsqlExcption as e:\n            msg = \"Could not autodetect table name in qsql file. File contains no record of a table\"\n            error = QError(e,msg,97)\n        except TooManyTablesInSqliteException as e:\n            msg = \"Could not autodetect table name in sqlite file %s . Existing tables: %s\" % (e.qsql_filename,\",\".join(e.existing_table_names))\n            error = QError(e,msg,87)\n        except NoTablesInSqliteException as e:\n            msg = \"sqlite file %s has no tables\" % e.sqlite_filename\n            error = QError(e,msg,88)\n        except TooManyAttachedDatabasesException as e:\n            msg = str(e)\n            error = QError(e,msg,89)\n        except UnknownFileTypeException as e:\n            msg = str(e)\n            error = QError(e,msg,95)\n        except KeyboardInterrupt as e:\n            warnings.append(QWarning(e,\"Interrupted\"))\n        except Exception as e:\n            global DEBUG\n            if DEBUG:\n                xprint(traceback.format_exc())\n            error = QError(e,repr(e),199)\n\n        return QOutput(data=None,warnings = warnings,error = error , metadata=QMetadata(table_structures=self.loaded_table_structures_dict,new_table_structures=self.loaded_table_structures_dict,output_column_name_list=[]))\n\n    def execute(self,query_str,input_params=None,save_db_to_disk_filename=None):\n        r = self._execute(query_str,input_params,stop_after_analysis=False,save_db_to_disk_filename=save_db_to_disk_filename)\n        return r\n\n    def unload(self):\n        # TODO This would fail, since table structures are just value objects now. Will be fixed as part of making q a full python module\n        for qtable_name,table_creator in six.iteritems(self.loaded_table_structures_dict):\n            try:\n                table_creator.drop_table()\n            except:\n                # Support no-table select queries\n                pass\n        self.loaded_table_structures_dict = OrderedDict()\n\n    def analyze(self,query_str,input_params=None,data_streams=None):\n        q_output = self._execute(query_str,input_params,data_streams=data_streams,stop_after_analysis=True)\n\n        return q_output\n\ndef escape_double_quotes_if_needed(v):\n    x = v.replace(six.u('\"'), six.u('\"\"'))\n    return x\n\ndef quote_none_func(output_delimiter,v):\n    return v\n\ndef quote_minimal_func(output_delimiter,v):\n    if v is None:\n        return v\n    t = type(v)\n    if (t == str or t == unicode) and ((output_delimiter in v) or ('\\n' in v) or ('\"' in v)):\n        return six.u('\"{}\"').format(escape_double_quotes_if_needed(v))\n    return v\n\ndef quote_nonnumeric_func(output_delimiter,v):\n    if v is None:\n        return v\n    if type(v) == str or type(v) == unicode:\n        return six.u('\"{}\"').format(escape_double_quotes_if_needed(v))\n    return v\n\ndef quote_all_func(output_delimiter,v):\n    if type(v) == str or type(v) == unicode:\n        return six.u('\"{}\"').format(escape_double_quotes_if_needed(v))\n    else:\n        return six.u('\"{}\"').format(v)\n\nclass QOutputParams(object):\n    def __init__(self,\n            delimiter=' ',\n            beautify=False,\n            output_quoting_mode='minimal',\n            formatting=None,\n            output_header=False,\n                 encoding=None):\n        self.delimiter = delimiter\n        self.beautify = beautify\n        self.output_quoting_mode = output_quoting_mode\n        self.formatting = formatting\n        self.output_header = output_header\n        self.encoding = encoding\n\n    def __str__(self):\n        return \"QOutputParams<%s>\" % str(self.__dict__)\n\n    def __repr__(self):\n        return \"QOutputParams(...)\"\n\nclass QOutputPrinter(object):\n    output_quoting_modes = {   'minimal' : quote_minimal_func,\n                        'all' : quote_all_func,\n                        'nonnumeric' : quote_nonnumeric_func,\n                        'none' : quote_none_func }\n\n    def __init__(self,output_params,show_tracebacks=False):\n        self.output_params = output_params\n        self.show_tracebacks = show_tracebacks\n\n        self.output_field_quoting_func = QOutputPrinter.output_quoting_modes[output_params.output_quoting_mode]\n\n    def print_errors_and_warnings(self,f,results):\n        if results.status == 'error':\n            error = results.error\n            print(error.msg, file=f)\n            if self.show_tracebacks:\n                print(error.traceback, file=f)\n\n        for warning in results.warnings:\n            print(\"%s\" % warning.msg, file=f)\n\n    def print_analysis(self,f_out,f_err,results):\n        self.print_errors_and_warnings(f_err,results)\n\n        if results.metadata is None:\n            return\n\n        if results.metadata.table_structures is None:\n            return\n\n        for qtable_name in results.metadata.table_structures:\n            table_structures = results.metadata.table_structures[qtable_name]\n            print(\"Table: %s\" % qtable_name,file=f_out)\n            print(\"  Sources:\",file=f_out)\n            dl = results.metadata.new_table_structures[qtable_name]\n            print(\"    source_type: %s source: %s\" % (dl.source_type,dl.source),file=f_out)\n            print(\"  Fields:\",file=f_out)\n            for n,t in zip(table_structures.column_names,table_structures.sqlite_column_types):\n                print(\"    `%s` - %s\" % (n,t), file=f_out)\n\n    def print_output(self,f_out,f_err,results):\n        try:\n            self._print_output(f_out,f_err,results)\n        except (UnicodeEncodeError, UnicodeError) as e:\n            print(\"Cannot encode data. Error:%s\" % e, file=f_err)\n            sys.exit(3)\n        except IOError as e:\n            if e.errno == 32:\n                # broken pipe, that's ok\n                pass\n            else:\n                # don't miss other problems for now\n                raise\n        except KeyboardInterrupt:\n            pass\n\n    def _print_output(self,f_out,f_err,results):\n        self.print_errors_and_warnings(f_err,results)\n\n        data = results.data\n\n        if data is None:\n            return\n\n        # If the user requested beautifying the output\n        if self.output_params.beautify:\n            if self.output_params.output_header:\n                data_with_possible_headers = data + [tuple(results.metadata.output_column_name_list)]\n            else:\n                data_with_possible_headers = data\n            max_lengths = determine_max_col_lengths(data_with_possible_headers,self.output_field_quoting_func,self.output_params.delimiter)\n\n        if self.output_params.formatting:\n            formatting_dict = dict(\n                [(x.split(\"=\")[0], x.split(\"=\")[1]) for x in self.output_params.formatting.split(\",\")])\n        else:\n            formatting_dict = {}\n\n        try:\n            if self.output_params.output_header and results.metadata.output_column_name_list is not None:\n                data.insert(0,results.metadata.output_column_name_list)\n            for rownum, row in enumerate(data):\n                row_str = []\n                skip_formatting = rownum == 0 and self.output_params.output_header\n                for i, col in enumerate(row):\n                    if str(i + 1) in formatting_dict.keys() and not skip_formatting:\n                        fmt_str = formatting_dict[str(i + 1)]\n                    else:\n                        if self.output_params.beautify:\n                            fmt_str = six.u(\"{{0:<{}}}\").format(max_lengths[i])\n                        else:\n                            fmt_str = six.u(\"{}\")\n\n                    if col is not None:\n                        xx = self.output_field_quoting_func(self.output_params.delimiter,col)\n                        row_str.append(fmt_str.format(xx))\n                    else:\n                        row_str.append(fmt_str.format(\"\"))\n\n\n                xxxx = six.u(self.output_params.delimiter).join(row_str) + six.u(\"\\n\")\n                f_out.write(xxxx)\n        except (UnicodeEncodeError, UnicodeError) as e:\n            print(\"Cannot encode data. Error:%s\" % e, file=sys.stderr)\n            sys.exit(3)\n        except TypeError as e:\n            print(\"Error while formatting output: %s\" % e, file=sys.stderr)\n            sys.exit(4)\n        except IOError as e:\n            if e.errno == 32:\n                # broken pipe, that's ok\n                pass\n            else:\n                # don't miss other problem for now\n                raise\n        except KeyboardInterrupt:\n            pass\n\n        try:\n            # Prevent python bug when order of pipe shutdowns is reversed\n            f_out.flush()\n        except IOError as e:\n            pass\n\ndef get_option_with_default(p, option_type, option, default):\n    try:\n        if not p.has_option('options', option):\n            return default\n        if p.get('options',option) == 'None':\n            return None\n        if option_type == 'boolean':\n            r = p.getboolean('options', option)\n            return r\n        elif option_type == 'int':\n            r = p.getint('options', option)\n            return r\n        elif option_type == 'string':\n            r = p.get('options', option)\n            return r\n        else:\n            raise Exception(\"Unknown option type %s \" % option_type)\n    except ValueError as e:\n        raise IncorrectDefaultValueException(option_type,option,p.get(\"options\",option))\n\nQRC_FILENAME_ENVVAR = 'QRC_FILENAME'\n\ndef dump_default_values_as_qrc(parser,exclusions):\n    m = parser.parse_args([]).__dict__\n    m.pop('leftover')\n    print(\"[options]\",file=sys.stdout)\n    for k in sorted(m.keys()):\n        if k not in exclusions:\n            print(\"%s=%s\" % (k,m[k]),file=sys.stdout)\n\nUSAGE_TEXT = \"\"\"\n\tq <flags> <query>\n\n\tExample Execution for a delimited file:\n\n\t\tq \"select * from myfile.csv\"\n\n\tExample Execution for an sqlite3 database:\n\n\t\tq \"select * from mydatabase.sqlite:::my_table_name\"\n\n            or\n\n\t\tq \"select * from mydatabase.sqlite\"\n\n            if the database file contains only one table\n\n\tAuto-caching of delimited files can be activated through `-C readwrite` (writes new caches if needed)  or `-C read` (only reads existing cache files)\n\n\tSetting the default caching mode (`-C`) can be done by writing a `~/.qrc` file. See docs for more info.\n\t\nq's purpose is to bring SQL expressive power to the Linux command line and to provide easy access to text as actual data.\n\nq allows the following:\n\n* Performing SQL-like statements directly on tabular text data, auto-caching the data in order to accelerate additional querying on the same file\n* Performing SQL statements directly on multi-file sqlite3 databases, without having to merge them or load them into memory\n\nChanging the default values for parameters can be done by creating a `~/.qrc` file. Run q with `--dump-defaults` in order to dump a default `.qrc` file into stdout.\n\nSee https://github.com/harelba/q for more details.\n\n\"\"\"\n\ndef run_standalone():\n    sqlite3.enable_callback_tracebacks(True)\n\n    p, qrc_filename = parse_qrc_file()\n\n    args, options, parser = initialize_command_line_parser(p, qrc_filename)\n\n    dump_defaults_and_stop__if_needed(options, parser)\n\n    dump_version_and_stop__if_needed(options)\n\n    STDOUT, default_input_params, q_output_printer, query_strs = parse_options(args, options)\n\n    data_streams_dict = initialize_default_data_streams()\n\n    q_engine = QTextAsData(default_input_params=default_input_params,data_streams_dict=data_streams_dict)\n\n    execute_queries(STDOUT, options, q_engine, q_output_printer, query_strs)\n\n    q_engine.done()\n\n    sys.exit(0)\n\n\ndef dump_version_and_stop__if_needed(options):\n    if options.version:\n        print_credentials()\n        sys.exit(0)\n\n\ndef dump_defaults_and_stop__if_needed(options, parser):\n    if options.dump_defaults:\n        dump_default_values_as_qrc(parser, ['dump-defaults', 'version'])\n        sys.exit(0)\n\n\ndef execute_queries(STDOUT, options, q_engine, q_output_printer, query_strs):\n    for query_str in query_strs:\n        if options.analyze_only:\n            q_output = q_engine.analyze(query_str)\n            q_output_printer.print_analysis(STDOUT, sys.stderr, q_output)\n        else:\n            q_output = q_engine.execute(query_str, save_db_to_disk_filename=options.save_db_to_disk_filename)\n            q_output_printer.print_output(STDOUT, sys.stderr, q_output)\n\n        if q_output.status == 'error':\n            sys.exit(q_output.error.errorcode)\n\n\ndef initialize_command_line_parser(p, qrc_filename):\n    try:\n        default_verbose = get_option_with_default(p, 'boolean', 'verbose', False)\n        default_save_db_to_disk = get_option_with_default(p, 'string', 'save_db_to_disk_filename', None)\n        default_caching_mode = get_option_with_default(p, 'string', 'caching_mode', 'none')\n\n        default_skip_header = get_option_with_default(p, 'boolean', 'skip_header', False)\n        default_delimiter = get_option_with_default(p, 'string', 'delimiter', None)\n        default_pipe_delimited = get_option_with_default(p, 'boolean', 'pipe_delimited', False)\n        default_tab_delimited = get_option_with_default(p, 'boolean', 'tab_delimited', False)\n        default_encoding = get_option_with_default(p, 'string', 'encoding', 'UTF-8')\n        default_gzipped = get_option_with_default(p, 'boolean', 'gzipped', False)\n        default_analyze_only = get_option_with_default(p, 'boolean', 'analyze_only', False)\n        default_mode = get_option_with_default(p, 'string', 'mode', \"relaxed\")\n        default_column_count = get_option_with_default(p, 'string', 'column_count', None)\n        default_keep_leading_whitespace_in_values = get_option_with_default(p, 'boolean',\n                                                                            'keep_leading_whitespace_in_values', False)\n        default_disable_double_double_quoting = get_option_with_default(p, 'boolean', 'disable_double_double_quoting',\n                                                                        True)\n        default_disable_escaped_double_quoting = get_option_with_default(p, 'boolean', 'disable_escaped_double_quoting',\n                                                                         True)\n        default_disable_column_type_detection = get_option_with_default(p, 'boolean', 'disable_column_type_detection',\n                                                                        False)\n        default_input_quoting_mode = get_option_with_default(p, 'string', 'input_quoting_mode', 'minimal')\n        default_max_column_length_limit = get_option_with_default(p, 'int', 'max_column_length_limit', 131072)\n        default_with_universal_newlines = get_option_with_default(p, 'boolean', 'with_universal_newlines', False)\n\n        default_output_delimiter = get_option_with_default(p, 'string', 'output_delimiter', None)\n        default_pipe_delimited_output = get_option_with_default(p, 'boolean', 'pipe_delimited_output', False)\n        default_tab_delimited_output = get_option_with_default(p, 'boolean', 'tab_delimited_output', False)\n        default_output_header = get_option_with_default(p, 'boolean', 'output_header', False)\n        default_beautify = get_option_with_default(p, 'boolean', 'beautify', False)\n        default_formatting = get_option_with_default(p, 'string', 'formatting', None)\n        default_output_encoding = get_option_with_default(p, 'string', 'output_encoding', 'none')\n        default_output_quoting_mode = get_option_with_default(p, 'string', 'output_quoting_mode', 'minimal')\n        default_list_user_functions = get_option_with_default(p, 'boolean', 'list_user_functions', False)\n        default_overwrite_qsql = get_option_with_default(p, 'boolean', 'overwrite_qsql', False)\n\n        default_query_filename = get_option_with_default(p, 'string', 'query_filename', None)\n        default_query_encoding = get_option_with_default(p, 'string', 'query_encoding', locale.getpreferredencoding())\n        default_max_attached_sqlite_databases = get_option_with_default(p,'int','max_attached_sqlite_databases', 10)\n    except IncorrectDefaultValueException as e:\n        print(\"Incorrect value '%s' for option %s in .qrc file %s (option type is %s)\" % (\n        e.actual_value, e.option, qrc_filename, e.option_type))\n        sys.exit(199)\n    parser = ArgumentParser(prog=\"q\",usage=USAGE_TEXT)\n    parser.add_argument(\"-v\", \"--version\", action=\"store_true\", help=\"Print version\")\n    parser.add_argument(\"-V\", \"--verbose\", default=default_verbose, action=\"store_true\",\n                      help=\"Print debug info in case of problems\")\n    parser.add_argument(\"-S\", \"--save-db-to-disk\", dest=\"save_db_to_disk_filename\", default=default_save_db_to_disk,\n                      help=\"Save database to an sqlite database file\")\n    parser.add_argument(\"-C\", \"--caching-mode\", default=default_caching_mode,\n                      help=\"Choose the autocaching mode (none/read/readwrite). Autocaches files to disk db so further queries will be faster. Caching is done to a side-file with the same name of the table, but with an added extension .qsql\")\n    parser.add_argument(\"--dump-defaults\", action=\"store_true\",\n                      help=\"Dump all default values for parameters and exit. Can be used in order to make sure .qrc file content is being read properly.\")\n    parser.add_argument(\"--max-attached-sqlite-databases\", default=default_max_attached_sqlite_databases,type=int,\n                      help=\"Set the maximum number of concurrently-attached sqlite dbs. This is a compile time definition of sqlite. q's performance will slow down once this limit is reached for a query, since it will perform table copies in order to avoid that limit.\")\n    # -----------------------------------------------\n    input_data_option_group = parser.add_argument_group(\"Input Data Options\")\n    input_data_option_group.add_argument(\"-H\", \"--skip-header\", default=default_skip_header,\n                                       action=\"store_true\",\n                                       help=\"Skip header row. This has been changed from earlier version - Only one header row is supported, and the header row is used for column naming\")\n    input_data_option_group.add_argument(\"-d\", \"--delimiter\", default=default_delimiter,\n                                       help=\"Field delimiter. If none specified, then space is used as the delimiter.\")\n    input_data_option_group.add_argument(\"-p\", \"--pipe-delimited\", default=default_pipe_delimited,\n                                       action=\"store_true\",\n                                       help=\"Same as -d '|'. Added for convenience and readability\")\n    input_data_option_group.add_argument(\"-t\", \"--tab-delimited\", default=default_tab_delimited,\n                                       action=\"store_true\",\n                                       help=\"Same as -d <tab>. Just a shorthand for handling standard tab delimited file You can use $'\\\\t' if you want (this is how Linux expects to provide tabs in the command line\")\n    input_data_option_group.add_argument(\"-e\", \"--encoding\", default=default_encoding,\n                                       help=\"Input file encoding. Defaults to UTF-8. set to none for not setting any encoding - faster, but at your own risk...\")\n    input_data_option_group.add_argument(\"-z\", \"--gzipped\", default=default_gzipped, action=\"store_true\",\n                                       help=\"Data is gzipped. Useful for reading from stdin. For files, .gz means automatic gunzipping\")\n    input_data_option_group.add_argument(\"-A\", \"--analyze-only\", default=default_analyze_only,\n                                       action='store_true',\n                                       help=\"Analyze sample input and provide information about data types\")\n    input_data_option_group.add_argument(\"-m\", \"--mode\", default=default_mode,\n                                       help=\"Data parsing mode. fluffy, relaxed and strict. In strict mode, the -c column-count parameter must be supplied as well\")\n    input_data_option_group.add_argument(\"-c\", \"--column-count\", default=default_column_count,\n                                       help=\"Specific column count when using relaxed or strict mode\")\n    input_data_option_group.add_argument(\"-k\", \"--keep-leading-whitespace\", dest=\"keep_leading_whitespace_in_values\",\n                                       default=default_keep_leading_whitespace_in_values, action=\"store_true\",\n                                       help=\"Keep leading whitespace in values. Default behavior strips leading whitespace off values, in order to provide out-of-the-box usability for simple use cases. If you need to preserve whitespace, use this flag.\")\n    input_data_option_group.add_argument(\"--disable-double-double-quoting\", \n                                       default=default_disable_double_double_quoting, action=\"store_false\",\n                                       help=\"Disable support for double double-quoting for escaping the double quote character. By default, you can use \\\"\\\" inside double quoted fields to escape double quotes. Mainly for backward compatibility.\")\n    input_data_option_group.add_argument(\"--disable-escaped-double-quoting\", \n                                       default=default_disable_escaped_double_quoting, action=\"store_false\",\n                                       help=\"Disable support for escaped double-quoting for escaping the double quote character. By default, you can use \\\\\\\" inside double quoted fields to escape double quotes. Mainly for backward compatibility.\")\n    input_data_option_group.add_argument(\"--as-text\", dest=\"disable_column_type_detection\",\n                                       default=default_disable_column_type_detection, action=\"store_true\",\n                                       help=\"Don't detect column types - All columns will be treated as text columns\")\n    input_data_option_group.add_argument(\"-w\", \"--input-quoting-mode\", \n                                       default=default_input_quoting_mode,\n                                       help=\"Input quoting mode. Possible values are all, minimal and none. Note the slightly misleading parameter name, and see the matching -W parameter for output quoting.\")\n    input_data_option_group.add_argument(\"-M\", \"--max-column-length-limit\", \n                                       default=default_max_column_length_limit,\n                                       help=\"Sets the maximum column length.\")\n    input_data_option_group.add_argument(\"-U\", \"--with-universal-newlines\", \n                                       default=default_with_universal_newlines, action=\"store_true\",\n                                       help=\"Expect universal newlines in the data. Limitation: -U works only with regular files for now, stdin or .gz files are not supported yet.\")\n    # -----------------------------------------------\n    output_data_option_group = parser.add_argument_group(\"Output Options\")\n    output_data_option_group.add_argument(\"-D\", \"--output-delimiter\", \n                                        default=default_output_delimiter,\n                                        help=\"Field delimiter for output. If none specified, then the -d delimiter is used if present, or space if no delimiter is specified\")\n    output_data_option_group.add_argument(\"-P\", \"--pipe-delimited-output\", \n                                        default=default_pipe_delimited_output, action=\"store_true\",\n                                        help=\"Same as -D '|'. Added for convenience and readability.\")\n    output_data_option_group.add_argument(\"-T\", \"--tab-delimited-output\", \n                                        default=default_tab_delimited_output, action=\"store_true\",\n                                        help=\"Same as -D <tab>. Just a shorthand for outputting tab delimited output. You can use -D $'\\\\t' if you want.\")\n    output_data_option_group.add_argument(\"-O\", \"--output-header\", default=default_output_header,\n                                        action=\"store_true\",\n                                        help=\"Output header line. Output column-names are determined from the query itself. Use column aliases in order to set your column names in the query. For example, 'select name FirstName,value1/value2 MyCalculation from ...'. This can be used even if there was no header in the input.\")\n    output_data_option_group.add_argument(\"-b\", \"--beautify\", default=default_beautify,\n                                        action=\"store_true\",\n                                        help=\"Beautify output according to actual values. Might be slow...\")\n    output_data_option_group.add_argument(\"-f\", \"--formatting\", default=default_formatting,\n                                        help=\"Output-level formatting, in the format X=fmt,Y=fmt etc, where X,Y are output column numbers (e.g. 1 for first SELECT column etc.\")\n    output_data_option_group.add_argument(\"-E\", \"--output-encoding\", \n                                        default=default_output_encoding,\n                                        help=\"Output encoding. Defaults to 'none', leading to selecting the system/terminal encoding\")\n    output_data_option_group.add_argument(\"-W\", \"--output-quoting-mode\", \n                                        default=default_output_quoting_mode,\n                                        help=\"Output quoting mode. Possible values are all, minimal, nonnumeric and none. Note the slightly misleading parameter name, and see the matching -w parameter for input quoting.\")\n    output_data_option_group.add_argument(\"-L\", \"--list-user-functions\", \n                                        default=default_list_user_functions, action=\"store_true\",\n                                        help=\"List all user functions\")\n    parser.add_argument(\"--overwrite-qsql\", default=default_overwrite_qsql,\n                      help=\"When used, qsql files (both caches and store-to-db) will be overwritten if they already exist. Use with care.\")\n    # -----------------------------------------------\n    query_option_group = parser.add_argument_group(\"Query Related Options\")\n    query_option_group.add_argument(\"-q\", \"--query-filename\", default=default_query_filename,\n                                  help=\"Read query from the provided filename instead of the command line, possibly using the provided query encoding (using -Q).\")\n    query_option_group.add_argument(\"-Q\", \"--query-encoding\", default=default_query_encoding,\n                                  help=\"query text encoding. Experimental. Please send your feedback on this\")\n    # -----------------------------------------------\n    parser.add_argument('leftover', nargs='*')\n    args = parser.parse_args()\n    return args.leftover, args, parser\n\n\ndef parse_qrc_file():\n    p = configparser.ConfigParser()\n    if QRC_FILENAME_ENVVAR in os.environ:\n        qrc_filename = os.environ[QRC_FILENAME_ENVVAR]\n        if qrc_filename != 'None':\n            xprint(\"qrc filename is %s\" % qrc_filename)\n            if os.path.exists(qrc_filename):\n                p.read([os.environ[QRC_FILENAME_ENVVAR]])\n            else:\n                print('QRC_FILENAME env var exists, but cannot find qrc file at %s' % qrc_filename, file=sys.stderr)\n                sys.exit(244)\n        else:\n            pass  # special handling of 'None' env var value for QRC_FILENAME. Allows to eliminate the default ~/.qrc reading\n    else:\n        qrc_filename = os.path.expanduser('~/.qrc')\n        p.read([qrc_filename, '.qrc'])\n    return p, qrc_filename\n\n\ndef initialize_default_data_streams():\n    data_streams_dict = {\n        '-': DataStream('stdin', '-', sys.stdin)\n    }\n    return data_streams_dict\n\n\ndef parse_options(args, options):\n    if options.list_user_functions:\n        print_user_functions()\n        sys.exit(0)\n    if len(args) == 0 and options.query_filename is None:\n        print_credentials()\n        print(\"Must provide at least one query in the command line, or through a file with the -q parameter\",\n              file=sys.stderr)\n        sys.exit(1)\n    if options.query_filename is not None:\n        if len(args) != 0:\n            print(\"Can't provide both a query file and a query on the command line\", file=sys.stderr)\n            sys.exit(1)\n        try:\n            f = open(options.query_filename, 'rb')\n            query_strs = [f.read()]\n            f.close()\n        except:\n            print(\"Could not read query from file %s\" % options.query_filename, file=sys.stderr)\n            sys.exit(1)\n    else:\n        if sys.stdin.encoding is not None:\n            query_strs = [x.encode(sys.stdin.encoding) for x in args]\n        else:\n            query_strs = args\n    if options.query_encoding is not None and options.query_encoding != 'none':\n        try:\n            for idx in range(len(query_strs)):\n                query_strs[idx] = query_strs[idx].decode(options.query_encoding).strip()\n\n                if len(query_strs[idx]) == 0:\n                    print(\"Query cannot be empty (query number %s)\" % (idx + 1), file=sys.stderr)\n                    sys.exit(1)\n\n        except Exception as e:\n            print(\"Could not decode query number %s using the provided query encoding (%s)\" % (\n            idx + 1, options.query_encoding), file=sys.stderr)\n            sys.exit(3)\n    ###\n    if options.mode not in ['relaxed', 'strict']:\n        print(\"Parsing mode can either be relaxed or strict\", file=sys.stderr)\n        sys.exit(13)\n    output_encoding = get_stdout_encoding(options.output_encoding)\n    try:\n        if six.PY3:\n            STDOUT = codecs.getwriter(output_encoding)(sys.stdout.buffer)\n        else:\n            STDOUT = codecs.getwriter(output_encoding)(sys.stdout)\n    except:\n        print(\"Could not create output stream using output encoding %s\" % (output_encoding), file=sys.stderr)\n        sys.exit(200)\n    # If the user flagged for a tab-delimited file then set the delimiter to tab\n    if options.tab_delimited:\n        if options.delimiter is not None and options.delimiter != '\\t':\n            print(\"Warning: -t parameter overrides -d parameter (%s)\" % options.delimiter, file=sys.stderr)\n        options.delimiter = '\\t'\n    # If the user flagged for a pipe-delimited file then set the delimiter to pipe\n    if options.pipe_delimited:\n        if options.delimiter is not None and options.delimiter != '|':\n            print(\"Warning: -p parameter overrides -d parameter (%s)\" % options.delimiter, file=sys.stderr)\n        options.delimiter = '|'\n    if options.delimiter is None:\n        options.delimiter = ' '\n    elif len(options.delimiter) != 1:\n        print(\"Delimiter must be one character only\", file=sys.stderr)\n        sys.exit(5)\n    if options.tab_delimited_output:\n        if options.output_delimiter is not None and options.output_delimiter != '\\t':\n            print(\"Warning: -T parameter overrides -D parameter (%s)\" % options.output_delimiter, file=sys.stderr)\n        options.output_delimiter = '\\t'\n    if options.pipe_delimited_output:\n        if options.output_delimiter is not None and options.output_delimiter != '|':\n            print(\"Warning: -P parameter overrides -D parameter (%s)\" % options.output_delimiter, file=sys.stderr)\n        options.output_delimiter = '|'\n    if options.output_delimiter:\n        # If output delimiter is specified, then we use it\n        options.output_delimiter = options.output_delimiter\n    else:\n        # Otherwise,\n        if options.delimiter:\n            # if an input delimiter is specified, then we use it as the output as\n            # well\n            options.output_delimiter = options.delimiter\n        else:\n            # if no input delimiter is specified, then we use space as the default\n            # (since no input delimiter means any whitespace)\n            options.output_delimiter = \" \"\n    try:\n        max_column_length_limit = int(options.max_column_length_limit)\n    except:\n        print(\"Max column length limit must be an integer larger than 2 (%s)\" % options.max_column_length_limit,\n              file=sys.stderr)\n        sys.exit(31)\n    if max_column_length_limit < 3:\n        print(\"Maximum column length must be larger than 2\",file=sys.stderr)\n        sys.exit(31)\n\n    csv.field_size_limit(max_column_length_limit)\n    xprint(\"Max column length limit is %s\" % options.max_column_length_limit)\n\n    if options.input_quoting_mode not in list(QTextAsData.input_quoting_modes.keys()):\n        print(\"Input quoting mode can only be one of %s. It cannot be set to '%s'\" % (\n        \",\".join(sorted(QTextAsData.input_quoting_modes.keys())), options.input_quoting_mode), file=sys.stderr)\n        sys.exit(55)\n    if options.output_quoting_mode not in list(QOutputPrinter.output_quoting_modes.keys()):\n        print(\"Output quoting mode can only be one of %s. It cannot be set to '%s'\" % (\n        \",\".join(QOutputPrinter.output_quoting_modes.keys()), options.input_quoting_mode), file=sys.stderr)\n        sys.exit(56)\n    if options.column_count is not None:\n        expected_column_count = int(options.column_count)\n        if expected_column_count < 1 or expected_column_count > int(options.max_column_length_limit):\n            print(\"Column count must be between 1 and %s\" % int(options.max_column_length_limit),file=sys.stderr)\n            sys.exit(90)\n    else:\n        # infer automatically\n        expected_column_count = None\n    if options.encoding != 'none':\n        try:\n            codecs.lookup(options.encoding)\n        except LookupError:\n            print(\"Encoding %s could not be found\" % options.encoding, file=sys.stderr)\n            sys.exit(10)\n    if options.save_db_to_disk_filename is not None:\n        if options.analyze_only:\n            print(\"Cannot save database to disk when running with -A (analyze-only) option.\", file=sys.stderr)\n            sys.exit(119)\n\n        print(\"Going to save data into a disk database: %s\" % options.save_db_to_disk_filename, file=sys.stderr)\n        if os.path.exists(options.save_db_to_disk_filename):\n            print(\"Disk database file %s already exists.\" % options.save_db_to_disk_filename, file=sys.stderr)\n            sys.exit(77)\n    # sys.exit(78) Deprecated, but shouldn't be reused\n    if options.caching_mode not in ['none', 'read', 'readwrite']:\n        print(\"caching mode must be none,read or readwrite\",file=sys.stderr)\n        sys.exit(85)\n    read_caching = options.caching_mode in ['read', 'readwrite']\n    write_caching = options.caching_mode in ['readwrite']\n\n    if options.max_attached_sqlite_databases <= 3:\n        print(\"Max attached sqlite databases must be larger than 3\")\n        sys.exit(99)\n\n    default_input_params = QInputParams(skip_header=options.skip_header,\n                                        delimiter=options.delimiter,\n                                        input_encoding=options.encoding,\n                                        gzipped_input=options.gzipped,\n                                        with_universal_newlines=options.with_universal_newlines,\n                                        parsing_mode=options.mode,\n                                        expected_column_count=expected_column_count,\n                                        keep_leading_whitespace_in_values=options.keep_leading_whitespace_in_values,\n                                        disable_double_double_quoting=options.disable_double_double_quoting,\n                                        disable_escaped_double_quoting=options.disable_escaped_double_quoting,\n                                        input_quoting_mode=options.input_quoting_mode,\n                                        disable_column_type_detection=options.disable_column_type_detection,\n                                        max_column_length_limit=max_column_length_limit,\n                                        read_caching=read_caching,\n                                        write_caching=write_caching,\n                                        max_attached_sqlite_databases=options.max_attached_sqlite_databases)\n\n    output_params = QOutputParams(\n        delimiter=options.output_delimiter,\n        beautify=options.beautify,\n        output_quoting_mode=options.output_quoting_mode,\n        formatting=options.formatting,\n        output_header=options.output_header,\n        encoding=output_encoding)\n    q_output_printer = QOutputPrinter(output_params, show_tracebacks=DEBUG)\n\n    return STDOUT, default_input_params, q_output_printer, query_strs\n\n\nif __name__ == '__main__':\n    run_standalone()\n"
  },
  {
    "path": "conftest.py",
    "content": "#!/usr/bin/env python\n\n# Required so pytest can find files properly\n\n\n"
  },
  {
    "path": "dist/fpm-config",
    "content": "-s dir\n--name q-text-as-data\n--license GPLv3\n--architecture x86_64\n--description \"q allows to perform SQL-like statements on tabular text data.\"\n--url https://github.com/harelba/q\n--maintainer \"Harel Ben-Attia <harelba@gmail.com>\"\n"
  },
  {
    "path": "dist/test-rpm-inside-container.sh",
    "content": "#!/bin/bash\nset -x\nset -e\n\nyum install -y python38 sqlite perl gcc python3-devel sqlite-devel\npip3 install -r test-requirements.txt\n\nrpm -i $1\nQ_EXECUTABLE=q Q_SKIP_EXECUTABLE_VALIDATION=true ./run-tests.sh -v\n"
  },
  {
    "path": "dist/test-using-deb.sh",
    "content": "#!/bin/bash\n\nset -x\nset -e\n\nsudo dpkg -i $1\nQ_EXECUTABLE=q Q_SKIP_EXECUTABLE_VALIDATION=true ./run-tests.sh -v\n\n"
  },
  {
    "path": "dist/test-using-rpm.sh",
    "content": "#!/bin/bash\n\nset -x\nset -e\n\nRPM_LOCATION=$1\n\ndocker run -i -v `pwd`:/q-sources -w /q-sources centos:8 /bin/bash -e -x ./dist/test-rpm-inside-container.sh ${RPM_LOCATION}\n"
  },
  {
    "path": "doc/AUTHORS",
    "content": "  Copyright (C) 2012-2014 Harel Ben-Attia (harelba@gmail.com, @harelba on twitter)\n\nHarel Ben-Attia <harelba@gmail.com> wrote the main program\n\n"
  },
  {
    "path": "doc/IMPLEMENTATION.markdown",
    "content": "# q - Treating Text as a Database \n\n## Implementation \n\nThe current implementation is written in Python using an in-memory database, in order to prevent the need for external dependencies. The implementation itself supports SELECT statements, including JOINs (Subqueries are supported only in the WHERE clause for now).\n\nPlease note that there is currently no checks and bounds on data size - It's up to the user to make sure things don't get too big.\n\nPlease make sure to read the limitations section as well.\n\nCode wise, I'm planning for a big refactoring, and I have added full test suite in the latest version, so it'll be easier to do properly.\n\n## Tests\n\nThe code includes a test suite runnable through `test/test-all`. If you're planning on sending a pull request, I'd appreciate if you could make sure that it doesn't fail. Additional ideas related to testing are most welcome.\n\n## Contact\nAny feedback/suggestions/complaints regarding this tool would be much appreciated. Contributions are most welcome as well, of course.\n\nHarel Ben-Attia, harelba@gmail.com, [@harelba](https://twitter.com/harelba) on Twitter\n\n"
  },
  {
    "path": "doc/LICENSE",
    "content": "GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "doc/RATIONALE.markdown",
    "content": "# q - Treating Text as a Database \n\n## Why aren't other Linux tools enough?\nThe standard Linux tools are amazing and I use them all the time, but the whole idea of Linux is mixing-and-matching the best tools for each part of job. This tool adds the declarative power of SQL to the Linux toolset, without loosing any of the other tools' benefits. In fact, I often use q together with other Linux tools, the same way I pipe awk/sed and grep together all the time.\n\nOne additional thing to note is that many Linux tools treat text as text and not as data. In that sense, you can look at q as a meta-tool which provides access to all the data-related tools that SQL provides (e.g. expressions, ordering, grouping, aggregation etc.).\n\n## Philosophy\nThis tool has been designed with general Linux/Unix design principles in mind. If you're interested in these general design principles, read the amazing book http://catb.org/~esr/writings/taoup/ and specifically http://catb.org/~esr/writings/taoup/html/ch01s06.html. If you believe that the way this tool works goes strongly against any of the principles, I would love to hear your view about it.\n\n## Contact\nAny feedback/suggestions/complaints regarding this tool would be much appreciated. Contributions are most welcome as well, of course.\n\nHarel Ben-Attia, harelba@gmail.com, [@harelba](https://twitter.com/harelba) on Twitter\n\n"
  },
  {
    "path": "doc/THANKS",
    "content": "  Copyright (C) 2012-2014 Harel Ben-Attia (harelba@gmail.com, @harelba on twitter)\n\nJens Neu (jens@zeeroos.de) - For writing the initial RPM package spec\nbarsnick (https://github.com/barsnick) - Thanks for additional RPM help\nStreakyCobra (https://github.com/StreakyCobra) - For providing Arch Linux RPMs\n"
  },
  {
    "path": "doc/USAGE.markdown",
    "content": "# q - Text as Data\n\n## SYNOPSIS\n\t`q <flags> <query>`\n\n\tExample Execution for a delimited file:\n\n\t\tq \"select * from myfile.csv\"\n\n\tExample Execution for an sqlite3 database:\n\n\t\tq \"select * from mydatabase.sqlite:::my_table_name\"\n\n            or\n\n\t\tq \"select * from mydatabase.sqlite\"\n\n            if the database file contains only one table\n\n\tAuto-caching of delimited files can be activated through `-C readwrite` (writes new caches if needed)  or `-C read` (only reads existing cache files)\n\n\tSetting the default caching mode (`-C`) can be done by writing a `~/.qrc` file. See docs for more info.\n\t\n## DESCRIPTION\nq's purpose is to bring SQL expressive power to the Linux command line and to provide easy access to text as actual data.\n\nq allows the following:\n\n* Performing SQL-like statements directly on tabular text data, auto-caching the data in order to accelerate additional querying on the same file\n* Performing SQL statements directly on multi-file sqlite3 databases, without having to merge them or load them into memory\n\nQuery should be an SQL-like query which contains filenames instead of table names (or - for stdin). The query itself should be provided as one parameter to the tool (i.e. enclosed in quotes).\n\nThe following filename types are supported:\n\n* Delimited-file filenames, including relative/absolute paths\n* sqlite3 database filenames, with an additional `:::<table_name>` for accessing a specific table. If a database contains only one table, then denoting the table name is not needed. Examples: `mydatabase.sqlite3:::users_table` or `my_single_table_database.sqlite`.\n\nUse `-H` to signify that the input contains a header line. Column names will be detected automatically in that case, and can be used in the query. If this option is not provided, columns will be named cX, starting with 1 (e.g. q \"SELECT c3,c8 from ...\").\n\nUse `-d` to specify the input delimiter.\n\nColumn types are auto detected by the tool, no casting is needed.\n\nPlease note that column names that include spaces need to be used in the query with back-ticks, as per the sqlite standard.\n\nQuery/Input/Output encodings are fully supported (and q tries to provide out-of-the-box usability in that area). Please use `-e`,`-E` and `-Q` to control encoding if needed.\n\nAll sqlite3 SQL constructs are supported, including joins across files (use an alias for each table), with the exception of CTE (for now).\n\nSee https://github.com/harelba/q for more details.\n\n## QUERY\nq gets one parameter - An SQL-like query. \n\nAny standard SQL expression, condition (both WHERE and HAVING), GROUP BY, ORDER BY etc. are allowed.\n\nJOINs are supported and Subqueries are supported in the WHERE clause, but unfortunately not in the FROM clause for now. Use table aliases when performing JOINs.\n\nThe SQL syntax itself is sqlite's syntax. For details look at https://www.sqlite.org/lang.html or search the net for examples.\n\n**NOTE:** Full type detection is implemented, so there is no need for any casting or anything.\n\n**NOTE2:** When using the `-O` output header option, use column name aliases if you want to control the output column names. For example, `q -O -H \"select count(*) cnt,sum(*) as mysum from -\"` would output `cnt` and `mysum` as the output header column names.\n\n## RUNTIME OPTIONS\nq can also get some runtime flags. The following parameters can be used, all optional:\n\n````\nOptions:\n  -h, --help            show this help message and exit\n  -v, --version         Print version\n  -V, --verbose         Print debug info in case of problems\n  -S SAVE_DB_TO_DISK_FILENAME, --save-db-to-disk=SAVE_DB_TO_DISK_FILENAME\n                        Save database to an sqlite database file\n  -C CACHING_MODE, --caching-mode=CACHING_MODE\n                        Choose the autocaching mode (none/read/readwrite).\n                        Autocaches files to disk db so further queries will be\n                        faster. Caching is done to a side-file with the same\n                        name of the table, but with an added extension .qsql\n  --dump-defaults       Dump all default values for parameters and exit. Can\n                        be used in order to make sure .qrc file content is\n                        being read properly.\n  --max-attached-sqlite-databases=MAX_ATTACHED_SQLITE_DATABASES\n                        Set the maximum number of concurrently-attached sqlite\n                        dbs. This is a compile time definition of sqlite. q's\n                        performance will slow down once this limit is reached\n                        for a query, since it will perform table copies in\n                        order to avoid that limit.\n  --overwrite-qsql=OVERWRITE_QSQL\n                        When used, qsql files (both caches and store-to-db)\n                        will be overwritten if they already exist. Use with\n                        care.\n\n  Input Data Options:\n    -H, --skip-header   Skip header row. This has been changed from earlier\n                        version - Only one header row is supported, and the\n                        header row is used for column naming\n    -d DELIMITER, --delimiter=DELIMITER\n                        Field delimiter. If none specified, then space is used\n                        as the delimiter.\n    -p, --pipe-delimited\n                        Same as -d '|'. Added for convenience and readability\n    -t, --tab-delimited\n                        Same as -d <tab>. Just a shorthand for handling\n                        standard tab delimited file You can use $'\\t' if you\n                        want (this is how Linux expects to provide tabs in the\n                        command line\n    -e ENCODING, --encoding=ENCODING\n                        Input file encoding. Defaults to UTF-8. set to none\n                        for not setting any encoding - faster, but at your own\n                        risk...\n    -z, --gzipped       Data is gzipped. Useful for reading from stdin. For\n                        files, .gz means automatic gunzipping\n    -A, --analyze-only  Analyze sample input and provide information about\n                        data types\n    -m MODE, --mode=MODE\n                        Data parsing mode. fluffy, relaxed and strict. In\n                        strict mode, the -c column-count parameter must be\n                        supplied as well\n    -c COLUMN_COUNT, --column-count=COLUMN_COUNT\n                        Specific column count when using relaxed or strict\n                        mode\n    -k, --keep-leading-whitespace\n                        Keep leading whitespace in values. Default behavior\n                        strips leading whitespace off values, in order to\n                        provide out-of-the-box usability for simple use cases.\n                        If you need to preserve whitespace, use this flag.\n    --disable-double-double-quoting\n                        Disable support for double double-quoting for escaping\n                        the double quote character. By default, you can use \"\"\n                        inside double quoted fields to escape double quotes.\n                        Mainly for backward compatibility.\n    --disable-escaped-double-quoting\n                        Disable support for escaped double-quoting for\n                        escaping the double quote character. By default, you\n                        can use \\\" inside double quoted fields to escape\n                        double quotes. Mainly for backward compatibility.\n    --as-text           Don't detect column types - All columns will be\n                        treated as text columns\n    -w INPUT_QUOTING_MODE, --input-quoting-mode=INPUT_QUOTING_MODE\n                        Input quoting mode. Possible values are all, minimal\n                        and none. Note the slightly misleading parameter name,\n                        and see the matching -W parameter for output quoting.\n    -M MAX_COLUMN_LENGTH_LIMIT, --max-column-length-limit=MAX_COLUMN_LENGTH_LIMIT\n                        Sets the maximum column length.\n    -U, --with-universal-newlines\n                        Expect universal newlines in the data. Limitation: -U\n                        works only with regular files for now, stdin or .gz\n                        files are not supported yet.\n\n  Output Options:\n    -D OUTPUT_DELIMITER, --output-delimiter=OUTPUT_DELIMITER\n                        Field delimiter for output. If none specified, then\n                        the -d delimiter is used if present, or space if no\n                        delimiter is specified\n    -P, --pipe-delimited-output\n                        Same as -D '|'. Added for convenience and readability.\n    -T, --tab-delimited-output\n                        Same as -D <tab>. Just a shorthand for outputting tab\n                        delimited output. You can use -D $'\\t' if you want.\n    -O, --output-header\n                        Output header line. Output column-names are determined\n                        from the query itself. Use column aliases in order to\n                        set your column names in the query. For example,\n                        'select name FirstName,value1/value2 MyCalculation\n                        from ...'. This can be used even if there was no\n                        header in the input.\n    -b, --beautify      Beautify output according to actual values. Might be\n                        slow...\n    -f FORMATTING, --formatting=FORMATTING\n                        Output-level formatting, in the format X=fmt,Y=fmt\n                        etc, where X,Y are output column numbers (e.g. 1 for\n                        first SELECT column etc.\n    -E OUTPUT_ENCODING, --output-encoding=OUTPUT_ENCODING\n                        Output encoding. Defaults to 'none', leading to\n                        selecting the system/terminal encoding\n    -W OUTPUT_QUOTING_MODE, --output-quoting-mode=OUTPUT_QUOTING_MODE\n                        Output quoting mode. Possible values are all, minimal,\n                        nonnumeric and none. Note the slightly misleading\n                        parameter name, and see the matching -w parameter for\n                        input quoting.\n    -L, --list-user-functions\n                        List all user functions\n\n  Query Related Options:\n    -q QUERY_FILENAME, --query-filename=QUERY_FILENAME\n                        Read query from the provided filename instead of the\n                        command line, possibly using the provided query\n                        encoding (using -Q).\n    -Q QUERY_ENCODING, --query-encoding=QUERY_ENCODING\n                        query text encoding. Experimental. Please send your\n                        feedback on this\n```\n\n### Table names\nThe table names are the actual file names that you want to read from. Path names are allowed. Use \"-\" if you want to read from stdin (e.g. `q \"SELECT * FROM -\"`)\n\nWildcard matches are supported - For example: `SELECT ... FROM ... mydata*.dat`\n\nFiles with .gz extension are considered to be gzipped and decompressed on the fly.\n\n### Parsing Modes\nq supports two parsing modes:\n\n* `relaxed` - This is the default mode. It tries to lean towards simplicity of use. When a row doesn't contains enough columns, they'll be filled with nulls, and when there are too many, the extra values will be merged to the last column. Defining the number of expected columns in this mode is done using the `-c` parameter. If it is not provided, then the number of columns is detected automatically (In most use cases, there is no need to specify `-c`)\n* `strict` - Strict mode is for hardcore csv/tsv parsing. Whenever a row doesn't contain the proper number of columns, processing will stop. `-c` must be provided when using this mode\n\n### Output formatting option\nThe format of F is as a list of X=f separated by commas, where X is a column number and f is a python format:\n\n* X - column number - This is the SELECTed column (or expression) number, not the one from the original table. E.g, 1 is the first SELECTed column, 3 is the third SELECTed column.\n* f - A python formatting string such as {} - See https://www.w3schools.com/python/ref_string_format.asp for details if needed.\n\n## EXAMPLES\nExample 1: `ls -ltrd * | q \"select c1,count(1) from - group by c1\"`\n\n\tThis example would print a count of each unique permission string in the current folder.\n\nExample 2: `seq 1 1000 | q \"select avg(c1),sum(c1) from -\"`\n\n\tThis example would provide the average and the sum of the numbers in the range 1 to 1000\n\nExample 3: `sudo find /tmp -ls | q \"select c5,c6,sum(c7)/1024.0/1024 as total from - group by c5,c6 order by total desc\"`\n\n\tThis example will output the total size in MB per user+group in the /tmp subtree\n\nExample 4: `ps -ef | q -H \"select UID,count(*) cnt from - group by UID order by cnt desc limit 3\"`\n\n\tThis example will show process counts per UID, calculated from ps data. Note that the column names provided by ps are being used as column name in the query (The -H flag activates that option)\n\n## AUTHOR\nHarel Ben-Attia (harelba@gmail.com)\n\n[@harelba](https://twitter.com/harelba) on Twitter\n\nAny feedback/suggestions/complaints regarding this tool would be much appreciated. Contributions are most welcome as well, of course.\n\n## COPYRIGHT\nCopyright (C) 2012--2021 Harel Ben Attia\n\nThis program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA  02110-1301, USA \n\n\n"
  },
  {
    "path": "examples/EXAMPLES.markdown",
    "content": "# q - Treating Text as a Database \n\nSee below for a JOIN example.\n\n## Tutorial\nThis is a tutorial for beginners. If you're familiar with the concept and just wanna see some full fledged examples, take a look [here](README.markdown#examples) in the main page.\n\nTutorial steps:\n\n1.  We'll start with a simple example and work from there. The file `exampledatafile` contains the output of an `ls -l` command, a list of files in some directory. In this example we'll do some calculations on this file list.\n  * The following commands will count the lines in the file *exampledatafile*, effectively getting the number of files in the directory. The output will be exactly as if we ran the `wc -l` command.  \n\n            q \"SELECT COUNT(1) FROM exampledatafile\"    \n\n            cat exampledatafile | q \"SELECT COUNT(1) FROM -\"   \n        \n  * Now, let's assume we want to know the number of files per date in the directory. Notice that the date is in column 6.\n\n            q \"SELECT c6,COUNT(1) FROM exampledatafile GROUP BY c6\"   \n\n  * The results will show the number of files per date. However, there's a lot of \"noise\" - dates in which there is only one file. Let's leave only the ones which have 3 files or more:  \n\n            q \"SELECT c6,COUNT(1) AS cnt FROM exampledatafile GROUP BY c6 HAVING cnt >= 3\"   \n\n  * Now, let's see if we can get something more interesting. The following command will provide the **total size** of the files for each date. Notice that the file size is in c5.  \n\n            q \"SELECT c6,SUM(c5) AS size FROM exampledatafile GROUP BY c6\"   \n\n  * We can see the results. However, the sums are in bytes. Let's show the same results but in KB:  \n\n            q \"SELECT c6,SUM(c5)/1024.0 AS size FROM exampledatafile GROUP BY c6\"  \n\n  * The last command provided us with a list of results, but there is no order and the list is too long. Let's get the Top 5 dates:  \n\n            q \"SELECT c6,SUM(c5)/1024.0 AS size FROM exampledatafile GROUP BY c6 ORDER BY size DESC LIMIT 5\"   \n\n  * Now we'll see how we can format the output itself, so it looks better:  \n\n            q -f \"2=%4.2f\" \"SELECT c6,SUM(c5)/1024.0 AS size FROM exampledatafile GROUP BY c6 ORDER BY size DESC LIMIT 5\"  \n        \n  * (An example of using JOIN will be added here - In the mean time just remember you have to use table alias for JOINed \"tables\")\n        \n2. A more complicated example, showing time manipulation. Let's assume that we have a file with a timestamp as its first column. We'll show how it's possible to get the number of rows per full minute:  \n\n        q \"SELECT DATETIME(ROUND(c1/60000)*60000/1000,'unixepoch','-05:00') as min, COUNT(1) FROM datafile*.gz GROUP BY min\"  \n        \n   There are several things to notice here:\n   \n   * The timestamp value is in the first column, hence c1.\n   * The timestamp is assumed to be a unix epoch timestamp, but in ms, and DATETIME accepts seconds, so we need to divide by 1000\n   * The full-minute rounding is done by dividing by 60000 (ms), rounding and then multiplying by the same amount. Rounding to an hour, for example, would be the same except for having 3600000 instead of 60000.\n   * We use DATETIME's capability in order to output the time in localtime format. In that case, it's converted to New York time (hence the -5 hours)\n   * The filename is actually all files matching `datafile*.gz` - Multiple files can be read, and since they have a .gz extension, they are decompressed on the fly.\n   * **NOTE:** For non-SQL people, the date manipulation may seem odd at first, but this is standard SQL processing for timestamps and it's easy to get used to.\n\n## JOIN example\n\n__Command 1 (Join data from two files):__\n\nThe following command _joins_ an ls output (`exampledatafile`) and a file containing rows of **group-name,email**  (`group-emails-example`) and provides a row of **filename,email** for each of the emails of the group. For brevity of output, there is also a filter for a specific filename called `ppp` which is achieved using a WHERE clause.\n```bash\nq \"select myfiles.c8,emails.c2 from exampledatafile myfiles join group-emails-example emails on (myfiles.c4 = emails.c1) where myfiles.c8 = 'ppp'\"\n```\n\n__Output 1: (rows of filename,email):__\n```bash\nppp dip.1@otherdomain.com\nppp dip.2@otherdomain.com\n```\n\nYou can see that the ppp filename appears twice, each time matched to one of the emails of the group `dip` to which it belongs. Take a look at the files [`exampledatafile`](exampledatafile) and [`group-emails-example`](group-emails-example) for the data.\n\n## Writing the data into an sqlite3 database\nq now supports writing its data into a disk base sqlite3 database file. In order to write the data to a database disk use the `-S` parameter (`--save-db-to-disk`) with a filename as a parameter. Note that you still need to provide a query as a parameter, even though it will not be executed. The tool will provide the proper sqlite3 query to run after writing the data to the database, allowing you to copy-paste it into the sqlite3 command line. If you don't care about running any query, just use \"select 1\" as the query.\n\nHere's an example that will write the output into `some.db` for further processing. Note that we've added the `-c 1` parameter to prevent q warning us about having only one column.\n```\n$ seq 1 100 | ./q \"select count(*) from -\" -S some.db -c 1\nGoing to save data into a disk database: some.db\nData has been loaded in 0.002 seconds\nSaving data to db file some.db\nData has been saved into some.db . Saving has taken 0.018 seconds\nQuery to run on the database: select count(*) from `-`;\n\n$ sqlite3 some.db\nSQLite version 3.19.3 2017-06-27 16:48:08\nEnter \".help\" for usage hints.\nsqlite> .tables\n-\nsqlite> .schema\nCREATE TABLE IF NOT EXISTS \"-\" (\"c1\" INT);\nsqlite> select count(*) from `-`;\n100\nsqlite>\n```\n\nNote that table names are explicitly set to the filenames in the original query (e.g. filenames), which means that in many cases you'd need to escape the table names in sqlite3 with backticks. For example, the name of the table above is `-`, and in order to use it in an sqlite3 query, it is backticked, otherwise it won't conform to a proper table name. I've decided to emphasize consistency and simplicity in this case, instead of trying to provide some normalization/sanitation of filenames, since I believe that doing it would cause much confusion and will be less effective. Any ideas and comments are this are most welcome obviously.\n\n### Choosing the method of writing the sqlite3 database\nThere's another parameter that controls the method of writing to the sqlite3 database - `--save-db-to-disk-method`. The value can either be `standard` or `fast`. The fast method requires changes in the packaging of q, since it's dependent on another python module (https://github.com/husio/python-sqlite3-backup by @husio - Thanks!). However, there are some complications with seamlessly packaging it without possibly causing some backward compatibility issues (see PR #159 for some details), so it's not the standard method as of yet. If you're an advanced user, and in need for the faster method due to very large files etc., you'd need to manually install this python package for the fast method to work - Run `pip install sqlitebck` on your python installation. Obviously, I'm considering this as a bug that I need to fix.\n\n## Installation\nInstallation instructions can be found [here](../doc/INSTALL.markdown)\n\n## Contact\nAny feedback/suggestions/complaints regarding this tool would be much appreciated. Contributions are most welcome as well, of course.\n\nHarel Ben-Attia, harelba@gmail.com, [@harelba](https://twitter.com/harelba) on Twitter\n\n"
  },
  {
    "path": "examples/exampledatafile",
    "content": "-rw-r--r--  1 root root     2064 2006-11-23 21:33 netscsid.conf\n-rw-r--r--  1 root root     1343 2007-01-09 20:39 wodim.conf\n-rw-r--r--  1 root root      112 2007-06-22 18:08 apg.conf\n-rw-r--r--  1 root root    15752 2009-07-25 18:13 ltrace.conf\n-rw-r--r--  1 root root      624 2010-05-16 14:18 mtools.conf\n-rw-r--r--  1 root root      395 2010-06-20 11:11 anacrontab\n-rw-r--r--  1 root root    18673 2010-10-18 06:49 globash.rc\n-rw-r--r--  1 root root    23958 2010-11-15 10:07 mime.types\n-rw-r--r--  1 root root      449 2010-11-15 10:07 mailcap.order\n-rw-r--r--  1 root root     8453 2010-12-03 22:32 nanorc\n-rwxr-xr-x  1 root root      268 2010-12-07 12:10 rmt\n-rw-r--r--  1 root root     1147 2011-01-04 16:27 rarfiles.lst\n-rw-r--r--  1 root root      600 2011-03-09 13:22 deluser.conf\ndrwxr-xr-x  2 root root     4096 2011-03-15 23:05 ODBCDataSources\n-rw-r--r--  1 root root        0 2011-03-15 23:05 odbc.ini\n-rw-r--r--  1 root root      801 2011-03-17 20:09 mke2fs.conf\ndrwxr-xr-x  2 root root     4096 2011-04-30 19:12 insserv.conf.d\n-rw-r--r--  1 root root      839 2011-04-30 19:12 insserv.conf\ndrwxr-xr-x  3 root root     4096 2011-04-30 19:12 insserv\n-rw-r--r--  1 root root      373 2011-05-01 02:15 rearj.cfg\n-rw-r--r--  1 root root     1260 2011-05-02 15:19 ucf.conf\n-rw-r-----  1 root daemon    144 2011-05-16 13:32 at.deny\n-rw-r--r--  1 root root     4496 2011-05-17 23:21 wgetrc\ndrwxr-xr-x  2 root root     4096 2011-05-18 12:01 libpaper.d\n-rw-r--r--  1 root root     1975 2011-05-18 13:00 bash.bashrc\n-rw-r-----  1 root fuse      216 2011-05-18 13:12 fuse.conf\n-rw-r--r--  1 root root    19666 2011-05-24 18:26 services\n-rw-r--r--  1 root root      887 2011-05-24 18:26 rpc\n-rw-r--r--  1 root root     2859 2011-05-24 18:26 protocols\n-rw-r--r--  1 root root     4728 2011-06-07 14:10 hdparm.conf\n-rw-r--r--  1 root root     2083 2011-06-10 19:58 sysctl.conf\n-rw-r--r--  1 root root     2290 2011-06-14 18:51 libuser.conf\n-rw-r--r--  1 root root     1195 2011-06-17 20:13 rsyslog.conf\n-rw-r--r--  1 root root     2570 2011-06-22 13:39 locale.alias\n-rw-r--r--  1 root root     2969 2011-06-23 10:01 debconf.conf\n-rw-r--r--  1 root root     3828 2011-06-24 12:28 securetty\n-rw-r--r--  1 root root    10551 2011-06-24 12:28 login.defs\n-rw-r--r--  1 root root       91 2011-07-08 20:13 networks\n-rw-r--r--  1 root root      267 2011-07-08 20:13 legal\n-rw-r--r--  1 root root       92 2011-07-08 20:13 host.conf\n-rw-r--r--  1 root root       11 2011-07-08 20:13 debian_version\n-rw-r--r--  1 root root    10183 2011-07-18 23:45 sensors3.conf\n-rw-r--r--  1 root root     3587 2011-07-27 14:14 lftp.conf\n-rw-r--r--  1 root root     5173 2011-07-27 14:32 manpath.config\n-rw-r--r--  1 root root      645 2011-07-27 14:36 ts.conf\n-rw-r--r--  1 root root     1586 2011-07-27 14:57 request-key.conf\n-rw-r--r--  1 root root      111 2011-08-08 23:52 magic.mime\n-rw-r--r--  1 root root      111 2011-08-08 23:52 magic\n-rw-r--r--  1 root root      321 2011-08-09 19:16 blkid.conf\ndrwxr-xr-x  2 root root     4096 2011-08-09 19:19 usb_modeswitch.d\n-rw-r--r--  1 root root     3279 2011-08-11 15:59 lsb-base-logging.sh\n-rw-r--r--  1 root root      326 2011-08-17 16:15 updatedb.conf\n-rw-r--r--  1 root root      552 2011-08-19 04:05 pam.conf\n-rw-r--r--  1 root root      652 2011-08-25 16:14 zsh_command_not_found\n-rw-r--r--  1 root root      592 2011-08-26 11:58 usb_modeswitch.conf\n-rw-r--r--  1 root root     1721 2011-09-01 19:49 inputrc\n-r--r-----  1 root root      574 2011-09-11 22:09 sudoers\ndrwxr-xr-x  2 root root     4096 2011-09-19 12:51 lsb-base\n-rw-r--r--  1 root root      724 2011-09-20 03:04 crontab\n-rw-r--r--  1 root root      643 2011-09-20 08:04 colord.conf\n-rw-r--r--  1 root root      599 2011-10-04 18:19 logrotate.conf\n-rw-r--r--  1 root root      344 2011-10-04 21:56 bindresvport.blacklist\n-rw-r--r--  1 root root     3343 2011-10-04 21:56 gai.conf\n-rw-r--r--  1 root root    58753 2011-10-04 22:53 bash_completion\ndrwxr-xr-x  2 root root     4096 2011-10-05 22:05 update-notifier\n-rw-r--r--  1 root root      100 2011-10-08 01:45 lsb-release\n-rw-r--r--  1 root root       13 2011-10-09 09:31 issue.net\n-rw-r--r--  1 root root       20 2011-10-09 09:31 issue\n-rw-r--r--  1 root root     1309 2011-10-09 09:41 kerneloops.conf\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:26 opt\n-rw-r--r--  1 root root       34 2011-10-12 16:26 ld.so.conf\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:27 terminfo\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:27 python2.7\n-rw-r--r--  1 root root      547 2011-10-12 16:27 profile\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:27 iproute2\n-rw-r--r--  1 root root       79 2011-10-12 16:27 environment\n-rw-r--r--  1 root root      165 2011-10-12 16:27 shells\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:27 depmod.d\n-rw-r--r--  1 root root     2981 2011-10-12 16:27 adduser.conf\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:27 udev\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:27 sysctl.d\n-rwxr-xr-x  1 root root      306 2011-10-12 16:27 rc.local\ndrwxr-xr-x  6 root root     4096 2011-10-12 16:27 network\ndrwxr-xr-x  5 root root     4096 2011-10-12 16:27 initramfs-tools\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:27 systemd\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:27 sudoers.d\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:27 vim\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:27 newt\ndrwxr-xr-x  4 root root     4096 2011-10-12 16:27 dhcp\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:27 cron.hourly\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:27 python\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:27 kbd\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:27 console-setup\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:28 ca-certificates\ndrwxr-xr-x  4 root root     4096 2011-10-12 16:28 perl\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:28 pkcs11\ndrwxr-xr-x  5 root root     4096 2011-10-12 16:28 pm\ndrwxr-xr-x  6 root root     4096 2011-10-12 16:28 gconf\ndrwxr-xr-x  6 root root     4096 2011-10-12 16:28 apm\ndrwxr-xr-x  5 root root     4096 2011-10-12 16:28 polkit-1\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:28 emacs\ndrwxr-xr-x  5 root root     4096 2011-10-12 16:28 ConsoleKit\ndrwxr-xr-x  4 root root     4096 2011-10-12 16:28 ghostscript\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:28 doc-base\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:28 gnome-settings-daemon\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:28 etc\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:28 sound\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:29 gnome-vfs-2.0\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:29 ifplugd\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:29 dhcp3\ndrwxr-xr-x  4 root root     4096 2011-10-12 16:29 fonts\ndrwxr-xr-x  4 root root     4096 2011-10-12 16:29 ssl\n-rw-r--r--  1 root root     7014 2011-10-12 16:29 ca-certificates.conf\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:29 foomatic\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:29 gtk-3.0\n-rw-r--r--  1 root root      880 2011-10-12 16:29 hosts.deny\n-rw-r--r--  1 root root      580 2011-10-12 16:29 hosts.allow\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:29 sensors.d\ndrwxr-xr-x  4 root root     4096 2011-10-12 16:29 dbus-1\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:29 groff\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:29 calendar\ndrwxr-xr-x  4 root root     4096 2011-10-12 16:29 security\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:29 apparmor\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:29 profile.d\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:29 grub.d\ndrwxr-s---  2 root dip      4096 2011-10-12 16:29 chatscripts\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:29 update-manager\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:29 ufw\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:29 rsyslog.d\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:30 acpi\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 gnome-app-install\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 cron.monthly\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 cron.d\ndrwxr-xr-x  5 root root     4096 2011-10-12 16:30 apport\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 cron.weekly\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:30 avahi\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 at-spi2\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 bluetooth\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:30 sgml\ndrwxr-xr-x  4 root root     4096 2011-10-12 16:30 defoma\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:30 compizconfig\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 checkbox.d\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 skel\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 gdb\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:30 firefox\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 obex-data-server\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 UPower\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 snmp\n-rw-r--r--  1 root root      513 2011-10-12 16:30 nsswitch.conf\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 wpa_supplicant\ndrwxr-xr-x  8 root dip      4096 2011-10-12 16:30 ppp\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 pcmcia\ndrwxr-xr-x  5 root root     4096 2011-10-12 16:30 NetworkManager\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 cupshelpers\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 xml\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 thunderbird\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 update-motd.d\ndrwxr-xr-x  4 root root     4096 2011-10-12 16:30 speech-dispatcher\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 ginn\ndrwxr-xr-x  2 root root    12288 2011-10-12 16:30 brltty\n-rw-r--r--  1 root root       33 2011-10-12 16:30 brlapi.key\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 gamin\n-rw-r--r--  1 root root     7649 2011-10-12 16:30 pnm2ppa.conf\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:30 hp\ndrwxr-xr-x  4 root root     4096 2011-10-12 16:30 mono\ndrwxr-xr-x  2 root root     4096 2011-10-12 16:31 xul-ext\ndrwxr-xr-x  3 root root     4096 2011-10-12 16:31 sane.d\n-rw-r--r--  1 root root       54 2011-10-12 16:31 crypttab\n-rw-r--r--  1 root root      227 2011-12-18 11:43 hosts\n-rw-r--r--  1 root root       13 2011-12-18 11:43 hostname\n-rw-r--r--  1 root root       10 2011-12-18 11:45 adjtime\ndrwxr-xr-x  2 root root     4096 2011-12-18 11:51 libreoffice\ndrwxr-xr-x  2 root root     4096 2011-12-18 11:52 dictionaries-common\n-rw-r--r--  1 root root      350 2011-12-18 11:52 popularity-contest.conf\n-rw-r--r--  1 root root        7 2011-12-18 11:52 papersize\n-rw-r--r--  1 root root       91 2011-12-18 11:52 kernel-img.conf\n-rw-r--r--  1 root root       15 2011-12-18 12:02 timezone\n-rw-r--r--  1 root root     2197 2011-12-18 12:02 localtime\ndrwxr-xr-x  2 root root     4096 2011-12-18 12:04 ldap\ndrwxr-xr-x  2 root root     4096 2011-12-18 12:04 pulse\ndrwxr-xr-x  2 root root     4096 2011-12-18 12:04 timidity\ndrwxr-xr-x  2 root root     4096 2011-12-18 12:04 wildmidi\ndrwxr-xr-x  2 root root     4096 2011-12-18 12:04 gtk-2.0\ndrwxr-xr-x  5 root root     4096 2011-12-18 12:05 java-6-openjdk\ndrwxr-xr-x  2 root root     4096 2011-12-18 12:05 icedtea-web\ndrwxr-xr-x  6 root root     4096 2011-12-18 12:08 kernel\ndrwxr-xr-x  3 root root     4096 2011-12-18 12:09 OpenCL\ndrwxr-xr-x  3 root root     4096 2011-12-18 12:09 dkms\ndrwxr-xr-x  2 root root     4096 2011-12-18 12:09 modprobe.d\n-rw-------  1 root harel       0 2011-12-18 13:21 mtab.fuselock\ndrwxr-xr-x  2 root root     4096 2011-12-18 13:30 gnome\ndrwxr-xr-x  4 root root     4096 2011-12-18 14:44 java-6-sun\ndrwxr-xr-x  2 root root     4096 2011-12-18 15:06 subversion\ndrwxr-xr-x  2 root root     4096 2011-12-18 15:37 bonobo-activation\ndrwxr-xr-x  2 root root     4096 2011-12-19 10:13 purple\ndrwxr-xr-x  2 root root     4096 2011-12-19 14:27 lightdm\ndrwxr-xr-x  2 root root     4096 2011-12-19 22:49 ld.so.conf.d\ndrwxr-xr-x  5 root root     4096 2011-12-19 22:50 xdg\ndrwxr-xr-x  6 root root     4096 2011-12-19 23:19 resolvconf\ndrwxr-xr-x  2 root root     4096 2011-12-19 23:19 rcS.d\ndrwxr-xr-x  2 root root     4096 2011-12-22 18:57 ssh\ndrwxr-xr-x  2 root root     4096 2011-12-23 12:05 qt3\ndrwxr-xr-x  2 root root     4096 2011-12-23 16:09 openvpn\ndrwxr-xr-x  4 root root     4096 2011-12-23 17:02 vlc\ndrwxr-xr-x  4 root root     4096 2011-12-23 17:17 dconf\ndrwxr-xr-x  6 root root     4096 2011-12-23 17:17 gdm\ndrwxr-xr-x  3 root root     4096 2011-12-24 18:47 samba\ndrwxr-xr-x  2 root root     4096 2011-12-25 10:39 gtags\ndrwxr-xr-x  2 root root     4096 2012-01-03 16:01 cron.daily\ndrwxr-xr-x  7 root root     4096 2012-01-03 16:01 apache2\n-rw-r--r--  1 root root      664 2012-01-06 11:11 fstab.bak\n-rw-r--r--  1 root root      211 2012-01-10 09:40 modules\n-rw-------  1 root root      789 2012-01-11 17:49 gshadow-\n-rw-------  1 root root      951 2012-01-11 17:49 group-\n-rw-------  1 root root     1343 2012-01-11 17:49 shadow-\n-rw-------  1 root root     1863 2012-01-11 17:49 passwd-\n-rw-r-----  1 root shadow   1343 2012-01-11 17:49 shadow\n-rw-r--r--  1 root root     1878 2012-01-11 17:49 passwd\ndrwxr-xr-x  5 root root     4096 2012-01-11 17:49 logcheck\ndrwxr-xr-x  8 root root     4096 2012-01-11 17:49 apparmor.d\ndrwxr-xr-x  2 root root     4096 2012-01-11 17:49 init\ndrwxr-xr-x  3 root root     4096 2012-01-11 17:49 mysql\ndrwxr-xr-x  4 root root     4096 2012-01-13 12:47 dpkg\ndrwxr-xr-x  3 root root     4096 2012-01-13 12:47 bash_completion.d\ndrwxr-xr-x  2 root root     4096 2012-01-13 12:48 R\ndrwxr-xr-x 10 root root     4096 2012-01-16 16:08 X11\ndrwxr-xr-x  2 root root    12288 2012-01-21 19:44 alternatives\n-rw-r--r--  1 root root      773 2012-01-22 14:03 fstab\ndrwxr-xr-x  3 root root     4096 2012-01-27 10:53 java\ndrwxr-xr-x  3 root root     4096 2012-01-28 17:24 gimp\ndrwxr-xr-x  6 root root     4096 2012-01-28 17:27 apt\n-rw-r--r--  1 root root    23432 2012-01-28 17:35 mailcap\ndrwxr-xr-x  2 root root     4096 2012-01-28 17:35 logrotate.d\ndrwxr-xr-x  2 root root     4096 2012-01-28 17:35 default\ndrwxr-xr-x  2 root root     4096 2012-01-28 17:35 init.d\n-rw-r--r--  1 root root      972 2012-01-28 17:35 group\n-rw-r-----  1 root shadow    807 2012-01-28 17:35 gshadow\ndrwxr-xr-x  2 root root     4096 2012-01-28 17:35 pam.d\ndrwxr-xr-x  2 root root     4096 2012-01-28 17:35 rc6.d\ndrwxr-xr-x  2 root root     4096 2012-01-28 17:35 rc5.d\ndrwxr-xr-x  2 root root     4096 2012-01-28 17:35 rc4.d\ndrwxr-xr-x  2 root root     4096 2012-01-28 17:35 rc3.d\ndrwxr-xr-x  2 root root     4096 2012-01-28 17:35 rc2.d\ndrwxr-xr-x  2 root root     4096 2012-01-28 17:35 rc1.d\ndrwxr-xr-x  2 root root     4096 2012-01-28 17:35 rc0.d\n-rw-r--r--  1 root root   136548 2012-01-28 17:35 ld.so.cache\n-rw-r--r--  1 root root      697 2012-01-31 00:40 mtab\ndrwxr-xr-x  4 root lp       4096 2012-01-31 00:48 cups\n"
  },
  {
    "path": "examples/group-emails-example",
    "content": "root root.1@mydomain.com\nharel harel.1@mydomain.com\nroot root.2@mydomain.com\nroot root.3@mydomain.com\ndaemon daemon.1@otherdomain.com\ndip dip.1@otherdomain.com\ndip dip.2@otherdomain.com\nfuse fuse.A@mydomain.com\nfuse fuse.B@mydomain.com\nfuse fuse.C@mydomain.com\nlpa lpa.1@mydomain.com\nshadow forsaken.1@mydomain.com\n"
  },
  {
    "path": "mkdocs/README.md",
    "content": "\n# Generate web site\n\n# mkdocs folder under project root\n$ `cd mkdocs`\n\n* create a pyenv virtual environment \n\n$ `pip install -r requirements.txt`\n\n$ `./generate-web-site.sh` (static files will be generated into `./generated-site`)\n\n$ `git checkout gh-pages`\n\n$ `cd ../`   # back to project root\n\n$ `scp -r mkdocs/generated-site/* ./`\n\n$ `git add` all modified files\n\n* commit to git \n\n$ `git push origin gh-pages`\n\n"
  },
  {
    "path": "mkdocs/docs/about.md",
    "content": "# About\n\n### Linkedin: [Harel Ben Attia](https://www.linkedin.com/in/harelba/)\n\n### Twitter [@harelba](https://twitter.com/harelba)\n\n### Email [harelba@gmail.com](mailto:harelba@gmail.com)\n\n### Patreon [harelba](https://www.patreon.com/harelba)\nAll the money received is donated to the [Center for the Prevention and Treatment of Domestic Violence](https://www.gov.il/he/departments/bureaus/molsa-almab-ramla) in my hometown - Ramla, Israel.\n\n<a href=\"https://www.patreon.com/bePatron?u=65276930\" data-patreon-widget-type=\"become-patron-button\">Become a Patron!</a><script async src=\"https://c6.patreon.com/becomePatronButton.bundle.js\"></script>\n\n### Chinese translation [jinzhencheng@outlook.com](mailto:jinzhencheng@outlook.com)\n\n"
  },
  {
    "path": "mkdocs/docs/fsg9b9b1.txt",
    "content": ""
  },
  {
    "path": "mkdocs/docs/google0efeb4ff0a886e81.html",
    "content": "google-site-verification: google0efeb4ff0a886e81.html"
  },
  {
    "path": "mkdocs/docs/index.md",
    "content": "# q - Run SQL directly on CSV or TSV files\n\n[![GitHub Stars](https://img.shields.io/github/stars/harelba/q.svg?style=social&label=GitHub Stars&maxAge=600)](https://GitHub.com/harelba/q/stargazers/)\n[![GitHub forks](https://img.shields.io/github/forks/harelba/q.svg?style=social&label=GitHub Forks&maxAge=600)](https://GitHub.com/harelba/q/network/)\n\n## Overview\nq's purpose is to bring SQL expressive power to the Linux command line by providing easy access to text as actual data, and allowing direct access to multi-file sqlite3 databases.\n\n```bash\n\tq <flags> <sql-query>\n```\n\nq allows the following:\n\n* Performing SQL-like statements directly on tabular text data, auto-caching the data in order to accelerate additional querying on the same file\n\n```bash\n    # Simple query from a file, columns are named c1...cN\n    q \"select c1,c5 from myfile.csv\"\n\n    # -d '|' sets the input delimiter, -H says there's a header\n    q -d '|' -H \"select my_field from myfile.delimited-file-with-pipes\"\n\n    # -C readwrite writes a cache for the csv file\n    q -d , -H \"select my_field from myfile.csv\" -C readwrite\n\n    # -C read tells q to use the cache\n    q -d , -H \"select my_field from myfile.csv\" -C read\n\n    # Setting the default caching mode (`-C`) can be done by writing a `~/.qrc` file\n```\n\n* Performing SQL statements directly on multi-file sqlite3 databases, without having to merge them or load them into memory\n\n```bash\n    q \"select * from mydatabase.sqlite:::my_table_name\"\n\n        or\n\n    q \"select * from mydatabase.sqlite\"\n\n        if the database file contains only one table\n\n    # sqlite files are autodetected, no need for any special filename extension\n```\n\nThe following table shows the impact of using caching:\n\n|    Rows   | Columns | File Size | Query time without caching | Query time with caching | Speed Improvement |\n|:---------:|:-------:|:---------:|:--------------------------:|:-----------------------:|:-----------------:|\n| 5,000,000 |   100   |   4.8GB   |    4 minutes, 47 seconds   |       1.92 seconds      |        x149       |\n| 1,000,000 |   100   |   983MB   |        50.9 seconds        |      0.461 seconds      |        x110       |\n| 1,000,000 |    50   |   477MB   |        27.1 seconds        |      0.272 seconds      |        x99        |\n|  100,000  |   100   |    99MB   |         5.2 seconds        |      0.141 seconds      |        x36        |\n|  100,000  |    50   |    48MB   |         2.7 seconds        |      0.105 seconds      |        x25        |\n\nNotice that for the current version, caching is **not enabled** by default, since the caches take disk space. Use `-C readwrite` or `-C read` to enable it for a query, or add `caching_mode` to `.qrc` to set a new default.\n \nq treats ordinary files as database tables, and supports all SQL constructs, such as `WHERE`, `GROUP BY`, `JOIN`s, etc. It supports automatic column name and type detection, and provides full support for multiple character encodings.\n\nThe new features - autocaching, direct querying of sqlite database and the use of `~/.qrc` file are described in detail in [here](https://github.com/harelba/q/blob/master/QSQL-NOTES.md).\n\nDownload the tool using the links in the [installation](#installation) below and play with it.\n\n### Encodings\n|                                        |                                                 |\n|:--------------------------------------:|:-----------------------------------------------:|\n| 完全支持所有的字符编码                 | すべての文字エンコーディングを完全にサポート    |\n| 모든 문자 인코딩이 완벽하게 지원됩니다 | все кодировки символов полностью поддерживаются |\n\n**Non-english users:** q fully supports all types of encoding. Use `-e data-encoding` to set the input data encoding, `-Q query-encoding` to set the query encoding, and use `-E output-encoding` to set the output encoding. Sensible defaults are in place for all three parameters. Please contact me if you encounter any issues and I'd be glad to help.\n\n**Files with BOM:** Files which contain a BOM ([Byte Order Mark](https://en.wikipedia.org/wiki/Byte_order_mark)) are not properly supported inside python's csv module. q contains a workaround that allows reading UTF8 files which contain a BOM - Use `-e utf-8-sig` for this. I plan to separate the BOM handling from the encoding itself, which would allow to support BOMs for all encodings.\n\n## Installation\n\n| Format | Instructions | Comments |\n:---|:---|:---|\n|[OSX](https://github.com/harelba/q/releases/download/v3.1.6/macos-q)|Run `brew install harelba/q/q` in order to install q (moved it to its own tap), or download the standalone executable directly from the link on the left|A man page is available, just run `man q`||\n|[RPM Package](https://github.com/harelba/q/releases/download/v3.1.6/q-text-as-data-3.1.6.x86_64.rpm)| run `rpm -ivh <package-filename>` or `rpm -U <package-filename>` if you already have an older version of q.| A man page is available for this release. Just enter `man q`.|\n|[DEB Package](https://github.com/harelba/q/releases/download/v3.1.6/q-text-as-data-3.1.6-1.x86_64.deb)| Run `sudo dpkg -i <package-filename>`|A man page is available for this release. Just enter `man q`. Some installations don't install the man page properly for some reason. I'll fix this soon|\n|[Windows Installer](https://github.com/harelba/q/releases/download/v3.1.6/q-text-as-data-3.1.6.msi)|Run the installer executable and hit next next next... q.exe will be added to the PATH so you can access it everywhere.|Windows doesn't update the PATH retroactively for open windows, so you'll need to open a new `cmd`/`bash` window after the installation is done.|\n|[Source tar.gz](https://github.com/harelba/q/archive/refs/tags/v3.1.6.tar.gz)|Full source file tree for latest stable version. Note that q.py cannot be used directly anymore, as it requires python dependencies||\n|[Source zip](https://github.com/harelba/q/archive/refs/tags/v3.1.6.zip)|Full source file tree for the latest stable version. Note that q.py cannot be used directly anymore, as it requires python dependencies||\n\nI will add packages for additional Linux Distributions if there's demand for it. If you're interested in another Linux distribution, please ping me. It's relatively easy to add new ones with the new packaging flow.\n\nThe previous version `2.0.19` can be downloaded directly from [here](https://github.com/harelba/q/releases/tag/2.0.19). Please let me know if for some reason the new version is not suitable for your needs, and you're planning on using the previous one.\n\n## Requirements\nq is packaged as a compiled standalone-executable that has no dependencies, not even python itself. This was done by using the awesome [pyoxidizer](https://github.com/indygreg/PyOxidizer) project.\n\n\n## Examples\n\nThis section shows example flows that highlight the main features. For more basic examples, see [here](#getting-started-examples).\n\n### Basic Examples:\n\n```bash\n# Prepare some data\n$ seq 1 1000000 > myfile.csv\n\n# Query it\n$ q \"select sum(c1),count(*) from myfile.csv where c1 % 3 = 0\"\n166666833333 333333\n\n# Use q to query from stdin\n$ ps -ef | q -b -H \"SELECT UID, COUNT(*) cnt FROM - GROUP BY UID ORDER BY cnt DESC LIMIT 3\"\n501 288\n0   115\n270 17\n```\n\n### Auto-caching Examples\n\n```bash\n# (time command output has been shortened for berevity)\n\n# Prepare some data\n$ seq 1 1000000 > myfile.csv\n\n# Read from the resulting file \n$ time q \"select sum(c1),count(*) from myfile.csv\"\n500000500000 1000000\ntotal_time=4.108 seconds\n\n# Running with `-C readwrite` auto-creates a cache file if there is none. The cache filename would be myfile.csv.qsql. The query runs as usual\n$ time q \"select sum(c1),count(*) from myfile.csv\" -C readwrite\n500000500000 1000000\ntotal_time=4.057 seconds\n\n# Now run with `-C read`. The query will run from the cache file and not the original. As the file gets bigger, the difference will be much more noticable\n$ time q \"select sum(c1),count(*) from myfile.csv\" -C read\n500000500000 1000000\ntotal_time=0.229 seconds\n\n# Now let's try another query on that file. Notice the short query duration. The cache is being used for any query that uses this file, and queries on multiple files that contain caches will reuse the cache as well.\n$ time q \"select avg(c1) from myfile.csv\" -C read\n500000.5\ntotal_time=0.217 seconds\n\n# You can also query the qsql file directly, as it's just a standard sqlite3 DB file (see next section for q's support of reading directly from sqlite DBs)\n$ time q \"select sum(c1),count(*) from myfile.csv.qsql\"\n500000500000 1000000\ntotal_time=0.226 seconds\n\n# Now let's delete the original csv file (be careful when deleting original data)\n$ rm -vf myfile.csv\n\n# Running another query directly on the qsql file just works\n$ time q \"select sum(c1),count(*) from myfile.csv.qsql\"\n500000500000 1000000\ntotal_time=0.226 seconds\n\n# See the `.qrc` section below if you want to set the default `-C` (`--caching-mode`) to something other than `none` (the default)\n```\n\n### Direct sqlite Querying Examples\n\n```bash\n# Download example sqlite3 database from https://www.sqlitetutorial.net/sqlite-sample-database/ and unzip it. The resulting file will be chinook.db\n$ curl -L https://www.sqlitetutorial.net/wp-content/uploads/2018/03/chinook.zip | tar -xvf -\n\n# Now we can query the database directly, specifying the name of the table in the query (<db_name>:::<table_name>)\n$ q \"select count(*) from chinook.db:::albums\"\n347\n\n# Let's take the top 5 longest tracks of album id 34. The -b option just beautifies the output, and -O tells q to output the column names as headers\n$ q \"select * from chinook.db:::tracks where albumid = '34' order by milliseconds desc limit 5\" -b -O\nTrackId Name                       AlbumId MediaTypeId GenreId Composer Milliseconds Bytes    UnitPrice\n407     \"Só Tinha De Ser Com Você\" 34      1           7       Vários   389642       13085596 0.99\n398     \"Only A Dream In Rio\"      34      1           7       Vários   371356       12192989 0.99\n393     \"Tarde Em Itapoã\"          34      1           7       Vários   313704       10344491 0.99\n401     \"Momentos Que Marcam\"      34      1           7       Vários   280137       9313740  0.99\n391     \"Garota De Ipanema\"        34      1           7       Vários   279536       9141343  0.99\n\n# Let's now copy the chinook database to another file, as if it's just another different database\n$ cp chinook.db another_db.db\n\n# Now we can run a join query between the two databases. They could have been any two different databases, using the copy of chinook is just for simplicity\n# Let's get the top-5 longest albums, using albums from the first database and tracks from the second database. The track times are converted to seconds, and rounded to two digits after the decimal point.\n$ q -b -O \"select a.title,round(sum(t.milliseconds)/1000.0/60,2) total_album_time_seconds from chinook.db:::albums a left join another_database.db:::tracks t on (a.albumid = t.albumid) group by a.albumid order by total_album_time_seconds desc limit 5\"\nTitle                                      total_album_time_seconds\n\"Lost, Season 3\"                           1177.76\n\"Battlestar Galactica (Classic), Season 1\" 1170.23\n\"Lost, Season 1\"                           1080.92\n\"Lost, Season 2\"                           1054.83\n\"Heroes, Season 1\"                         996.34\n```\n\n### Analysis Examples\n\n```bash\n# Let's create a simple CSV file without a header. Make sure to copy only the three lines, press enter, and\n# then press Ctrl-D to exit so the file will be written.\n$ cat > some-data-without-header.csv\nharel,1,2\nben,3,4\nattia,5,6\n<Ctrl-D>\n\n# Let's run q on it with -A, to see the detected structure of the file. `-d ,` sets the delimiter to a comma\n$ q -d , \"select * from some-data-without-header.csv\" -A\nTable: /Users/harelben-attia/dev/harelba/q/some-data-without-header.csv\n  Sources:\n    source_type: file source: /Users/harelben-attia/dev/harelba/q/some-data-without-header.csv\n  Fields:\n    `c1` - text\n    `c2` - int\n    `c3` - int\n\n# Now let's create another simple CSV file, this time with a header (-H tells q to expect a header in the file)\n$ cat > some-data.csv\nplanet_id,name,diameter_km,length_of_day_hours\n1000,Earth,12756,24\n2000,Mars,6792,24.7\n3000,Jupiter,142984,9.9\n<Ctrl-D>\n\n# Let's run q with -A to see the analysis results.\n$ q -b -O -H -d , \"select * from some-data.csv\" -A\nTable: /Users/harelben-attia/dev/harelba/q/some-data.csv\n  Sources:\n    source_type: file source: /Users/harelben-attia/dev/harelba/q/some-data.csv\n  Fields:\n    `planet_id` - int\n    `name` - text\n    `diameter_km` - int\n    `length_of_day_hours` - real\n\n# Let's run it with `-C readwrite` so a cache will be created\n$ q -b -O -H -d , \"select * from some-data.csv\" -C readwrite\nplanet_id,name   ,diameter_km,length_of_day_hours\n1000     ,Earth  ,12756      ,24.0\n2000     ,Mars   ,6792       ,24.7\n3000     ,Jupiter,142984     ,9.9\n\n# Running another query that uses some-data.csv with -A will now show that a qsql exists for that file. The source-type \n# will be \"file-with-unused-qsql\". The qsql cache is not being used, since by default, q does not activate caching\n# so backward compatibility is maintained\n$ q -b -O -H -d , \"select * from some-data.csv\" -A\nTable: /Users/harelben-attia/dev/harelba/q/some-data.csv\n  Sources:\n    source_type: file-with-unused-qsql source: /Users/harelben-attia/dev/harelba/q/some-data.csv\n  Fields:\n    `planet_id` - int\n    `name` - text\n    `diameter_km` - int\n    `length_of_day_hours` - real\n\n# Now let's run another query, this time with `-C read`, telling q to use the qsql caches. This time source-type will \n# be \"qsql-file-with-original\", and the cache will be used when querying:\n$ q -b -O -H -d , \"select * from some-data.csv\" -A -C read\nTable: /Users/harelben-attia/dev/harelba/q/some-data.csv\n  Sources:\n    source_type: qsql-file-with-original source: /Users/harelben-attia/dev/harelba/q/some-data.csv.qsql\n  Fields:\n    `planet_id` - int\n    `name` - text\n    `diameter_km` - int\n    `length_of_day_hours` - real\n\n# Let's now read directly from the qsql file. Notice the change in the table name inside the query. `-C read` is not needed\n# here. The source-type will be \"qsql-file\" \n$ q -b -O -H -d , \"select * from some-data.csv.qsql\" -A\nTable: /Users/harelben-attia/dev/harelba/q/some-data.csv.qsql\n  Sources:\n    source_type: qsql-file source: /Users/harelben-attia/dev/harelba/q/some-data.csv.qsql\n  Fields:\n    `planet_id` - int\n    `name` - text\n    `diameter_km` - int\n    `length_of_day_hours` - real\n```\n\n## Usage\nQuery should be an SQL-like query which contains filenames instead of table names (or - for stdin). The query itself should be provided as one parameter to the tool (i.e. enclosed in quotes).\n\nAll sqlite3 SQL constructs are supported, including joins across files (use an alias for each table). Take a look at the [limitations](#limitations) section below for some rarely-used use cases which are not fully supported.\n\nq gets a full SQL query as a parameter. Remember to double-quote the query.\n\nHistorically, q supports multiple queries on the same command-line, loading each data file only once, even if it is used by multiple queries on the same q invocation. This is still supported. However, due to the new automatic-caching capabilities, this is not really required. Activate caching, and a cache file will be automatically created for each file. q Will use the cache behind the scenes in order to speed up queries. The speed up is extremely significant, so consider using caching for large files.\n\nThe following filename types are supported:\n\n* **Delimited-file filenames** - including relative/absolute paths. E.g. `./my_folder/my_file.csv` or `/var/tmp/my_file.csv`\n* **sqlite3 database filenames**\n    * **With Multiple Tables** - Add an additional `:::<table_name>` for accessing a specific table. For example `mydatabase.sqlite3:::users_table`.\n    * **With One Table Only** - Just specify the database filename, no need for a table name postfix. For example `my_single_table_database.sqlite`.\n* **`.qsql` cache files** - q can auto-generate cache files for delimited files, and they can be queried directly as a table, since they contain only one table, as they are essentially standard sqlite datbases\n\nUse `-H` to signify that the input contains a header line. Column names will be detected automatically in that case, and can be used in the query. If this option is not provided, columns will be named cX, starting with 1 (e.g. `q \"SELECT c3,c8 from ...\"`).\n\nUse `-d` to specify the input delimiter.\n\nColumn types are auto detected by the tool, no casting is needed. Note that there's a flag `--as-text` which forces all columns to be treated as text columns.\n\nPlease note that column names that include spaces need to be used in the query with back-ticks, as per the sqlite standard. Make sure to use single-quotes around the query, so bash/zsh won't interpret the backticks.\n\nQuery/Input/Output encodings are fully supported (and q tries to provide out-of-the-box usability in that area). Please use `-e`,`-E` and `-Q` to control encoding if needed.\n\nJOINs are supported and Subqueries are supported in the WHERE clause, but unfortunately not in the FROM clause for now. Use table aliases when performing JOINs.\n\nThe SQL syntax itself is sqlite's syntax. For details look at https://www.sqlite.org/lang.html or search the net for examples.\n\nNOTE: When using the `-O` output header option, use column name aliases if you want to control the output column names. For example, `q -O -H \"select count(*) cnt,sum(*) as mysum from -\"` would output `cnt` and `mysum` as the output header column names.\n\n``` bash\nOptions:\n  -h, --help            show this help message and exit\n  -v, --version         Print version\n  -V, --verbose         Print debug info in case of problems\n  -S SAVE_DB_TO_DISK_FILENAME, --save-db-to-disk=SAVE_DB_TO_DISK_FILENAME\n                        Save database to an sqlite database file\n  -C CACHING_MODE, --caching-mode=CACHING_MODE\n                        Choose the autocaching mode (none/read/readwrite).\n                        Autocaches files to disk db so further queries will be\n                        faster. Caching is done to a side-file with the same\n                        name of the table, but with an added extension .qsql\n  --dump-defaults       Dump all default values for parameters and exit. Can\n                        be used in order to make sure .qrc file content is\n                        being read properly.\n  --max-attached-sqlite-databases=MAX_ATTACHED_SQLITE_DATABASES\n                        Set the maximum number of concurrently-attached sqlite\n                        dbs. This is a compile time definition of sqlite. q's\n                        performance will slow down once this limit is reached\n                        for a query, since it will perform table copies in\n                        order to avoid that limit.\n  --overwrite-qsql=OVERWRITE_QSQL\n                        When used, qsql files (both caches and store-to-db)\n                        will be overwritten if they already exist. Use with\n                        care.\n\n  Input Data Options:\n    -H, --skip-header   Skip header row. This has been changed from earlier\n                        version - Only one header row is supported, and the\n                        header row is used for column naming\n    -d DELIMITER, --delimiter=DELIMITER\n                        Field delimiter. If none specified, then space is used\n                        as the delimiter.\n    -p, --pipe-delimited\n                        Same as -d '|'. Added for convenience and readability\n    -t, --tab-delimited\n                        Same as -d <tab>. Just a shorthand for handling\n                        standard tab delimited file You can use $'\\t' if you\n                        want (this is how Linux expects to provide tabs in the\n                        command line\n    -e ENCODING, --encoding=ENCODING\n                        Input file encoding. Defaults to UTF-8. set to none\n                        for not setting any encoding - faster, but at your own\n                        risk...\n    -z, --gzipped       Data is gzipped. Useful for reading from stdin. For\n                        files, .gz means automatic gunzipping\n    -A, --analyze-only  Analyze sample input and provide information about\n                        data types\n    -m MODE, --mode=MODE\n                        Data parsing mode. fluffy, relaxed and strict. In\n                        strict mode, the -c column-count parameter must be\n                        supplied as well\n    -c COLUMN_COUNT, --column-count=COLUMN_COUNT\n                        Specific column count when using relaxed or strict\n                        mode\n    -k, --keep-leading-whitespace\n                        Keep leading whitespace in values. Default behavior\n                        strips leading whitespace off values, in order to\n                        provide out-of-the-box usability for simple use cases.\n                        If you need to preserve whitespace, use this flag.\n    --disable-double-double-quoting\n                        Disable support for double double-quoting for escaping\n                        the double quote character. By default, you can use \"\"\n                        inside double quoted fields to escape double quotes.\n                        Mainly for backward compatibility.\n    --disable-escaped-double-quoting\n                        Disable support for escaped double-quoting for\n                        escaping the double quote character. By default, you\n                        can use \\\" inside double quoted fields to escape\n                        double quotes. Mainly for backward compatibility.\n    --as-text           Don't detect column types - All columns will be\n                        treated as text columns\n    -w INPUT_QUOTING_MODE, --input-quoting-mode=INPUT_QUOTING_MODE\n                        Input quoting mode. Possible values are all, minimal\n                        and none. Note the slightly misleading parameter name,\n                        and see the matching -W parameter for output quoting.\n    -M MAX_COLUMN_LENGTH_LIMIT, --max-column-length-limit=MAX_COLUMN_LENGTH_LIMIT\n                        Sets the maximum column length.\n    -U, --with-universal-newlines\n                        Expect universal newlines in the data. Limitation: -U\n                        works only with regular files for now, stdin or .gz\n                        files are not supported yet.\n\n  Output Options:\n    -D OUTPUT_DELIMITER, --output-delimiter=OUTPUT_DELIMITER\n                        Field delimiter for output. If none specified, then\n                        the -d delimiter is used if present, or space if no\n                        delimiter is specified\n    -P, --pipe-delimited-output\n                        Same as -D '|'. Added for convenience and readability.\n    -T, --tab-delimited-output\n                        Same as -D <tab>. Just a shorthand for outputting tab\n                        delimited output. You can use -D $'\\t' if you want.\n    -O, --output-header\n                        Output header line. Output column-names are determined\n                        from the query itself. Use column aliases in order to\n                        set your column names in the query. For example,\n                        'select name FirstName,value1/value2 MyCalculation\n                        from ...'. This can be used even if there was no\n                        header in the input.\n    -b, --beautify      Beautify output according to actual values. Might be\n                        slow...\n    -f FORMATTING, --formatting=FORMATTING\n                        Output-level formatting, in the format X=fmt,Y=fmt\n                        etc, where X,Y are output column numbers (e.g. 1 for\n                        first SELECT column etc.\n    -E OUTPUT_ENCODING, --output-encoding=OUTPUT_ENCODING\n                        Output encoding. Defaults to 'none', leading to\n                        selecting the system/terminal encoding\n    -W OUTPUT_QUOTING_MODE, --output-quoting-mode=OUTPUT_QUOTING_MODE\n                        Output quoting mode. Possible values are all, minimal,\n                        nonnumeric and none. Note the slightly misleading\n                        parameter name, and see the matching -w parameter for\n                        input quoting.\n    -L, --list-user-functions\n                        List all user functions\n\n  Query Related Options:\n    -q QUERY_FILENAME, --query-filename=QUERY_FILENAME\n                        Read query from the provided filename instead of the\n                        command line, possibly using the provided query\n                        encoding (using -Q).\n    -Q QUERY_ENCODING, --query-encoding=QUERY_ENCODING\n                        query text encoding. Experimental. Please send your\n                        feedback on this\n```\n\n### Setting the default values for parameters\nIt's possible to set default values for parameters which are used often by configuring them in the file `~/.qrc`.\n\nThe file format is as follows:\n```bash\n[options]\n<setting>=<default-value>\n```\n\nIt's possible to generate a default `.qrc` file by running `q --dump-defaults` and write the output into the `.qrc` file.\n\nOne valuable use-case for this could be setting the caching-mode to `read`. This will make q automatically use generated `.qsql` cache files if they exist. Whenever you want a cache file to be generated, just use `-C readwrite` and a `.qsql` file will be generated if it doesn't exist.\n\nHere's the content of the `~/.qrc` file for enabling cache reads by default:\n```bash\n[options]\ncaching_mode=read\n```\n  \n## Getting Started Examples\nThis section shows some more basic examples of simple SQL constructs. \n\nFor some more complex use-cases, see the [examples](#examples) at the beginning of the documentation.\n\nNOTES:\n\n* The `-H` flag in the examples below signifies that the file has a header row which is used for naming columns.\n* The `-t` flag is just a shortcut for saying that the file is a tab-separated file (any delimiter is supported - Use the `-d` flag).\n* Queries are given using upper case for clarity, but actual query keywords such as SELECT and WHERE are not really case sensitive.\n\nBasic Example List:\n\n* [Example 1 - COUNT DISTINCT values of specific field (uuid of clicks data)](#example-1)\n* [Example 2 - Filter numeric data, controlling ORDERing and LIMITing output](#example-2)\n* [Example 3 - Illustrate GROUP BY](#example-3)\n* [Example 4 - More complex GROUP BY (group by time expression)](#example-4)\n* [Example 5 - Read input from standard input](#example-5)\n* [Example 6 - Use column names from header row](#example-6)\n* [Example 7 - JOIN two files](#example-7)\n\n### Example 1\nPerform a COUNT DISTINCT values of specific field (uuid of clicks data).\n\n``` bash\nq -H -t \"SELECT COUNT(DISTINCT(uuid)) FROM ./clicks.csv\"\n```\nOutput\n``` bash\n229\n```\n### Example 2\nFilter numeric data, controlling ORDERing and LIMITing output\n\nNote that q understands that the column is numeric and filters according to its numeric value (real numeric value comparison, not string comparison).\n\n``` bash\nq -H -t \"SELECT request_id,score FROM ./clicks.csv WHERE score > 0.7 ORDER BY score DESC LIMIT 5\"\n```\nOutput:\n``` bash\n2cfab5ceca922a1a2179dc4687a3b26e    1.0\nf6de737b5aa2c46a3db3208413a54d64    0.986665809568\n766025d25479b95a224bd614141feee5    0.977105183282\n2c09058a1b82c6dbcf9dc463e73eddd2    0.703255121794\n```\n\n### Example 3\nIllustrate GROUP BY\n\n``` bash\nq -t -H \"SELECT hashed_source_machine,count(*) FROM ./clicks.csv GROUP BY hashed_source_machine\"\n```\nOutput:\n``` bash\n47d9087db433b9ba.domain.com 400000\n```\n\n### Example 4\nMore complex GROUP BY (group by time expression)\n\n``` bash\nq -t -H \"SELECT strftime('%H:%M',date_time) hour_and_minute,count(*) FROM ./clicks.csv GROUP BY hour_and_minute\"\n```\nOutput:\n``` bash\n07:00   138148\n07:01   140026\n07:02   121826\n```\n\n### Example 5\nRead input from standard input\n\nCalculates the total size per user/group in the /tmp subtree.\n\n``` bash\nsudo find /tmp -ls | q \"SELECT c5,c6,sum(c7)/1024.0/1024 AS total FROM - GROUP BY c5,c6 ORDER BY total desc\"\n```\nOutput:\n``` bash\nmapred hadoop   304.00390625\nroot   root     8.0431451797485\nsmith  smith    4.34389972687\n```\n\n### Example 6\nUse column names from header row\n\nCalculate the top 3 user ids with the largest number of owned processes, sorted in descending order.\n\nNote the usage of the autodetected column name UID in the query.\n\n``` bash\nps -ef | q -H \"SELECT UID,COUNT(*) cnt FROM - GROUP BY UID ORDER BY cnt DESC LIMIT 3\"\n```\nOutput:\n``` bash\nroot 152\nharel 119\navahi 2\n```\n\n### Example 7\nJOIN two files\n\nThe following command joins an ls output (exampledatafile) and a file containing rows of group-name,email (group-emails-example) and provides a row of filename,email for each of the emails of the group. For brevity of output, there is also a filter for a specific filename called ppp which is achieved using a WHERE clause.\n\n``` bash\nq \"SELECT myfiles.c8,emails.c2 FROM exampledatafile myfiles JOIN group-emails-example emails ON (myfiles.c4 = emails.c1) WHERE myfiles.c8 = 'ppp'\"\n```\nOutput:\n``` bash\nppp dip.1@otherdomain.com\nppp dip.2@otherdomain.com\n```\n\nYou can see that the ppp filename appears twice, each time matched to one of the emails of the group dip to which it belongs. Take a look at the files `exampledatafile` and `group-emails-example` for the data.\n\nColumn name detection is supported for JOIN scenarios as well. Just specify `-H` in the command line and make sure that the source files contain the header rows.\n\n## Implementation\nBehind the scenes q creates a \"virtual\" sqlite3 database that does not contain data of its own, but attaches to multiple other databases as follows:\n\n* When reading delimited files or data from `stdin`, it will analyze the data and construct an in-memory \"adhoc database\" that contains it. This adhoc database will be attached to the virtual database\n* When a delimited file has a `.qsql` cache, it will attach to that file directly, without having to read it into memory\n* When querying a standard sqlite3 file, it will be attached to the virtual database to it as well, without reading it into memory. sqlite3 files are auto-detected, no need for any special filename extension\n\nThe user query will be executed directly on the virtual database, using the attached databases.\n\nsqlite3 itself has a limit on the number of attached databases (usually 10). If that limit is reached, q will automatically attach databases until that limit is reached, and will load additional tables into the adhoc database's in-memory database.\n\nPlease make sure to read the [limitations](#limitations) section as well.\n\n## Development\n\n### Tests\nThe code includes a test suite runnable through `run-tests.sh`. By default, it uses the python source code for running the tests. However, it is possible to provide a path to an actual executable to the tests using the `Q_EXECUTABLE` env var. This is actually being used during the build and packaging process, in order to test the resulting binary.  \n\n## Limitations\nHere's the list of known limitations. Please contact me if you have a use case that needs any of those missing capabilities.\n\n* Common Table Expressions (CTE) are not supported for now. Will be implemented soon - See [here](https://github.com/harelba/q/issues/67) and [here](https://github.com/harelba/q/issues/124) for details.\n* `FROM <subquery>` is not supported\n* Spaces in file names are not supported. Use stdin for piping the data into q, or rename the file\n* Some rare cases of subqueries are not supported yet.\n* Queries with more than 10 different sqlite3 databases will load some data into memory\n* up to 500 tables are supported in a single query\n\n## Rationale\nHave you ever stared at a text file on the screen, hoping it would have been a database so you could ask anything you want about it? I had that feeling many times, and I've finally understood that it's not the database that I want. It's the language - SQL.\n\nSQL is a declarative language for data, and as such it allows me to define what I want without caring about how exactly it's done. This is the reason SQL is so powerful, because it treats data as data and not as bits and bytes (and chars).\n\nThe goal of this tool is to provide a bridge between the world of text files and of SQL.\n\n### Why aren't other Linux tools enough?\nThe standard Linux tools are amazing and I use them all the time, but the whole idea of Linux is mixing-and-matching the best tools for each part of job. This tool adds the declarative power of SQL to the Linux toolset, without loosing any of the other tools' benefits. In fact, I often use q together with other Linux tools, the same way I pipe awk/sed and grep together all the time.\n\nOne additional thing to note is that many Linux tools treat text as text and not as data. In that sense, you can look at q as a meta-tool which provides access to all the data-related tools that SQL provides (e.g. expressions, ordering, grouping, aggregation etc.).\n\n### Philosophy\nThis tool has been designed with general Linux/Unix design principles in mind. If you're interested in these general design principles, read this amazing [book](http://catb.org/~esr/writings/taoup/) and specifically [this part](http://catb.org/~esr/writings/taoup/html/ch01s06.html). If you believe that the way this tool works goes strongly against any of the principles, I would love to hear your view about it.\n\n## Future\n\n* Expose python as a python module - Planned as a goal after the new version `3.x` is out\n\n\n"
  },
  {
    "path": "mkdocs/docs/index_cn.md",
    "content": "# q - 直接在CSV或TSV文件上运行SQL\n\n[![GitHub Stars](https://img.shields.io/github/stars/harelba/q.svg?style=social&label=GitHub Stars&maxAge=600)](https://GitHub.com/harelba/q/stargazers/)\n[![GitHub forks](https://img.shields.io/github/forks/harelba/q.svg?style=social&label=GitHub Forks&maxAge=600)](https://GitHub.com/harelba/q/network/)\n\n\n## 概述\nq 是一个可以运行在 CSV / TSV 文件(或其他表格式的文本文件)上运行类SQL命令的命令行工具。\n\nq 将普通文本（如上述）作为数据库表，且支持所有的SQL语法如：WHERE、GROUP BY、各种JOIN等。此外，还拥有自动识别列名和列类型及广泛支持多种编码的特性。\n\n``` bash\nq \"SELECT COUNT(*) FROM ./clicks_file.csv WHERE c3 > 32.3\"\n```\n\n``` bash\nps -ef | q -H \"SELECT UID,COUNT(*) cnt FROM - GROUP BY UID ORDER BY cnt DESC LIMIT 3\"\n```\n\n查看[示例](#示例)或[安装](#安装)体验.\n\n|                                        |                                                 |\n|:--------------------------------------:|:-----------------------------------------------:|\n| 完全支持所有的字符编码                 | すべての文字エンコーディングを完全にサポート    |\n| 모든 문자 인코딩이 완벽하게 지원됩니다 | все кодировки символов полностью поддерживаются |\n\n\n**非英语用户:** q 完全支持所有类型的字符编码。 使用 `-e data-encoding` 设置输入编码; 使用 `-Q query-encoding` 设置查询编码; 使用 `-E output-encoding` 设置输出编码;\n如上三个参数均设有合理的默认值。<br/>\n\n> 如果遇到问题请与我联系，期待与你交流。\n\n**含有BOM的文件:** python的csv模块并不能很好的支持含有[Byte Order Mark](https://en.wikipedia.org/wiki/Byte_order_mark) 的文件。针对该种情况，使用 `-e utf-8-sig` 命令参数可读取包含BOM的UTF8编码文件。\n\n> 我们计划将BOM相关处理与编码'解耦', 这样就可以支持所有编码的BOM文件了。\n\n## 安装\n\n| 格式 | 说明 | 备注 |\n|:---|:---|:---|\n|[OSX](https://github.com/harelba/q/releases/download/2.0.19/q-x86_64-Darwin)|运行 `brew install q`| 该方式暂不支持MAN手册, 可以使用 `q --help` 查看帮助||\n|[RPM Package](https://github.com/harelba/q/releases/download/2.0.19/q-text-as-data-2.0.19-1.x86_64.rpm)| 运行 `rpm -ivh <package-filename>` 如果安装过旧版则运行 `rpm -U <package-filename>` | 该方式支持MAN手册，可运行`man q`查看|\n|[DEB Package](https://github.com/harelba/q/releases/download/2.0.19/q-text-as-data_2.0.19-2_amd64.deb)| 运行 `sudo dpkg -i <package-filename>`|该方式支持MAN手册，可运行`man q`查看|\n|[Windows Installer](https://github.com/harelba/q/releases/download/2.0.19/q-AMD64-Windows-installer.exe)|运行安装可执行文件，一直点击下一步、下一步... q.exe 将被添加至PATH，以便于随处运行|PATH更新后并不会即时生效，重新打开cmd命令窗口便可|\n|[tar.gz](https://github.com/harelba/q/archive/2.0.19.tar.gz)|最新稳定版的所有源码文件。提示，q.py 文件不能直接使用，因为它需要python依赖||\n|[zip](https://github.com/harelba/q/archive/2.0.19.zip)|最新稳定版的所有源码文件。提示，q.py 文件不能直接使用，因为它需要python依赖||\n\n**旧版本可以在这儿[下载](https://github.com/harelba/packages-for-q) 。按理说不会有人愿意用旧版本，要是你计划使用旧版，希望能与你交流。**\n\n## 须知\n从`2.0.9`版本开始，不需要任何外部依赖。Python(3.7)和其他所需的库包含在了安装文件中且与系统隔离。\n\n## 使用\n\n``` bash\nq <flags> \"<query>\"\n\n  最简单的执行语句：q \"SELECT * FROM myfile\" 该语句会输出文件内容\n```\n\nq 支持在表格式的文本上执行类SQL命令。它的初衷是为Linux命令行附加SQL的表达力且实现对文本数据的轻松访问。\n\n类SQL的查询将*文件名(或标准输入流)看作表名*。查询语句会作为命令输入的一个参数（使用引号包裹)，如果将多个文件看作一张表，可以这样写 `文件名1+文件名2....`或者使用通配符（比如：`my_files*.csv`)。\n\n使用 `-H` 表示输入内容中包含表头。该情况下列名会被自动识别，如果没有指定该参数，列名将会被以`cX`命名，`X`从1开始（比如: `q \"SELECT c3,c8 from ...\"`) 。\n\n使用 `-d` 声明输入的分隔符。\n\n列类型可由工具自动识别，无需强制转换。 提示，使用`--as-text` 可以强制将所有列类型转换为文本类型。\n\n依据sqlite规范，如果列名中含有空格，需要使用反引号 (即：`) 引起来。\n\n完全支持查询/输入/输出的编码设置（q 力争提供一种开箱即用的方法), 可以分别使用`-Q`,`-e` 和 `-E`来指定编码设置类型。\n\n支持所有的sqlite3 SQL方法，包括文件之间的 JOIN（可以为文件设置别名）操作。在下面的[限制](#限制)小节可以看到一些少有使用的、欠支持的说明。\n\n### 查询\n\nq 的每一个参数都是由双引号包裹的一条完整的SQL语句。所有的查询语句会依次执行，最终结果以标准输出流形式输出。 提示，在同一命令行中执行多条查询语句时，仅在执行第一条查询语句时需要耗时载入数据，其他查询语句即时执行。\n\n支持所有标准SQL语法，条件（WHERE 和 HAVING）、GROUP BY、ORDER BY等。\n\n在WHERE条件查询中，支持JOIN操作和子查询，但在FROM子句中并不支持。JOIN操作时，可以为文件起别名。\n\nSQL语法同sqlite的语法，详情见 https://www.sqlite.org/lang.html 或上网找一些示例。\n\n**注意**：\n\n* 支持所有类型的自动识别，无需强制转换或其他操作。\n  \n* 如果重命名输出列，则需要为列指定别名并使用 `-O` 声明。如: `q -O -H \"select count(*) cnt,sum(*) as mysum from -\"` 便会将`cnt`和`mysum`作为列名输出。\n\n### 指令\n\n``` bash\n使用:\n        q 支持在表格式的文本数据上执行类SQL查询。\n\n        它的初衷是为Linux命令行附加SQL的表达力且实现对文本数据的轻松访问。\n\n        基本操作是 q \"SQL查询语句\" 表名便是文件名（使用 - 从标注输入中读取数据）。若输入内容包含表头时，可以使用 -H 指定列名。若无表头，则列将会自动命名为 c1...cN。\n\n        列类型可被自动识别。可以使用 -A 命令查看每列的名称及其类型。\n\n        可以使用 -d (或 -t) 指定分隔符，使用 -D 指定输出分割符。\n\n        支持所有的sqlite3 SQL方法。\n\n        示例:\n            \n          例子1: ls -ltrd * | q \"select c1,count(1) from - group by c1\" \n          上例将会输出当前目录下，所有文件的权限表达式分组及每组数量。\n\n          例子2: seq 1 1000 | q \"select avg(c1),sum(c1) from -\" \n          上例将会输出1到1000的平均数与和数。\n          \n          例子3: sudo find /tmp -ls | q \"select c5,c6,sum(c7)/1024.0/1024 as total from - group by c5,c6 order by total desc\" \n          上例将会输出在/tmp目录下，相同'用户+组'的文件所占用的MB磁盘空间。\n\n          更多详情见 https://github.com/harelba/q/ 或查看帮助\n    \n选项：\n  -h, --help            显示此帮助信息并退出 \n  -v, --version         显示版本号\n  -V, --verbose         出现问题时显示调试信息\n  -S SAVE_DB_TO_DISK_FILENAME, --save-db-to-disk=SAVE_DB_TO_DISK_FILENAME\n                        将数据库保存为一个 sqlite 数据库文件\n  --save-db-to-disk-method=SAVE_DB_TO_DISK_METHOD\n                        保存数据库到磁盘的方法\n                        'standard' 不需要任何设置\n                        'fast'需要手动在python的安装目录下执行`pip install sqlitebck`\n                        打包的问题解决后，'fast'即被作为默认方式\n  数据相关的选项:\n  \n    -H, --skip-header   忽略表头，在早期的版本中已修改为：仅支持用于标明列名的一行表头\n    -d DELIMITER, --delimiter=DELIMITER\n                        列分隔符，若无特别指定，默认为空格符\n    -p, --pipe-delimited\n                        作用同 -d '|'，为了方便和可读性提供该参数\n    -t, --tab-delimited\n                        作用同 -d <tab>，这仅是一种简写，也可以在Linux命令行中使用$'\\t'\n    -e ENCODING, --encoding=ENCODING\n                        输入文件的编码，默认是UTF-8\n    -z, --gzipped       压缩数据，对于从输入流读取文件非常高效 .gz 是自动压缩后文件扩展名\n    -A, --analyze-only  简单分析：各列的数据类型\n    -m MODE, --mode=MODE\n                        数据解析模式: 松散, 宽松和严格。在严格模式下必须指定 -c \n                        --column-count 参数。\n    -c COLUMN_COUNT, --column-count=COLUMN_COUNT\n                        当使用宽松或严格模式时，用于指定列的数量\n    -k, --keep-leading-whitespace\n                        保留每列前的空格。为了使其开箱即用，默认去除了列前的空格\n                        如果有需要，可以指定该参数\n    --disable-double-double-quoting\n                        禁止一对双引号的转义。默认可以使用 \"\" 转义双引号\n                        主要为了向后兼容\n    --disable-escaped-double-quoting\n                        禁止转义双引号\n                        默认可以在双引号字段中使用 \\\" 进行转义\n                        主要为了向后兼容 \n    --as-text           不识别列类型（所有列被当作文本类型）\n    -w INPUT_QUOTING_MODE, --input-quoting-mode=INPUT_QUOTING_MODE\n                        输入内容的转义模式，可选值 all、minimal、none\n                        该参数稍有误导性，-W 指定输出内容的转义模式 \n    -M MAX_COLUMN_LENGTH_LIMIT, --max-column-length-limit=MAX_COLUMN_LENGTH_LIMIT\n                        设置列的最大长度\n    -U, --with-universal-newlines\n                        设置通用换行符\n                        -U 参数当前仅适用于常规文件，输入流或.gz类文件暂不支持\n\n  输出相关的选项:\n    -D OUTPUT_DELIMITER, --output-delimiter=OUTPUT_DELIMITER\n                        输出列间的分隔符\n                        若未指定，则与 -d 指定的分隔符相同；若均为指定，则默认为空格符\n    -P, --pipe-delimited-output\n                        同 -D '|' 为了方便和可读性提供该参数\n    -T, --tab-delimited-output\n                        同 -D <tab> 这仅是一种简写，也可以在Linux命令行中使用$'\\t' \n    -O, --output-header\n                        输出表头，输出的列名是由查询中指定的别名\n                        如: 'select name FirstName, value1/value2 MyCalculation\n                        from ...' 即使输入时未指定表头仍可使用该参数。\n    -b, --beautify      美化输出结果，可能较慢...\n    -f FORMATTING, --formatting=FORMATTING\n                        格式化输出列\n                        如格式X=fmt，Y=fmt等，上述中的X、Y是指第几列（如：1 表示 SELECT \n                        的第一列)\n    -E OUTPUT_ENCODING, --output-encoding=OUTPUT_ENCODING\n                        输出内容的编码，默认是 'none'，跟随系统或终端的编码\n    -W OUTPUT_QUOTING_MODE, --output-quoting-mode=OUTPUT_QUOTING_MODE\n                        输出内容的转义模式，可选值 all、minimal、none\n                        该参数稍有误导性，-w 指定输入内容的转义模式 \n    -L, --list-user-functions\n                        列出所有内置函数\n\n  查询相关的参数:\n    -q QUERY_FILENAME, --query-filename=QUERY_FILENAME\n                        指定文件名，由文件中读取查询语句。\n                        该操作常与查询编码（使用 -Q)一同使用\n    -Q QUERY_ENCODING, --query-encoding=QUERY_ENCODING\n                        查询编码(包含查询语句的文件编码)\n                        实验性参数，对该参数的意见可反馈\n```\n\n## 示例\n下述 `-H` 参数的例子，表示文件中含有表头时使用该参数。\n\n`-t` 参数是指定文件以 tab 作为分隔符的缩写（可以使用 `-d` 参数指定任意分隔符）。\n\n为了清楚起见，查询关键字均使用大写，实际上关键字(如 SELECT、WHERE等)对大小写并不敏感。\n\n示例目录:\n\n* [例1 - 统计指定列唯一值的数量](#1)\n* [例2 - 数值条件过滤、排序并限制输出数](#2)\n* [例3 - GROUP BY简单示例](#3)\n* [例4 - GROUP BY进阶示例 (以时间格式分组)](#4)\n* [例5 - 标准输入流作为输入](#5)\n* [例6 - 使用表头中列名](#6)\n* [例7 - JOIN 两个文件](#7)\n\n### 例1\n对指定字段（点击数据中的uuid）执行 COUNT DISTINCT \n\n``` bash\nq -H -t \"SELECT COUNT(DISTINCT(uuid)) FROM ./clicks.csv\"\n```\n输出:\n``` bash\n229\n```\n\n### 例2\n过滤数值数据、排序并限制输出数量\n\n注意：q 将其看作数值类型并对其进行数值过滤(数值比较而不是字符串比较)\n\n``` bash\nq -H -t \"SELECT request_id,score FROM ./clicks.csv WHERE score > 0.7 ORDER BY score DESC LIMIT 5\"\n```\n输出:\n``` bash\n2cfab5ceca922a1a2179dc4687a3b26e    1.0\nf6de737b5aa2c46a3db3208413a54d64    0.986665809568\n766025d25479b95a224bd614141feee5    0.977105183282\n2c09058a1b82c6dbcf9dc463e73eddd2    0.703255121794\n```\n\n### 例3\nGROUP BY 简单示例\n\n``` bash\nq -t -H \"SELECT hashed_source_machine,count(*) FROM ./clicks.csv GROUP BY hashed_source_machine\"\n```\n输出:\n``` bash\n47d9087db433b9ba.domain.com 400000\n```\n\n### 例4\nGROUP BY进阶示例 (以时间格式分组)\n\n``` bash\nq -t -H \"SELECT strftime('%H:%M',date_time) hour_and_minute,count(*) FROM ./clicks.csv GROUP BY hour_and_minute\"\n```\n输出:\n``` bash\n07:00   138148\n07:01   140026\n07:02   121826\n```\n\n### 例5\n标准输入流作为输入\n\n计算 /tmp 目录下各 user/group 的占用空间大小\n\n``` bash\nsudo find /tmp -ls | q \"SELECT c5,c6,sum(c7)/1024.0/1024 AS total FROM - GROUP BY c5,c6 ORDER BY total desc\"\n```\n输出:\n``` bash\nmapred hadoop   304.00390625\nroot   root     8.0431451797485\nsmith  smith    4.34389972687\n```\n\n### 例6\n使用表头中列名\n\n计算拥有进程数最多的前3位用户名及其数量\n\n注意: 该查询中自动识别了列名\n\n``` bash\nps -ef | q -H \"SELECT UID,COUNT(*) cnt FROM - GROUP BY UID ORDER BY cnt DESC LIMIT 3\"\n```\n输出:\n``` bash\nroot 152\nharel 119\navahi 2\n```\n\n### 例7\nJOIN 两个文件\n\n如下命令中JOIN一个ls命令输出内容文件（exampledatafile) 和一个包含group_name、email两列字段的文件（group-emails-example)，每一邮件组均包含filename、email列, 为了输出简便，使用WHERE条件过滤出名为 ppp 的文件\n\n``` bash\nq \"SELECT myfiles.c8,emails.c2 FROM exampledatafile myfiles JOIN group-emails-example emails ON (myfiles.c4 = emails.c1) WHERE myfiles.c8 = 'ppp'\"\n```\n输出:\n``` bash\nppp dip.1@otherdomain.com\nppp dip.2@otherdomain.com\n```\n可以看出 ppp 文件出现了两次，每次都匹配到了它所属的dip邮件组（如例中 dip.1@... /  dip2@...)，可以在 `exampledatafile` 和 `group-emails-example` 文件中查看数据。\n\nJOIN 的应用场景中也支持列名识别，在查询包含表头的文件时，只需指定 `-H` 参数即可。\n\n## 声明\n为了避免引用外部依赖，当前是使用由Python编写的内存数据库实现的。当前是支持 SELECT 语句及 各种JOIN （ 目前仅在 WHERE 语句中支持子查询)。\n若想对数据进一步分析，可以使用 `--save-db-to-disk` 参数，以将结果输出为 sqlite 数据库文件，然后使用 `sqlite3` 语句来执行查询操作。\n\n需要提示的是，当前并没有对数据量的大小进行检测和限制 - 也就是说，需要用户自己掌控文件大小。\n\n请务必阅读[限制](#限制)小节。\n\n## 开发\n\n### 测试\n源码中包含了测试用例，可以通过 `test/test-all` 来执行。若想要提交 PR的话，一定先确保其均执行成功。\n\n## 限制\n如下罗列了一些已知的限制，若你的使用场景中需要用到以下标明的限制，请联系我。\n\n* 不支持 `FROM <subquery>` \n* 不支持公用表表达式(CTE)\n* 不支持文件名中包含空格 (可以将文件以标准输入流的方式输入 q 或重命名文件)\n* 不支持较少用到的子查询\n\n## 原理\n你是否曾经盯着屏幕上的文本文件发呆，希望它要是数据库就好了，这样就可以找出自己想要的内容？我曾有过很多次，最终顿悟。我想要的不是数据库，而是 SQL。\n\nSQL 是一种面向数据声明的语言，它允许自定义数据内容而无需关心其执行过程。这也正是SQL强大之处，因为它对于数据'所见即所得'，而不是将数据看作字节码。\n\n本工具的目的是：在文本文件和SQL之间搭建一座桥梁。\n\n### 为什么其他Linux工具不能满足需求？\n传统的Linux工具库也很酷，我也经常使用它们， 但Linux的整体理念是为任一部分搭配最好的工具。本工具为传统Linux工具集新添了 SQL 族类工具，其他工具并不会失去本来优势。\n事实上，我也经常将 q 和其他Linux工具搭配使用，就如同使用管道将 awk/sed 和 grep 搭配使用一样。\n\n另外需要注意的是,许多Linux工具就将文本看作文本，而不是数据。从这个意义上来讲，可以将 q 看作提供了 SQL 功能（如：表达式、排序、分组、聚合等）的元工具。\n\n### 理念\n\n本工具的设计遵从了 Linux/Unix 的传统设计原则。若你对这些设计原则感兴趣，可以阅读 [这本书](http://catb.org/~esr/writings/taoup/) ，尤其是书中 [这部分](http://catb.org/~esr/writings/taoup/html/ch01s06.html)\n若你认为本工具工作方式与之背道而驰，愿洗耳恭听你的建议。\n\n## 展望\n\n* 主要方向：将其作为python的模块公开。 在公开之前，需要对处理标准输入流做一些内部API的完善。\n* 支持分布式以提高算力。\n\n\n\n"
  },
  {
    "path": "mkdocs/docs/js/google-analytics.js",
    "content": "// Monitor all download links in GA\n\nvar dlCnt = 0;\nvar tocCnt = 0;\n\nfunction GAizeDownloadLink(a) {\n        var url = a.href;\n        var x = url.indexOf(\"?\");\n        if (x != -1) {\n            url = url.substr(0, x);\n        }\n        var url_test = url.match(/^http.*(archive\\/|releases\\/)(?<path>.*)/);\n        if (url_test) {\n            a.event_action = url_test.groups.path;\n            console.log(\"Converting download link to be GA aware: \" + url + \" . download path is \" + a.event_action);\n            dlCnt = dlCnt + 1;\n            a.onclick = function() {\n                console.log(\"Sending GA event for link\" + url);\n                var that = this;\n                gtag('event','perform download', { 'event_category': 'Downloads', 'event_label': 'Download ' + this.event_action  , 'value': 1 });\n                setTimeout(function() {\n                    location.href = that.href;\n                }, 500);\n                return false;\n            };\n        }\n}\n\nfunction GAizeTOCLink(l) {\n\ttocCnt = tocCnt + 1;\n           l.onclick = function() {\n               url_test = l.href.match(/^https?:\\/\\/.+(#.*)$/i);\n               toc_name = url_test[1];\n                var that = this;\n                console.log(\"Sending GA event for toc link \" + this.href);\n                \n                gtag('event','navigate', { 'event_category': 'Navigation', 'event_label': 'go to ' + toc_name, 'value': 1 });\n                setTimeout(function() {\n                    location.href = that.href;\n                }, 250);\n                return false;\n            };\n\n}\n\nwindow.onload = function() {\n    var anchors = document.getElementsByTagName('a');\n    for (i = 0; i < anchors.length; i++) {\n      GAizeDownloadLink(anchors[i]);\n    }\n    var toc_links = document.querySelectorAll('div.md-sidebar[data-md-component=toc] a.md-nav__link');\n    for (i = 0; i < toc_links.length; i++) {\n      GAizeTOCLink(toc_links[i]);\n    }\n    console.log(\"Converted \" + dlCnt + \" download links and \" + tocCnt + \" TOC links to be GA aware\");\n}\n"
  },
  {
    "path": "mkdocs/docs/stylesheets/extra.css",
    "content": "\ndiv.md-content pre {\n  background-color: black;\n  color: #41FF00;\n}\n\n.md-typeset code pre {\n  background-color: black;\n  color: #41FF00;\n}\n\n.md-typeset p code {\n  color: rgba(0,0,0,.87);\n}\n\n.md-typeset code.bash {\n  color: #41FF00;\n}\n\n.md-typeset__scrollwrap {\n  text-align: center;\n}\n\n.md-typeset .headerlink {\n  opacity: 50%;\n}\n\narticle.md-content__inner.md-typeset>p {\n  text-align: left;\n}\n\n.md-nav__link[data-md-state=blur] {\n    color: rgba(0.3,0.5,0.4,.4)\n}\n\n.md-nav__link[data-md-state=current] {\n    font-weight: 700;\n}\n"
  },
  {
    "path": "mkdocs/generate-web-site.sh",
    "content": "#!/bin/bash\n\nmkdocs build -c -s -d ./generated-site\n"
  },
  {
    "path": "mkdocs/mkdocs.yml",
    "content": "site_name: q - Text as Data\nsite_url: https://harelba.github.io/q/\nrepo_url: https://github.com/harelba/q\nedit_uri: \"\"\nsite_description: Text as Data - q is a command line tool that allows direct execution of SQL-like queries on CSVs/TSVs (and any other tabular text files).\nsite_author: Harel Ben-Attia\ncopyright: 'Copyright &copy; 2012-2019 Harel Ben-Attia'\ngoogle_analytics: \n  - \"UA-48316355-1\"\n  - \"auto\"\nnav:\n    - Home: index.md\n    - 首页: index_cn.md\n    - About: about.md\ntheme: \n  name: material\n  language: 'en'\n  palette:\n    primary: purple\n    accent: amber\n  fonts:\n    text: 'Roboto'\n    code: 'Roboto Mono'\n  favicon: 'img/q-logo1.ico'\n  logo: 'img/q-logo1.ico'\n  custom_dir: 'theme'\nextra:\n  social:\n    - type: 'github'\n      link: 'https://github.com/harelba'\n    - type: 'twitter'\n      link: 'https://twitter.com/harelba'\n    - type: 'linkedin'\n      link: 'https://www.linkedin.com/in/harelba'\nextra_css:\n  - 'stylesheets/extra.css'\nextra_javascript:\n  - 'js/google-analytics.js'\nmarkdown_extensions:\n  - meta\n  - toc:\n      permalink: true\n  - tables\n  - fenced_code\n  - admonition\n    #  - codehilite\n\n\n\n"
  },
  {
    "path": "mkdocs/requirements.txt",
    "content": "Click==7.0\nDeprecated==1.2.7\nJinja2==2.10.3\nMarkdown==3.1.1\nMarkupSafe==1.1.1\nPyGithub==1.45\nPyJWT==1.7.1\nPyYAML==5.3\nPygments==2.5.2\ncertifi==2019.11.28\nchardet==3.0.4\nhtmlmin==0.1.12\nidna==2.8\njsmin==2.2.2\nlivereload==2.6.1\nmkdocs-bootstrap4==0.1.2\nmkdocs-bootswatch==1.0\nmkdocs-git-committers-plugin==0.1.8\nmkdocs-material==4.6.0\nmkdocs-minify-plugin==0.2.1\nmkdocs==1.0.4\npep562==1.0\npymdown-extensions==6.2.1\nrequests==2.22.0\nsix==1.14.0\ntornado==6.0.3\nurllib3==1.25.8\nwrapt==1.11.2\n"
  },
  {
    "path": "mkdocs/theme/main.html",
    "content": "{% extends \"base.html\" %}\n\n{% block analytics %}\n<!-- Global site tag (gtag.js) - Google Analytics -->\n{% set analytics = config.google_analytics %}\n<script async src=\"https://www.googletagmanager.com/gtag/js?id={{ analytics[0] }}\"></script>\n<script>\n  window.dataLayer = window.dataLayer || [];\n  function gtag(){dataLayer.push(arguments);}\n  gtag('js', new Date());\n\ngtag('config', '{{ analytics[0] }}');\ngtag('send','pageview');\n\n/* Register handler to log search on blur */\n  document.addEventListener(\"DOMContentLoaded\", () => {\n    if (document.forms.search) {\n      var query = document.forms.search.query\n      query.addEventListener(\"blur\", function() {\n        if (this.value) {\n          var path = document.location.pathname;\n          ga(\"send\", \"pageview\", path + \"?q=\" + this.value)\n        }\n      })\n    }\n  });\n</script>\n{% endblock %}\n"
  },
  {
    "path": "prepare-benchmark-env",
    "content": "#!/bin/bash\n\nset -e\n\neval \"$(pyenv init -)\"\neval \"$(pyenv virtualenv-init -)\"\n\nsource benchmark-config.sh\n\nif [ ! -f ./benchmark_data.tar.gz ];\nthen\n\techo benchmark data not found. downloading it\n  curl \"https://s3.amazonaws.com/harelba-q-public/benchmark_data.tar.gz\" -o ./benchmark_data.tar.gz\nelse\n  echo no need to download benchmark data\nfi\n\nif [ ! -d ./_benchmark_data ];\nthen\n\techo extracting benchmark data\n  tar xvfz benchmark_data.tar.gz\n  echo benchmark data is ready\nelse\n  echo no need to extract benchmark data\nfi\n\nfor ver in \"${BENCHMARK_PYTHON_VERSIONS[@]}\"\ndo\n  echo installing $ver \n  pyenv install -s $ver\n\n  venv_name=q-benchmark-$ver\n  echo create venv $venv_name\n  pyenv virtualenv -f $ver $venv_name\n  echo activate venv $venv_name\n  pyenv activate $venv_name\n  pyenv version\n  echo installing requirements $venv_name\n  pip install -r ./requirements.txt\n  echo deactivating $venv_name\n  pyenv deactivate    \ndone\n\n\n"
  },
  {
    "path": "pyoxidizer.bzl",
    "content": "# This file defines how PyOxidizer application building and packaging is\n# performed. See PyOxidizer's documentation at\n# https://pyoxidizer.readthedocs.io/en/stable/ for details of this\n# configuration file format.\n\nPYTHON_VERSION = VARS.get(\"PYTHON_VERSION\",\"3.8\")\nQ_VERSION = VARS.get(\"Q_VERSION\",\"0.0.1\")\n\n# Configuration files consist of functions which define build \"targets.\"\n# This function creates a Python executable and installs it in a destination\n# directory.\ndef make_exe():\n    dist = default_python_distribution(python_version=PYTHON_VERSION)\n\n    policy = dist.make_python_packaging_policy()\n    policy.set_resource_handling_mode(\"classify\")\n    policy.resources_location = \"in-memory\"\n    policy.resources_location_fallback = \"filesystem-relative:Lib\"\n    policy.allow_in_memory_shared_library_loading = False\n\n    python_config = dist.make_python_interpreter_config()\n\n    python_config.run_module = \"bin.q\"\n\n    exe = dist.to_python_executable(\n        name=\"q\",\n\n        packaging_policy=policy,\n\n        config=python_config,\n    )\n\n    exe.pip_install([\"wheel\"])\n\n    exe.add_python_resources(exe.pip_install([\"-r\", \"requirements.txt\"]))\n    exe.add_python_resources(exe.pip_install([\"-e\", \".\"]))\n\n    exe.add_python_resources(exe.read_package_root(\n        path=\"./\",\n        packages=[\"bin\"],\n    ))\n\n    return exe\n\ndef make_embedded_resources(exe):\n    return exe.to_embedded_resources()\n\ndef make_install(exe):\n    # Create an object that represents our installed application file layout.\n    files = FileManifest()\n\n    # Add the generated executable to our install layout in the root directory.\n    files.add_python_resource(\".\", exe)\n\n    return files\n\ndef make_msi(exe):\n    # See the full docs for more. But this will convert your Python executable\n    # into a `WiXMSIBuilder` Starlark type, which will be converted to a Windows\n    # .msi installer when it is built.\n    builder = exe.to_wix_msi_builder(\n        # Simple identifier of your app.\n        \"q\",\n        # The name of your application.\n        \"q-text-as-data\",\n        # The version of your application.\n        Q_VERSION,\n        # The author/manufacturer of your application.\n        \"Harel Ben-Attia\"\n    )\n    return builder\n\n\n# Dynamically enable automatic code signing.\ndef register_code_signers():\n    # You will need to run with `pyoxidizer build --var ENABLE_CODE_SIGNING 1` for\n    # this if block to be evaluated.\n    if not VARS.get(\"ENABLE_CODE_SIGNING\"):\n        return\n\n    # Use a code signing certificate in a .pfx/.p12 file, prompting the\n    # user for its path and password to open.\n    # pfx_path = prompt_input(\"path to code signing certificate file\")\n    # pfx_password = prompt_password(\n    #     \"password for code signing certificate file\",\n    #     confirm = True\n    # )\n    # signer = code_signer_from_pfx_file(pfx_path, pfx_password)\n\n    # Use a code signing certificate in the Windows certificate store, specified\n    # by its SHA-1 thumbprint. (This allows you to use YubiKeys and other\n    # hardware tokens if they speak to the Windows certificate APIs.)\n    # sha1_thumbprint = prompt_input(\n    #     \"SHA-1 thumbprint of code signing certificate in Windows store\"\n    # )\n    # signer = code_signer_from_windows_store_sha1_thumbprint(sha1_thumbprint)\n\n    # Choose a code signing certificate automatically from the Windows\n    # certificate store.\n    # signer = code_signer_from_windows_store_auto()\n\n    # Activate your signer so it gets called automatically.\n    # signer.activate()\n\n\n# Call our function to set up automatic code signers.\nregister_code_signers()\n\n# Tell PyOxidizer about the build targets defined above.\nregister_target(\"exe\", make_exe)\nregister_target(\"resources\", make_embedded_resources, depends=[\"exe\"], default_build_script=True)\nregister_target(\"install\", make_install, depends=[\"exe\"], default=True)\nregister_target(\"msi_installer\", make_msi, depends=[\"exe\"])\n\n# Resolve whatever targets the invoker of this configuration file is requesting\n# be resolved.\nresolve_targets()\n"
  },
  {
    "path": "pytest.ini",
    "content": "[pytest]\nmarkers =\n  benchmark: Benchmark tests\n"
  },
  {
    "path": "requirements.txt",
    "content": "six==1.11.0\nflake8==3.6.0\nsetuptools<45.0.0\n"
  },
  {
    "path": "run-benchmark",
    "content": "#!/bin/bash\n\n# Usage: ./run-benchmark.sh <benchmark-id> <q-executable>\nset -e\n\nget_abs_filename() {\n  # $1 : relative filename\n  echo \"$(cd \"$(dirname \"$1\")\" && pwd)/$(basename \"$1\")\"\n}\n\neval \"$(pyenv init -)\"\neval \"$(pyenv virtualenv-init -)\"\n\nif [ \"x$1\" == \"x\" ];\nthen\n\techo Benchmark id must be provided as a parameter\n  exit 1\nfi\nQ_BENCHMARK_ID=$1\nshift\n\nif [ \"x$1\" == \"x\" ];\nthen\n  EFFECTIVE_Q_EXECUTABLE=\"source-files-$(git rev-parse HEAD)\"\nelse\n  ABS_Q_EXECUTABLE=\"$(get_abs_filename $1)\"\n  export Q_EXECUTABLE=$ABS_Q_EXECUTABLE\n\tif [ ! -f $ABS_Q_EXECUTABLE ]\n\tthen\n\t\techo \"q executable must exist ($ABS_Q_EXECUTABLE)\"\n\t\texit 1\n\tfi\n  EFFECTIVE_Q_EXECUTABLE=\"${ABS_Q_EXECUTABLE//\\//__}\"\n  shift\nfi\n\necho \"Q executable to use is $EFFECTIVE_Q_EXECUTABLE\"\n\nPYTEST_OPTIONS=\"$@\"\necho \"pytest options are $PYTEST_OPTIONS\"\n\nmkdir -p ./test/benchmark-results\n\n# Must be provided to the benchmark code so it knows where to write the results to\nexport Q_BENCHMARK_RESULTS_FOLDER=\"./test/benchmark-results/${EFFECTIVE_Q_EXECUTABLE}/${Q_BENCHMARK_ID}/\"\necho Benchmark results folder is $Q_BENCHMARK_RESULTS_FOLDER\nmkdir -p $Q_BENCHMARK_RESULTS_FOLDER\n\nsource benchmark-config.sh\nLATEST_PYTHON_VERSION=${BENCHMARK_PYTHON_VERSIONS[${#BENCHMARK_PYTHON_VERSIONS[@]}-1]}\n\nALL_FILES=()\n\nfor ver in \"${BENCHMARK_PYTHON_VERSIONS[@]}\"\ndo\nvenv_name=q-benchmark-$ver\necho activating $venv_name\npyenv activate $venv_name\necho \"==== testing inside $venv_name ===\"\nif [[ -f $Q_BENCHMARK_RESULTS_FOLDER/${venv_name}.benchmark-results ]]\nthen\n\techo \"Results files for version $ver already exists skipping benchmark for this version\"\n\tcontinue\nfi\n\nexport Q_BENCHMARK_NAME=${venv_name}\nexport Q_BENCHMARK_ADDITIONAL_PARAMS=\"-C read\"\n\nQ_BENCHMARK_NAME=${venv_name}-with-caching Q_BENCHMARK_DATA_DIR=./_benchmark_data_with_qsql_caches pytest -m benchmark -k test_q_matrix -v -s $PYTEST_OPTIONS\nQ_BENCHMARK_NAME=${venv_name} Q_BENCHMARK_DATA_DIR=./_benchmark_data pytest -m benchmark -k test_q_matrix -v -s $PYTEST_OPTIONS\n\nRESULT_FILE=\"${Q_BENCHMARK_RESULTS_FOLDER}/$venv_name.benchmark-results\"\necho \"==== Done. Results are in $RESULT_FILE\"\nALL_FILES[${#ALL_FILES[@]}]=\"$RESULT_FILE\"\necho \"Deactivating\"\npyenv deactivate\ndone\n\nexit 0\n\npyenv activate q-benchmark-${LATEST_PYTHON_VERSION}\necho \"==== testing textql ===\"\nif [[ -f `ls $Q_BENCHMARK_RESULTS_FOLDER/textql*.benchmark-results` ]]\nthen\n\techo \"Results files for textql already exist. Skipping benchmark for textql\"\nelse\n\tpytest -m benchmark -k test_textql_matrix -v -s $PYTEST_OPTIONS\n\tRESULT_FILE=\"textql*.benchmark-results\"\n\tALL_FILES[${#ALL_FILES[@]}]=\"${Q_BENCHMARK_RESULTS_FOLDER}/$RESULT_FILE\"\n\techo \"Done. Results are in textql.benchmark-results\"\nfi\n\necho \"==== testing octosql ===\"\nif [[ -f $Q_BENCHMARK_RESULTS_FOLDER/octosql.benchmark-results ]]\nthen\n\techo \"Results files for octosql aready exist. Skipping benchmark for octosql\"\nelse\n\tpytest -m benchmark -k test_octosql_matrix -v -s $PYTEST_OPTIONS\n\tRESULT_FILE=\"octosql*.benchmark-results\"\n\tALL_FILES[${#ALL_FILES[@]}]=\"${Q_BENCHMARK_RESULTS_FOLDER}/$RESULT_FILE\"\n\techo \"Done. Results are in octosql.benchmark-results\"\nfi\n\nsummary_file=\"$Q_BENCHMARK_RESULTS_FOLDER/summary.benchmark-results\"\n\nrm -vf $summary_file\n\npaste ${ALL_FILES[*]} > $summary_file\necho \"Done. final results file is $summary_file\"\npyenv deactivate\n"
  },
  {
    "path": "run-coverage.sh",
    "content": "#!/bin/bash\n\nset -e\n\nrm -vf ./htmlcov/*\n\npytest -m \"not benchmark\" --cov --cov-report html \"$@\"\n\nfunction cleanup() {\n  kill %1\n}\n\n# TODO Fix\n\n# python -m http.server 8000 \n# open http://localhost:8000/htmlcov/\n\n\n"
  },
  {
    "path": "run-tests.sh",
    "content": "#!/bin/bash\n\npytest -m 'not benchmark' \"$@\"\n"
  },
  {
    "path": "setup.py",
    "content": "#!/usr/bin/env python\n\nfrom setuptools import setup\nimport setuptools\n\nq_version = '3.1.6'\n\nwith open(\"README.markdown\", \"r\", encoding=\"utf-8\") as fh:\n    long_description = fh.read()\n\nsetup(\n    name='q',\n    url='https://github.com/harelba/q',\n    license='LICENSE',\n    version=q_version,\n    author='Harel Ben-Attia',\n    description=\"Run SQL directly on CSV or TSV files\",\n    long_description=long_description,\n    long_description_content_type=\"text/markdown\",\n    author_email='harelba@gmail.com',\n    install_requires=[\n        'six==1.11.0'\n    ],\n    package_dir={\"\": \"bin\"},\n    packages=setuptools.find_packages(where=\"bin\"),\n    entry_points={\n        'console_scripts': [\n            'q = bin.q:run_standalone'\n        ]\n    }\n)\n"
  },
  {
    "path": "test/BENCHMARK.md",
    "content": "\n\nNOTE: *Please don't use or publish this benchmark data yet. See below for details*\n\n# Update\nq now provides inherent automatic caching capabilities, writing the CSV/TSV file to a `.qsql` file that sits beside the original file. After the cache exists (created as part of an initial query on a file), q knows to use it behind the scenes without changing the query itself, speeding up performance significantly.\n\nThe following table shows the impact of using caching in q:\n\n|    Rows   | Columns | File Size | Query time without caching | Query time with caching | Speed Improvement |\n|:---------:|:-------:|:---------:|:--------------------------:|:-----------------------:|:-----------------:|\n| 5,000,000 |   100   |   4.8GB   |    4 minutes, 47 seconds   |       1.92 seconds      |        x149       |\n| 1,000,000 |   100   |   983MB   |        50.9 seconds        |      0.461 seconds      |        x110       |\n| 1,000,000 |    50   |   477MB   |        27.1 seconds        |      0.272 seconds      |        x99        |\n|  100,000  |   100   |    99MB   |         5.2 seconds        |      0.141 seconds      |        x36        |\n|  100,000  |    50   |    48MB   |         2.7 seconds        |      0.105 seconds      |        x25        |\n\n\nEffectively, `.qsql` files are just standard sqlite3 files, with an additional metadata table that is used for detecting changes in the original delimited file. This means that any tool that can read sqlite3 files can use these files directly. The tradeoff is of course the additional disk usage that the cache files take.\n\nA good side-effect to this addition, is that q now knows how to directly query multi-file sqlite3 databases. This means that the user can query any sqlite3 database file, or the `.qsql` file itself, even when the original file doesn't exist anymore. For example:\n\n```bash\nq \"select a.*,b.* from my_file.csv.qsql a left join some-sqlite3-database:::some_table_name b on (a.id = b.id)\"\n```\n\nNOTE: In the current version, caching is not enabled by default - Use `-C readwrite` to enable reading+writing cache files, or `-C read` to just read any existing cache files. A `~/.qrc` file can be added in order to make these options the default if you want.\n\nThe benchmark results below reflect the peformance without the caching, e.g. directly reading the delimited files, parsing them and performing the query.\n\nI'll update benchmark results later on to provide cached results as well.\n\n# Overview\nThis just a preliminary benchmark, originally created for validating performance optimizations and suggestions from users, and analyzing q's move to python3. After writing it, I thought it might be interesting to test its speed against textql and octosql as well.\n\nThe results I'm getting are somewhat surprising, to the point of me questioning them a bit, so it would be great to validate the further before finalizing the benchmark results.\n\nThe most surprising results are as follows:\n* python3 vs python2 - A huge improvement (for large files, execution times with python 3 are around 40% of the times for python 2)\n* python3 vs textql (written in golang) - Seems that textql becomes slower than the python3 q version as the data sizes grows (both rows and columns)\n\nI would love to validate these results by having other people run the benchmark as well and send me their results. \n\nIf you're interested, follow the instructions and run the benchmark on your machine. After the benchmark is finished, send me the final results file, along with some details about your hardware, and i'll add it to the spreadsheet. <harelba@gmail.com>\n\nI've tried to make running the benchmark as seamless as possible, but there obviously might be errors/issues. Please contact me if you encounter any issue, or just open a ticket.\n\n# Benchmark\nThis is an initial version of the benchmark, along with some results. The following is compared:\n* q running on multiple python versions\n* textql 2.0.3\n* octosql v0.3.0\n\nThe specific python versions which are being tested are specified in `benchmark-config.sh`.\n\nThis is by no means a scientific benchmark, and it only focuses on the data loading time which is the only significant factor for comparison (e.g. the query itself is a very simple count query). Also, it does not try to provide any usability comparison between q and textql/octosql, an interesting topic on its own.\n\n## Methodology\nThe idea was to compare the time sensitivity of row and column count. \n\n* Row counts: 1,10,100,1000,10000,100000,1000000\n* Column counts: 1,5,10,20,50,100\n* Iterations for each combination: 10\n\nFile sizes:\n* 1M rows by 100 columns - 976MB (~1GB) - Largest file\n* 1M rows by 50 columns - 477MB\n\nThe benchmark executes simple `select count(*) from <file>` queries for each combination, calculating the mean and stddev of each set of iterations. The stddev is used in order to measure the validity of the results.\n\nThe graphs below only compare the means of the results, the standard deviations are written into the google sheet itself, and can be viewed there if needed.\n\nInstructions on how to run the benchmark are at the bottom section of this document, after the results section.\n\n## Hardware\nOSX Catalina on a 15\" Macbook Pro from Mid 2015, with 16GB of RAM, and an internal Flash Drive of 256GB.\n\n## Results\n(Results are automatically updated from the baseline tab in the google spreadsheet).\n\nDetailed results below.\n\nSummary:\n* All python 3 versions (3.6/3.7/3.8) provide similar results across all scales.\n* python 3.x provides significantly better results than python2. Improvement grows as the file size grows (20% improvement for small files, up to ~70% improvement for the largest file)\n* textql seems to provide faster results than q (py3) for smaller files, up to around 30MB of data. As the size grows further, it becomes slower than q, up to 80% (74 seconds vs 41 seconds) for the largest file\n* The larger the files, textql becomes slower than q-py3 (up to 80% more time than q for the largest file)\n* octosql is significantly slower than both q and textql, even for small files with a low number of rows and columns\n\n### Data for 1M rows\n\n#### Run time durations for 1M rows and different column counts:\n|   rows  \t| columns \t| File Size \t| python 2.7 \t| python 3.6 \t| python 3.7 \t| python 3.8 \t| textql \t| octosql \t|\n|:-------:\t|:-------:\t|:---------:\t|:----------:\t|:----------:\t|:----------:\t|:----------:\t|:------:\t|:-------:\t|\n| 1000000 \t|    1    \t|    17M    \t|    5.15    \t|    4.24    \t|    4.08    \t|    3.98    \t|  2.90  \t|  49.95  \t|\n| 1000000 \t|    5    \t|    37M    \t|    10.68   \t|    5.37    \t|    5.26    \t|    5.14    \t|  5.88  \t|  54.69  \t|\n| 1000000 \t|    10   \t|    89M    \t|    17.56   \t|    7.25    \t|    7.15    \t|    7.01    \t|  9.69  \t|  65.32  \t|\n| 1000000 \t|    20   \t|    192M   \t|    30.28   \t|    10.96   \t|    10.78   \t|    10.64   \t|  17.34 \t|  83.94  \t|\n| 1000000 \t|    50   \t|    477M   \t|    71.56   \t|    21.98   \t|    21.59   \t|    21.70   \t|  38.57 \t|  158.26 \t|\n| 1000000 \t|   100   \t|    986M   \t|   131.86   \t|    41.71   \t|    40.82   \t|    41.02   \t|  74.62 \t|  289.58 \t|\n\n#### Comparison between python 3.x and python 2 run times (1M rows):\n(>100% is slower than q-py2, <100% is faster than q-py2)\n\n|   rows    | columns \t| file size \t| q-py2 runtime \t| q-py3.6 vs q-py2 runtime \t| q-py3.7 vs q-py2 runtime \t| q-py3.8 vs q-py2 runtime \t|\n|:-------:\t|:-------:\t|:---------:\t|:-------------:\t|:------------------------:\t|:------------------------:\t|:------------------------:\t|\n| 1000000 \t|    1    \t|    17M    \t|    100.00%    \t|          82.34%          \t|          79.34%          \t|          77.36%          \t|\n| 1000000 \t|    5    \t|    37M    \t|    100.00%    \t|          50.25%          \t|          49.22%          \t|          48.08%          \t|\n| 1000000 \t|    10   \t|    89M    \t|    100.00%    \t|          41.30%          \t|          40.69%          \t|          39.93%          \t|\n| 1000000 \t|    20   \t|    192M   \t|    100.00%    \t|          36.18%          \t|          35.59%          \t|          35.14%          \t|\n| 1000000 \t|    50   \t|    477M   \t|    100.00%    \t|          30.71%          \t|          30.17%          \t|          30.32%          \t|\n| 1000000 \t|   100   \t|    986M   \t|    100.00%    \t|          31.63%          \t|          30.96%          \t|          31.11%          \t|\n\n#### textql and octosql comparison against q-py3 run time (1M rows):\n(>100% is slower than q-py3, <100% is faster than q-py3)\n\n|   rows  \t| columns \t| file size \t| avg q-py3 runtime \t| textql vs q-py3 runtime \t| octosql vs q-py3 runtime \t|\n|:-------:\t|:-------:\t|:---------:\t|:-----------------:\t|:-----------------------:\t|:------------------------:\t|\n| 1000000 \t|    1    \t|    17M    \t|      100.00%      \t|          70.67%         \t|         1217.76%         \t|\n| 1000000 \t|    5    \t|    37M    \t|      100.00%      \t|         111.86%         \t|         1040.70%         \t|\n| 1000000 \t|    10   \t|    89M    \t|      100.00%      \t|         135.80%         \t|          915.28%         \t|\n| 1000000 \t|    20   \t|    192M   \t|      100.00%      \t|         160.67%         \t|          777.92%         \t|\n| 1000000 \t|    50   \t|    477M   \t|      100.00%      \t|         177.26%         \t|          727.40%         \t|\n| 1000000 \t|   100   \t|    986M   \t|      100.00%      \t|         181.19%         \t|          703.15%         \t|\n\n### Sensitivity to column count \nBased on a the largest file size of 1,000,000 rows.\n\n![Sensitivity to column count](https://docs.google.com/spreadsheets/d/e/2PACX-1vQy9Zm4I322Tdf5uoiFFJx6Oi3Z4AMq7He3fUUtsEQVQIdTGfWgjxFD6k8PAy9wBjvFkqaG26oBgNTP/pubchart?oid=1585602598&format=image)\n\n### Sensitivity to line count (per column count)\n\n#### 1 Column Table\n![1 column table](https://docs.google.com/spreadsheets/d/e/2PACX-1vQy9Zm4I322Tdf5uoiFFJx6Oi3Z4AMq7He3fUUtsEQVQIdTGfWgjxFD6k8PAy9wBjvFkqaG26oBgNTP/pubchart?oid=1119350798&format=image)\n\n#### 5 Column Table\n![5 column table](https://docs.google.com/spreadsheets/d/e/2PACX-1vQy9Zm4I322Tdf5uoiFFJx6Oi3Z4AMq7He3fUUtsEQVQIdTGfWgjxFD6k8PAy9wBjvFkqaG26oBgNTP/pubchart?oid=599223098&format=image)\n\n#### 10 Column Table\n![10 column table](https://docs.google.com/spreadsheets/d/e/2PACX-1vQy9Zm4I322Tdf5uoiFFJx6Oi3Z4AMq7He3fUUtsEQVQIdTGfWgjxFD6k8PAy9wBjvFkqaG26oBgNTP/pubchart?oid=82695414&format=image)\n\n#### 20 Column Table\n![20 column table](https://docs.google.com/spreadsheets/d/e/2PACX-1vQy9Zm4I322Tdf5uoiFFJx6Oi3Z4AMq7He3fUUtsEQVQIdTGfWgjxFD6k8PAy9wBjvFkqaG26oBgNTP/pubchart?oid=1573199483&format=image)\n\n#### 50 Column Table\n![50 column table](https://docs.google.com/spreadsheets/d/e/2PACX-1vQy9Zm4I322Tdf5uoiFFJx6Oi3Z4AMq7He3fUUtsEQVQIdTGfWgjxFD6k8PAy9wBjvFkqaG26oBgNTP/pubchart?oid=448568670&format=image)\n\n#### 100 Column Table\n![100 column table](https://docs.google.com/spreadsheets/d/e/2PACX-1vQy9Zm4I322Tdf5uoiFFJx6Oi3Z4AMq7He3fUUtsEQVQIdTGfWgjxFD6k8PAy9wBjvFkqaG26oBgNTP/pubchart?oid=2101488258&format=image)\n\n## Running the benchmark\nPlease note that the initial run generates large files, so you'd need more than 3GB of free space available. All the generated files reside in the `_benchmark_data/` folder.\n\nPart of the preparation flow will download the benchmark data as needed.\n\n### Preparations\n* Prerequisites:\n  * pyenv installed\n  * pyenv-virtualenv installed\n  * [`textql`](https://github.com/dinedal/textql#install)\n  * [`octosql`](https://github.com/cube2222/octosql#installation)\n\nRun `./prepare-benchmark-env`\n\n### Execution\nRun `./run-benchmark <benchmark-id>`.\n\nBenchmark output files will be written to `./benchmark-results/<q-executable>/<benchmark-id>/`.\n\n* `benchmark-id` is the id you wanna give the benchmark.\n* `q-executable` is the name of the q executable being used for the benchmark. If none has been provided through Q_EXECUTABLE, then the value will be the last commit hash. Note that there is no checking of whether the working tree is clean. \n\nThe summary of benchmark will be written to `./benchmark-results/<benchmark-id>/summary.benchmark-results``\n\nBy default, the benchmark will use the source python files inside the project. If you wanna run it on one of the standalone binary executable, the set Q_EXECUTABLE to the full path of the q binary.\n\nFor anyone helping with running the benchmark, don't use this parameter for now, just test against a clean checkout of the code using `./run-benchmark <benchmark-id>`.\n\n## Benchmark Development info\n### Running against the standalone binary\n* `./run-benchmark` can accept a second parameter with the q executable. If it gets this parameter, it will use this path for running q. This provides a way to test the standalone q binaries in the new packaging format. When this parameter does not exist, the benchmark is executed directly from the source code.\n\n### Updating the benchmark markdown document file\nThe results should reside in the following [google sheet](https://docs.google.com/spreadsheets/d/1Ljr8YIJwUQ5F4wr6ATga5Aajpu1CvQp1pe52KGrLkbY/edit?usp=sharing). \n\nadd a new tab to the google sheet, and paste the content of `summary.benchmark-results` to the new sheet.\n\n"
  },
  {
    "path": "test/__init__.py",
    "content": ""
  },
  {
    "path": "test/benchmark-results/source-files-1443b7418b46594ad256abd9db4a7671cb251e6a/2020-09-17-v2.0.17/octosql_v0.3.0.benchmark-results",
    "content": "lines\tcolumns\toctosql_v0.3.0_mean\toctosql_v0.3.0_stddev\n1\t1\t0.582091641426\t0.0235290239617\n10\t1\t0.596219730377\t0.0320124029461\n100\t1\t0.575977492332\t0.0199296245316\n1000\t1\t0.56785056591\t0.00846389017466\n10000\t1\t1.1466334343\t0.00760108698846\n100000\t1\t5.49565172195\t0.131791932977\n1000000\t1\t49.9513648033\t0.443430523063\nlines\tcolumns\toctosql_v0.3.0_mean\toctosql_v0.3.0_stddev\n1\t5\t0.582160949707\t0.0274409391571\n10\t5\t0.57046456337\t0.0199413000359\n100\t5\t0.585747480392\t0.0372543971623\n1000\t5\t0.572268772125\t0.00384300349763\n10000\t5\t1.15530762672\t0.0117990775856\n100000\t5\t6.10629923344\t0.146711842919\n1000000\t5\t54.6851765394\t0.315486399525\nlines\tcolumns\toctosql_v0.3.0_mean\toctosql_v0.3.0_stddev\n1\t10\t0.586222410202\t0.0232479065914\n10\t10\t0.59000480175\t0.0186508192447\n100\t10\t0.581873703003\t0.0331332482772\n1000\t10\t0.569027900696\t0.0103675493106\n10000\t10\t1.40067322254\t0.00583352224401\n100000\t10\t7.30705575943\t0.0165839217599\n1000000\t10\t65.3242264032\t0.512552576414\nlines\tcolumns\toctosql_v0.3.0_mean\toctosql_v0.3.0_stddev\n1\t20\t0.571048212051\t0.0166919396871\n10\t20\t0.594776701927\t0.0368900941023\n100\t20\t0.561370825768\t0.00907051791451\n1000\t20\t0.577527880669\t0.00983965108957\n10000\t20\t1.90710241795\t0.00757011452155\n100000\t20\t9.8267291069\t0.127844155326\n1000000\t20\t83.9448960066\t0.46121344046\nlines\tcolumns\toctosql_v0.3.0_mean\toctosql_v0.3.0_stddev\n1\t50\t0.572030115128\t0.0253648479103\n10\t50\t0.56993534565\t0.0230474303306\n100\t50\t0.563336873055\t0.00964411866903\n1000\t50\t0.826378440857\t0.00941629472813\n10000\t50\t3.27872717381\t0.126592845956\n100000\t50\t17.890055728\t0.116794666005\n1000000\t50\t158.262442636\t0.826290454446\nlines\tcolumns\toctosql_v0.3.0_mean\toctosql_v0.3.0_stddev\n1\t100\t0.569358110428\t0.0279801762531\n10\t100\t0.580981063843\t0.0272341107532\n100\t100\t0.559471726418\t0.00668155858429\n1000\t100\t1.08161640167\t0.00698594638512\n10000\t100\t5.67823712826\t0.0123398407167\n100000\t100\t32.2797194242\t0.315508270241\n1000000\t100\t289.582628798\t0.929455236817\n"
  },
  {
    "path": "test/benchmark-results/source-files-1443b7418b46594ad256abd9db4a7671cb251e6a/2020-09-17-v2.0.17/q-benchmark-2.7.18.benchmark-results",
    "content": "lines\tcolumns\tq-benchmark-2.7.18_mean\tq-benchmark-2.7.18_stddev\n1\t1\t0.106449890137\t0.002010027753\n10\t1\t0.106737875938\t0.00224112203891\n100\t1\t0.107839012146\t0.00102954061006\n1000\t1\t0.113026666641\t0.00147361890226\n10000\t1\t0.160376381874\t0.00569766179806\n100000\t1\t0.608236479759\t0.00604026519608\n1000000\t1\t5.14807910919\t0.0584474028762\nlines\tcolumns\tq-benchmark-2.7.18_mean\tq-benchmark-2.7.18_stddev\n1\t5\t0.106719517708\t0.00236752032369\n10\t5\t0.107823801041\t0.00238873169438\n100\t5\t0.109785079956\t0.0013047675259\n1000\t5\t0.120395207405\t0.00207224422629\n10000\t5\t0.21783041954\t0.00522254475716\n100000\t5\t1.17115747929\t0.0221394865225\n1000000\t5\t10.6830974817\t0.339822977934\nlines\tcolumns\tq-benchmark-2.7.18_mean\tq-benchmark-2.7.18_stddev\n1\t10\t0.104981088638\t0.00166552032929\n10\t10\t0.108320140839\t0.00204034349199\n100\t10\t0.112528729439\t0.00168376477305\n1000\t10\t0.13019015789\t0.00253773120965\n10000\t10\t0.284891676903\t0.00384009140782\n100000\t10\t1.84725661278\t0.00860738744089\n1000000\t10\t17.5610994339\t0.228322442172\nlines\tcolumns\tq-benchmark-2.7.18_mean\tq-benchmark-2.7.18_stddev\n1\t20\t0.106477689743\t0.00254429925697\n10\t20\t0.108580899239\t0.00173704653824\n100\t20\t0.118750286102\t0.00247623639866\n1000\t20\t0.146431708336\t0.00249685551944\n10000\t20\t0.419492387772\t0.00248210434668\n100000\t20\t3.15847921371\t0.0550301268026\n1000000\t20\t30.279082489\t0.124978814506\nlines\tcolumns\tq-benchmark-2.7.18_mean\tq-benchmark-2.7.18_stddev\n1\t50\t0.105411934853\t0.00171651054128\n10\t50\t0.109102797508\t0.00111620290512\n100\t50\t0.135682177544\t0.00196166766665\n1000\t50\t0.198261427879\t0.00396172489054\n10000\t50\t0.821499919891\t0.0111642692132\n100000\t50\t7.05980975628\t0.121182371277\n1000000\t50\t71.5645889759\t5.02009516291\nlines\tcolumns\tq-benchmark-2.7.18_mean\tq-benchmark-2.7.18_stddev\n1\t100\t0.10662381649\t0.00193146624495\n10\t100\t0.110662698746\t0.00171461379583\n100\t100\t0.163547992706\t0.00166570196628\n1000\t100\t0.280023741722\t0.00337543024145\n10000\t100\t1.46053376198\t0.0221691284465\n100000\t100\t13.2369835854\t0.309375896258\n1000000\t100\t131.864977288\t1.22415449691\n"
  },
  {
    "path": "test/benchmark-results/source-files-1443b7418b46594ad256abd9db4a7671cb251e6a/2020-09-17-v2.0.17/q-benchmark-3.6.4.benchmark-results",
    "content": "lines\tcolumns\tq-benchmark-3.6.4_mean\tq-benchmark-3.6.4_stddev\n1\t1\t0.10342762470245362\t0.0017673875851759295\n10\t1\t0.10239293575286865\t0.0012505611685910795\n100\t1\t0.10317318439483643\t0.0010581783881541751\n1000\t1\t0.10687050819396973\t0.0014050135772919004\n10000\t1\t0.1447664737701416\t0.001841256227287192\n100000\t1\t0.5162809371948243\t0.006962985088492867\n1000000\t1\t4.238853335380554\t0.04834401143632507\nlines\tcolumns\tq-benchmark-3.6.4_mean\tq-benchmark-3.6.4_stddev\n1\t5\t0.10211825370788574\t0.0022568191323651568\n10\t5\t0.1025341272354126\t0.0016446470901070106\n100\t5\t0.1053577184677124\t0.0015298114223855884\n1000\t5\t0.10980842113494874\t0.002536098780902228\n10000\t5\t0.1590113162994385\t0.003123074098301634\n100000\t5\t0.6348223447799682\t0.0082691507829872\n1000000\t5\t5.368562030792236\t0.11628913334105236\nlines\tcolumns\tq-benchmark-3.6.4_mean\tq-benchmark-3.6.4_stddev\n1\t10\t0.10251858234405517\t0.0015963869535345293\n10\t10\t0.10278875827789306\t0.0009920577082124496\n100\t10\t0.10715732574462891\t0.002033320000941064\n1000\t10\t0.11389360427856446\t0.0023603847702423973\n10000\t10\t0.17806434631347656\t0.001114054252191835\n100000\t10\t0.8252989768981933\t0.0037080843359275904\n1000000\t10\t7.252838873863221\t0.029052130546213153\nlines\tcolumns\tq-benchmark-3.6.4_mean\tq-benchmark-3.6.4_stddev\n1\t20\t0.10367965698242188\t0.003661761341842434\n10\t20\t0.10489590167999267\t0.001977141196109372\n100\t20\t0.11108210086822509\t0.0014801173497056886\n1000\t20\t0.12110791206359864\t0.001648524669420912\n10000\t20\t0.2178968906402588\t0.0019298316207276716\n100000\t20\t1.1962245225906372\t0.010541407803235559\n1000000\t20\t10.956057572364807\t0.12677108174061705\nlines\tcolumns\tq-benchmark-3.6.4_mean\tq-benchmark-3.6.4_stddev\n1\t50\t0.10458300113677979\t0.0016367630302744722\n10\t50\t0.10616152286529541\t0.002345135740908088\n100\t50\t0.12375867366790771\t0.00238414904864133\n1000\t50\t0.14462883472442628\t0.0022428030896492978\n10000\t50\t0.34488487243652344\t0.004867441221052092\n100000\t50\t2.3394312858581543\t0.02263239858944125\n1000000\t50\t21.979821610450745\t0.09080404939303836\nlines\tcolumns\tq-benchmark-3.6.4_mean\tq-benchmark-3.6.4_stddev\n1\t100\t0.10372309684753418\t0.0010299126833031144\n10\t100\t0.10784556865692138\t0.0016557634029464607\n100\t100\t0.14526791572570802\t0.0028194506905186724\n1000\t100\t0.18315494060516357\t0.0023585311962114673\n10000\t100\t0.5586131334304809\t0.004808492789681402\n100000\t100\t4.287398314476013\t0.00957500108409644\n1000000\t100\t41.706851434707644\t0.4161526076289425\n"
  },
  {
    "path": "test/benchmark-results/source-files-1443b7418b46594ad256abd9db4a7671cb251e6a/2020-09-17-v2.0.17/q-benchmark-3.7.9.benchmark-results",
    "content": "lines\tcolumns\tq-benchmark-3.7.9_mean\tq-benchmark-3.7.9_stddev\n1\t1\t0.08099310398101807\t0.001417385651688644\n10\t1\t0.0822291374206543\t0.0014809900020001858\n100\t1\t0.08169686794281006\t0.002108157069167563\n1000\t1\t0.08690853118896484\t0.0012595326919263487\n10000\t1\t0.12215542793273926\t0.0020152625320395434\n100000\t1\t0.4825761795043945\t0.0050418000028856335\n1000000\t1\t4.084399747848511\t0.027731958079814215\nlines\tcolumns\tq-benchmark-3.7.9_mean\tq-benchmark-3.7.9_stddev\n1\t5\t0.0817826271057129\t0.002665533758836163\n10\t5\t0.08261749744415284\t0.0019205430658525572\n100\t5\t0.08472237586975098\t0.002571239449841039\n1000\t5\t0.08973510265350342\t0.002323797583077552\n10000\t5\t0.13746986389160157\t0.001964971666036654\n100000\t5\t0.60649254322052\t0.007131635266871318\n1000000\t5\t5.2585612535476685\t0.05661789407928516\nlines\tcolumns\tq-benchmark-3.7.9_mean\tq-benchmark-3.7.9_stddev\n1\t10\t0.08112843036651611\t0.002251300165899426\n10\t10\t0.08175232410430908\t0.0014557171018568637\n100\t10\t0.08572309017181397\t0.0019643550214810675\n1000\t10\t0.09268453121185302\t0.001816414236580489\n10000\t10\t0.15538835525512695\t0.0024978076091814994\n100000\t10\t0.7879442930221557\t0.009412516078916211\n1000000\t10\t7.146207928657532\t0.06659760176757985\nlines\tcolumns\tq-benchmark-3.7.9_mean\tq-benchmark-3.7.9_stddev\n1\t20\t0.08142082691192627\t0.001304584466639188\n10\t20\t0.08197519779205323\t0.0014842098503865223\n100\t20\t0.08949971199035645\t0.0009937446141285785\n1000\t20\t0.09955930709838867\t0.0013978961740806384\n10000\t20\t0.1966566801071167\t0.0028489273218240147\n100000\t20\t1.1518636226654053\t0.006410720031542237\n1000000\t20\t10.776052689552307\t0.04739925571001746\nlines\tcolumns\tq-benchmark-3.7.9_mean\tq-benchmark-3.7.9_stddev\n1\t50\t0.08237688541412354\t0.0016494314799953837\n10\t50\t0.08519520759582519\t0.002610550182895596\n100\t50\t0.10423583984375\t0.0018808335751867933\n1000\t50\t0.12195603847503662\t0.0023611894043373983\n10000\t50\t0.3163540124893188\t0.002761333651520998\n100000\t50\t2.237372374534607\t0.009955353920396077\n1000000\t50\t21.59097549915314\t0.081188190530421\nlines\tcolumns\tq-benchmark-3.7.9_mean\tq-benchmark-3.7.9_stddev\n1\t100\t0.08336784839630126\t0.0013840724401561887\n10\t100\t0.0864112138748169\t0.0017946939354350697\n100\t100\t0.12199611663818359\t0.0013003743156634682\n1000\t100\t0.15871686935424806\t0.0035993681064501234\n10000\t100\t0.5243751525878906\t0.004370273273595629\n100000\t100\t4.175828623771667\t0.016127303710583043\n1000000\t100\t40.82292411327362\t0.12328165162380703\n"
  },
  {
    "path": "test/benchmark-results/source-files-1443b7418b46594ad256abd9db4a7671cb251e6a/2020-09-17-v2.0.17/q-benchmark-3.8.5.benchmark-results",
    "content": "lines\tcolumns\tq-benchmark-3.8.5_mean\tq-benchmark-3.8.5_stddev\n1\t1\t0.10138180255889892\t0.0017947074090971444\n10\t1\t0.10056869983673096\t0.003442371291904885\n100\t1\t0.10126984119415283\t0.0016392348107127808\n1000\t1\t0.10484635829925537\t0.0019743937339163262\n10000\t1\t0.1400548219680786\t0.0024523366133394117\n100000\t1\t0.4901275157928467\t0.003970374711691596\n1000000\t1\t3.982502889633179\t0.045292138461945054\nlines\tcolumns\tq-benchmark-3.8.5_mean\tq-benchmark-3.8.5_stddev\n1\t5\t0.09946837425231933\t0.0018876161478998787\n10\t5\t0.099178147315979\t0.0014194733014858227\n100\t5\t0.10171806812286377\t0.0017580984705406846\n1000\t5\t0.10602672100067138\t0.002000261880840017\n10000\t5\t0.15207929611206056\t0.0015802680033212048\n100000\t5\t0.609218978881836\t0.006150144273259608\n1000000\t5\t5.13688440322876\t0.03649575898109647\nlines\tcolumns\tq-benchmark-3.8.5_mean\tq-benchmark-3.8.5_stddev\n1\t10\t0.09925477504730225\t0.002168389758635997\n10\t10\t0.09943633079528809\t0.0016154501074880502\n100\t10\t0.10376312732696533\t0.0017275485891005433\n1000\t10\t0.11087138652801513\t0.0016934328033239559\n10000\t10\t0.17246220111846924\t0.0023824485659318527\n100000\t10\t0.7999232530593872\t0.003442975393506892\n1000000\t10\t7.012071299552917\t0.059217904448851263\nlines\tcolumns\tq-benchmark-3.8.5_mean\tq-benchmark-3.8.5_stddev\n1\t20\t0.10027089118957519\t0.0020291529595204906\n10\t20\t0.10038816928863525\t0.001957086760826999\n100\t20\t0.10723590850830078\t0.0013833918448622436\n1000\t20\t0.11735000610351562\t0.0020318895390750882\n10000\t20\t0.21264209747314453\t0.00482341642419078\n100000\t20\t1.1567201137542724\t0.002987096441878969\n1000000\t20\t10.640758633613586\t0.06116581724028616\nlines\tcolumns\tq-benchmark-3.8.5_mean\tq-benchmark-3.8.5_stddev\n1\t50\t0.10066506862640381\t0.002051307639276982\n10\t50\t0.10588631629943848\t0.0035835389655972105\n100\t50\t0.11841504573822022\t0.001608174845404568\n1000\t50\t0.14032282829284667\t0.002640027148889162\n10000\t50\t0.33160474300384524\t0.0027796660009712947\n100000\t50\t2.258401036262512\t0.011041280982383895\n1000000\t50\t21.70080256462097\t0.15897944629180621\nlines\tcolumns\tq-benchmark-3.8.5_mean\tq-benchmark-3.8.5_stddev\n1\t100\t0.10147004127502442\t0.0021285682695135768\n10\t100\t0.10471885204315186\t0.001248479289219899\n100\t100\t0.13894760608673096\t0.002307980025026551\n1000\t100\t0.17586205005645753\t0.0023822296091426\n10000\t100\t0.5414002418518067\t0.0036291866664635458\n100000\t100\t4.222555088996887\t0.08562968951916528\n1000000\t100\t41.021552324295044\t0.16033566363076862\n"
  },
  {
    "path": "test/benchmark-results/source-files-1443b7418b46594ad256abd9db4a7671cb251e6a/2020-09-17-v2.0.17/summary.benchmark-results",
    "content": "lines\tcolumns\tq-benchmark-2.7.18_mean\tq-benchmark-2.7.18_stddev\tlines\tcolumns\tq-benchmark-3.6.4_mean\tq-benchmark-3.6.4_stddev\tlines\tcolumns\tq-benchmark-3.7.9_mean\tq-benchmark-3.7.9_stddev\tlines\tcolumns\tq-benchmark-3.8.5_mean\tq-benchmark-3.8.5_stddev\tlines\tcolumns\ttextql_2.0.3_mean\ttextql_2.0.3_stddev\tlines\tcolumns\toctosql_v0.3.0_mean\toctosql_v0.3.0_stddev\n1\t1\t0.106449890137\t0.002010027753\t1\t1\t0.10342762470245362\t0.0017673875851759295\t1\t1\t0.08099310398101807\t0.001417385651688644\t1\t1\t0.10138180255889892\t0.0017947074090971444\t1\t1\t0.0196103572845\t0.00207355214257\t1\t1\t0.582091641426\t0.0235290239617\n10\t1\t0.106737875938\t0.00224112203891\t10\t1\t0.10239293575286865\t0.0012505611685910795\t10\t1\t0.0822291374206543\t0.0014809900020001858\t10\t1\t0.10056869983673096\t0.003442371291904885\t10\t1\t0.0186784029007\t0.000970810220668\t10\t1\t0.596219730377\t0.0320124029461\n100\t1\t0.107839012146\t0.00102954061006\t100\t1\t0.10317318439483643\t0.0010581783881541751\t100\t1\t0.08169686794281006\t0.002108157069167563\t100\t1\t0.10126984119415283\t0.0016392348107127808\t100\t1\t0.019472026825\t0.00181951524514\t100\t1\t0.575977492332\t0.0199296245316\n1000\t1\t0.113026666641\t0.00147361890226\t1000\t1\t0.10687050819396973\t0.0014050135772919004\t1000\t1\t0.08690853118896484\t0.0012595326919263487\t1000\t1\t0.10484635829925537\t0.0019743937339163262\t1000\t1\t0.022180891037\t0.00116649968967\t1000\t1\t0.56785056591\t0.00846389017466\n10000\t1\t0.160376381874\t0.00569766179806\t10000\t1\t0.1447664737701416\t0.001841256227287192\t10000\t1\t0.12215542793273926\t0.0020152625320395434\t10000\t1\t0.1400548219680786\t0.0024523366133394117\t10000\t1\t0.051066827774\t0.0018168767618\t10000\t1\t1.1466334343\t0.00760108698846\n100000\t1\t0.608236479759\t0.00604026519608\t100000\t1\t0.5162809371948243\t0.006962985088492867\t100000\t1\t0.4825761795043945\t0.0050418000028856335\t100000\t1\t0.4901275157928467\t0.003970374711691596\t100000\t1\t0.307463979721\t0.00246268029188\t100000\t1\t5.49565172195\t0.131791932977\n1000000\t1\t5.14807910919\t0.0584474028762\t1000000\t1\t4.238853335380554\t0.04834401143632507\t1000000\t1\t4.084399747848511\t0.027731958079814215\t1000000\t1\t3.982502889633179\t0.045292138461945054\t1000000\t1\t2.89862303734\t0.022182722976\t1000000\t1\t49.9513648033\t0.443430523063\nlines\tcolumns\tq-benchmark-2.7.18_mean\tq-benchmark-2.7.18_stddev\tlines\tcolumns\tq-benchmark-3.6.4_mean\tq-benchmark-3.6.4_stddev\tlines\tcolumns\tq-benchmark-3.7.9_mean\tq-benchmark-3.7.9_stddev\tlines\tcolumns\tq-benchmark-3.8.5_mean\tq-benchmark-3.8.5_stddev\tlines\tcolumns\ttextql_2.0.3_mean\ttextql_2.0.3_stddev\tlines\tcolumns\toctosql_v0.3.0_mean\toctosql_v0.3.0_stddev\n1\t5\t0.106719517708\t0.00236752032369\t1\t5\t0.10211825370788574\t0.0022568191323651568\t1\t5\t0.0817826271057129\t0.002665533758836163\t1\t5\t0.09946837425231933\t0.0018876161478998787\t1\t5\t0.0195286750793\t0.0017840569109\t1\t5\t0.582160949707\t0.0274409391571\n10\t5\t0.107823801041\t0.00238873169438\t10\t5\t0.1025341272354126\t0.0016446470901070106\t10\t5\t0.08261749744415284\t0.0019205430658525572\t10\t5\t0.099178147315979\t0.0014194733014858227\t10\t5\t0.0183676958084\t0.000925251595491\t10\t5\t0.57046456337\t0.0199413000359\n100\t5\t0.109785079956\t0.0013047675259\t100\t5\t0.1053577184677124\t0.0015298114223855884\t100\t5\t0.08472237586975098\t0.002571239449841039\t100\t5\t0.10171806812286377\t0.0017580984705406846\t100\t5\t0.0199447393417\t0.000907007099218\t100\t5\t0.585747480392\t0.0372543971623\n1000\t5\t0.120395207405\t0.00207224422629\t1000\t5\t0.10980842113494874\t0.002536098780902228\t1000\t5\t0.08973510265350342\t0.002323797583077552\t1000\t5\t0.10602672100067138\t0.002000261880840017\t1000\t5\t0.0263328790665\t0.00165486505938\t1000\t5\t0.572268772125\t0.00384300349763\n10000\t5\t0.21783041954\t0.00522254475716\t10000\t5\t0.1590113162994385\t0.003123074098301634\t10000\t5\t0.13746986389160157\t0.001964971666036654\t10000\t5\t0.15207929611206056\t0.0015802680033212048\t10000\t5\t0.0826982736588\t0.00152451583229\t10000\t5\t1.15530762672\t0.0117990775856\n100000\t5\t1.17115747929\t0.0221394865225\t100000\t5\t0.6348223447799682\t0.0082691507829872\t100000\t5\t0.60649254322052\t0.007131635266871318\t100000\t5\t0.609218978881836\t0.006150144273259608\t100000\t5\t0.60660867691\t0.00395761320274\t100000\t5\t6.10629923344\t0.146711842919\n1000000\t5\t10.6830974817\t0.339822977934\t1000000\t5\t5.368562030792236\t0.11628913334105236\t1000000\t5\t5.2585612535476685\t0.05661789407928516\t1000000\t5\t5.13688440322876\t0.03649575898109647\t1000000\t5\t5.87811236382\t0.0304332294491\t1000000\t5\t54.6851765394\t0.315486399525\nlines\tcolumns\tq-benchmark-2.7.18_mean\tq-benchmark-2.7.18_stddev\tlines\tcolumns\tq-benchmark-3.6.4_mean\tq-benchmark-3.6.4_stddev\tlines\tcolumns\tq-benchmark-3.7.9_mean\tq-benchmark-3.7.9_stddev\tlines\tcolumns\tq-benchmark-3.8.5_mean\tq-benchmark-3.8.5_stddev\tlines\tcolumns\ttextql_2.0.3_mean\ttextql_2.0.3_stddev\tlines\tcolumns\toctosql_v0.3.0_mean\toctosql_v0.3.0_stddev\n1\t10\t0.104981088638\t0.00166552032929\t1\t10\t0.10251858234405517\t0.0015963869535345293\t1\t10\t0.08112843036651611\t0.002251300165899426\t1\t10\t0.09925477504730225\t0.002168389758635997\t1\t10\t0.0191783189774\t0.00107718516178\t1\t10\t0.586222410202\t0.0232479065914\n10\t10\t0.108320140839\t0.00204034349199\t10\t10\t0.10278875827789306\t0.0009920577082124496\t10\t10\t0.08175232410430908\t0.0014557171018568637\t10\t10\t0.09943633079528809\t0.0016154501074880502\t10\t10\t0.0185215950012\t0.000840353961363\t10\t10\t0.59000480175\t0.0186508192447\n100\t10\t0.112528729439\t0.00168376477305\t100\t10\t0.10715732574462891\t0.002033320000941064\t100\t10\t0.08572309017181397\t0.0019643550214810675\t100\t10\t0.10376312732696533\t0.0017275485891005433\t100\t10\t0.0209223031998\t0.00164494657684\t100\t10\t0.581873703003\t0.0331332482772\n1000\t10\t0.13019015789\t0.00253773120965\t1000\t10\t0.11389360427856446\t0.0023603847702423973\t1000\t10\t0.09268453121185302\t0.001816414236580489\t1000\t10\t0.11087138652801513\t0.0016934328033239559\t1000\t10\t0.0309282779694\t0.00110848590345\t1000\t10\t0.569027900696\t0.0103675493106\n10000\t10\t0.284891676903\t0.00384009140782\t10000\t10\t0.17806434631347656\t0.001114054252191835\t10000\t10\t0.15538835525512695\t0.0024978076091814994\t10000\t10\t0.17246220111846924\t0.0023824485659318527\t10000\t10\t0.121016025543\t0.00105071105139\t10000\t10\t1.40067322254\t0.00583352224401\n100000\t10\t1.84725661278\t0.00860738744089\t100000\t10\t0.8252989768981933\t0.0037080843359275904\t100000\t10\t0.7879442930221557\t0.009412516078916211\t100000\t10\t0.7999232530593872\t0.003442975393506892\t100000\t10\t0.987622976303\t0.00699348302979\t100000\t10\t7.30705575943\t0.0165839217599\n1000000\t10\t17.5610994339\t0.228322442172\t1000000\t10\t7.252838873863221\t0.029052130546213153\t1000000\t10\t7.146207928657532\t0.06659760176757985\t1000000\t10\t7.012071299552917\t0.059217904448851263\t1000000\t10\t9.69240145683\t0.0354453778052\t1000000\t10\t65.3242264032\t0.512552576414\nlines\tcolumns\tq-benchmark-2.7.18_mean\tq-benchmark-2.7.18_stddev\tlines\tcolumns\tq-benchmark-3.6.4_mean\tq-benchmark-3.6.4_stddev\tlines\tcolumns\tq-benchmark-3.7.9_mean\tq-benchmark-3.7.9_stddev\tlines\tcolumns\tq-benchmark-3.8.5_mean\tq-benchmark-3.8.5_stddev\tlines\tcolumns\ttextql_2.0.3_mean\ttextql_2.0.3_stddev\tlines\tcolumns\toctosql_v0.3.0_mean\toctosql_v0.3.0_stddev\n1\t20\t0.106477689743\t0.00254429925697\t1\t20\t0.10367965698242188\t0.003661761341842434\t1\t20\t0.08142082691192627\t0.001304584466639188\t1\t20\t0.10027089118957519\t0.0020291529595204906\t1\t20\t0.0202306985855\t0.00159619251952\t1\t20\t0.571048212051\t0.0166919396871\n10\t20\t0.108580899239\t0.00173704653824\t10\t20\t0.10489590167999267\t0.001977141196109372\t10\t20\t0.08197519779205323\t0.0014842098503865223\t10\t20\t0.10038816928863525\t0.001957086760826999\t10\t20\t0.0187650680542\t0.000845692486156\t10\t20\t0.594776701927\t0.0368900941023\n100\t20\t0.118750286102\t0.00247623639866\t100\t20\t0.11108210086822509\t0.0014801173497056886\t100\t20\t0.08949971199035645\t0.0009937446141285785\t100\t20\t0.10723590850830078\t0.0013833918448622436\t100\t20\t0.0211876153946\t0.000993808448942\t100\t20\t0.561370825768\t0.00907051791451\n1000\t20\t0.146431708336\t0.00249685551944\t1000\t20\t0.12110791206359864\t0.001648524669420912\t1000\t20\t0.09955930709838867\t0.0013978961740806384\t1000\t20\t0.11735000610351562\t0.0020318895390750882\t1000\t20\t0.0404737234116\t0.00122415059261\t1000\t20\t0.577527880669\t0.00983965108957\n10000\t20\t0.419492387772\t0.00248210434668\t10000\t20\t0.2178968906402588\t0.0019298316207276716\t10000\t20\t0.1966566801071167\t0.0028489273218240147\t10000\t20\t0.21264209747314453\t0.00482341642419078\t10000\t20\t0.197762489319\t0.00198188642677\t10000\t20\t1.90710241795\t0.00757011452155\n100000\t20\t3.15847921371\t0.0550301268026\t100000\t20\t1.1962245225906372\t0.010541407803235559\t100000\t20\t1.1518636226654053\t0.006410720031542237\t100000\t20\t1.1567201137542724\t0.002987096441878969\t100000\t20\t1.75432097912\t0.00692372147543\t100000\t20\t9.8267291069\t0.127844155326\n1000000\t20\t30.279082489\t0.124978814506\t1000000\t20\t10.956057572364807\t0.12677108174061705\t1000000\t20\t10.776052689552307\t0.04739925571001746\t1000000\t20\t10.640758633613586\t0.06116581724028616\t1000000\t20\t17.3383012295\t0.0410164637448\t1000000\t20\t83.9448960066\t0.46121344046\nlines\tcolumns\tq-benchmark-2.7.18_mean\tq-benchmark-2.7.18_stddev\tlines\tcolumns\tq-benchmark-3.6.4_mean\tq-benchmark-3.6.4_stddev\tlines\tcolumns\tq-benchmark-3.7.9_mean\tq-benchmark-3.7.9_stddev\tlines\tcolumns\tq-benchmark-3.8.5_mean\tq-benchmark-3.8.5_stddev\tlines\tcolumns\ttextql_2.0.3_mean\ttextql_2.0.3_stddev\tlines\tcolumns\toctosql_v0.3.0_mean\toctosql_v0.3.0_stddev\n1\t50\t0.105411934853\t0.00171651054128\t1\t50\t0.10458300113677979\t0.0016367630302744722\t1\t50\t0.08237688541412354\t0.0016494314799953837\t1\t50\t0.10066506862640381\t0.002051307639276982\t1\t50\t0.0205577373505\t0.00133922342068\t1\t50\t0.572030115128\t0.0253648479103\n10\t50\t0.109102797508\t0.00111620290512\t10\t50\t0.10616152286529541\t0.002345135740908088\t10\t50\t0.08519520759582519\t0.002610550182895596\t10\t50\t0.10588631629943848\t0.0035835389655972105\t10\t50\t0.0195438146591\t0.000791630611893\t10\t50\t0.56993534565\t0.0230474303306\n100\t50\t0.135682177544\t0.00196166766665\t100\t50\t0.12375867366790771\t0.00238414904864133\t100\t50\t0.10423583984375\t0.0018808335751867933\t100\t50\t0.11841504573822022\t0.001608174845404568\t100\t50\t0.0246078014374\t0.00108949795701\t100\t50\t0.563336873055\t0.00964411866903\n1000\t50\t0.198261427879\t0.00396172489054\t1000\t50\t0.14462883472442628\t0.0022428030896492978\t1000\t50\t0.12195603847503662\t0.0023611894043373983\t1000\t50\t0.14032282829284667\t0.002640027148889162\t1000\t50\t0.063302564621\t0.00058195987294\t1000\t50\t0.826378440857\t0.00941629472813\n10000\t50\t0.821499919891\t0.0111642692132\t10000\t50\t0.34488487243652344\t0.004867441221052092\t10000\t50\t0.3163540124893188\t0.002761333651520998\t10000\t50\t0.33160474300384524\t0.0027796660009712947\t10000\t50\t0.410061001778\t0.00294901155085\t10000\t50\t3.27872717381\t0.126592845956\n100000\t50\t7.05980975628\t0.121182371277\t100000\t50\t2.3394312858581543\t0.02263239858944125\t100000\t50\t2.237372374534607\t0.009955353920396077\t100000\t50\t2.258401036262512\t0.011041280982383895\t100000\t50\t3.87797718048\t0.0123467913678\t100000\t50\t17.890055728\t0.116794666005\n1000000\t50\t71.5645889759\t5.02009516291\t1000000\t50\t21.979821610450745\t0.09080404939303836\t1000000\t50\t21.59097549915314\t0.081188190530421\t1000000\t50\t21.70080256462097\t0.15897944629180621\t1000000\t50\t38.5674883366\t0.0602820291386\t1000000\t50\t158.262442636\t0.826290454446\nlines\tcolumns\tq-benchmark-2.7.18_mean\tq-benchmark-2.7.18_stddev\tlines\tcolumns\tq-benchmark-3.6.4_mean\tq-benchmark-3.6.4_stddev\tlines\tcolumns\tq-benchmark-3.7.9_mean\tq-benchmark-3.7.9_stddev\tlines\tcolumns\tq-benchmark-3.8.5_mean\tq-benchmark-3.8.5_stddev\tlines\tcolumns\ttextql_2.0.3_mean\ttextql_2.0.3_stddev\tlines\tcolumns\toctosql_v0.3.0_mean\toctosql_v0.3.0_stddev\n1\t100\t0.10662381649\t0.00193146624495\t1\t100\t0.10372309684753418\t0.0010299126833031144\t1\t100\t0.08336784839630126\t0.0013840724401561887\t1\t100\t0.10147004127502442\t0.0021285682695135768\t1\t100\t0.0216581106186\t0.00103280947157\t1\t100\t0.569358110428\t0.0279801762531\n10\t100\t0.110662698746\t0.00171461379583\t10\t100\t0.10784556865692138\t0.0016557634029464607\t10\t100\t0.0864112138748169\t0.0017946939354350697\t10\t100\t0.10471885204315186\t0.001248479289219899\t10\t100\t0.021723818779\t0.000920429257416\t10\t100\t0.580981063843\t0.0272341107532\n100\t100\t0.163547992706\t0.00166570196628\t100\t100\t0.14526791572570802\t0.0028194506905186724\t100\t100\t0.12199611663818359\t0.0013003743156634682\t100\t100\t0.13894760608673096\t0.002307980025026551\t100\t100\t0.0299471855164\t0.00130217326679\t100\t100\t0.559471726418\t0.00668155858429\n1000\t100\t0.280023741722\t0.00337543024145\t1000\t100\t0.18315494060516357\t0.0023585311962114673\t1000\t100\t0.15871686935424806\t0.0035993681064501234\t1000\t100\t0.17586205005645753\t0.0023822296091426\t1000\t100\t0.0996923923492\t0.00155352212734\t1000\t100\t1.08161640167\t0.00698594638512\n10000\t100\t1.46053376198\t0.0221691284465\t10000\t100\t0.5586131334304809\t0.004808492789681402\t10000\t100\t0.5243751525878906\t0.004370273273595629\t10000\t100\t0.5414002418518067\t0.0036291866664635458\t10000\t100\t0.767001605034\t0.00328944029633\t10000\t100\t5.67823712826\t0.0123398407167\n100000\t100\t13.2369835854\t0.309375896258\t100000\t100\t4.287398314476013\t0.00957500108409644\t100000\t100\t4.175828623771667\t0.016127303710583043\t100000\t100\t4.222555088996887\t0.08562968951916528\t100000\t100\t7.46734063625\t0.0262039846119\t100000\t100\t32.2797194242\t0.315508270241\n1000000\t100\t131.864977288\t1.22415449691\t1000000\t100\t41.706851434707644\t0.4161526076289425\t1000000\t100\t40.82292411327362\t0.12328165162380703\t1000000\t100\t41.021552324295044\t0.16033566363076862\t1000000\t100\t74.6216712952\t0.0994037504394\t1000000\t100\t289.582628798\t0.929455236817\n"
  },
  {
    "path": "test/benchmark-results/source-files-1443b7418b46594ad256abd9db4a7671cb251e6a/2020-09-17-v2.0.17/textql_2.0.3.benchmark-results",
    "content": "lines\tcolumns\ttextql_2.0.3_mean\ttextql_2.0.3_stddev\n1\t1\t0.0196103572845\t0.00207355214257\n10\t1\t0.0186784029007\t0.000970810220668\n100\t1\t0.019472026825\t0.00181951524514\n1000\t1\t0.022180891037\t0.00116649968967\n10000\t1\t0.051066827774\t0.0018168767618\n100000\t1\t0.307463979721\t0.00246268029188\n1000000\t1\t2.89862303734\t0.022182722976\nlines\tcolumns\ttextql_2.0.3_mean\ttextql_2.0.3_stddev\n1\t5\t0.0195286750793\t0.0017840569109\n10\t5\t0.0183676958084\t0.000925251595491\n100\t5\t0.0199447393417\t0.000907007099218\n1000\t5\t0.0263328790665\t0.00165486505938\n10000\t5\t0.0826982736588\t0.00152451583229\n100000\t5\t0.60660867691\t0.00395761320274\n1000000\t5\t5.87811236382\t0.0304332294491\nlines\tcolumns\ttextql_2.0.3_mean\ttextql_2.0.3_stddev\n1\t10\t0.0191783189774\t0.00107718516178\n10\t10\t0.0185215950012\t0.000840353961363\n100\t10\t0.0209223031998\t0.00164494657684\n1000\t10\t0.0309282779694\t0.00110848590345\n10000\t10\t0.121016025543\t0.00105071105139\n100000\t10\t0.987622976303\t0.00699348302979\n1000000\t10\t9.69240145683\t0.0354453778052\nlines\tcolumns\ttextql_2.0.3_mean\ttextql_2.0.3_stddev\n1\t20\t0.0202306985855\t0.00159619251952\n10\t20\t0.0187650680542\t0.000845692486156\n100\t20\t0.0211876153946\t0.000993808448942\n1000\t20\t0.0404737234116\t0.00122415059261\n10000\t20\t0.197762489319\t0.00198188642677\n100000\t20\t1.75432097912\t0.00692372147543\n1000000\t20\t17.3383012295\t0.0410164637448\nlines\tcolumns\ttextql_2.0.3_mean\ttextql_2.0.3_stddev\n1\t50\t0.0205577373505\t0.00133922342068\n10\t50\t0.0195438146591\t0.000791630611893\n100\t50\t0.0246078014374\t0.00108949795701\n1000\t50\t0.063302564621\t0.00058195987294\n10000\t50\t0.410061001778\t0.00294901155085\n100000\t50\t3.87797718048\t0.0123467913678\n1000000\t50\t38.5674883366\t0.0602820291386\nlines\tcolumns\ttextql_2.0.3_mean\ttextql_2.0.3_stddev\n1\t100\t0.0216581106186\t0.00103280947157\n10\t100\t0.021723818779\t0.000920429257416\n100\t100\t0.0299471855164\t0.00130217326679\n1000\t100\t0.0996923923492\t0.00155352212734\n10000\t100\t0.767001605034\t0.00328944029633\n100000\t100\t7.46734063625\t0.0262039846119\n1000000\t100\t74.6216712952\t0.0994037504394\n"
  },
  {
    "path": "test/test_suite.py",
    "content": "#!/usr/bin/env python3\n\n#\n# test suite for q.\n# \n# Prefer end-to-end tests, running the actual q command and testing stdout/stderr, and the return code.\n# Some utilities are provided for making that easy, see other tests for examples.\n#\n# Q_EXECUTABLE env var can be used to inject the path of q. This allows full e2e testing of the resulting executable\n# instead of just testing the python code.\n#\n# Tests are compatible with Linux and OSX (path separators, tmp folder, etc.).\n\nfrom __future__ import print_function\n\nimport collections\nimport functools\nimport tempfile\nimport unittest\nimport random\nimport json\nimport uuid\nfrom collections import OrderedDict\nfrom json import JSONEncoder\nfrom subprocess import PIPE, Popen, STDOUT\nimport sys\nimport os\nimport time\nfrom tempfile import NamedTemporaryFile\nimport locale\nimport pprint\nimport six\nfrom six.moves import range\nimport codecs\nimport itertools\nfrom gzip import GzipFile\nimport pytest\nimport uuid\nimport sqlite3\nimport re\nimport collections\n\nsys.path.append(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),'..','bin'))\nfrom bin.q import QTextAsData, QOutput, QOutputPrinter, QInputParams, DataStream, Sqlite3DB\n\n# q uses this encoding as the default output encoding. Some of the tests use it in order to \n# make sure that the output is correctly encoded\nSYSTEM_ENCODING = locale.getpreferredencoding()\n\nEXAMPLES = os.path.abspath(os.path.join(os.getcwd(), 'examples'))\n\nQ_EXECUTABLE = os.getenv('Q_EXECUTABLE', os.path.abspath('./bin/q.py'))\nQ_SKIP_EXECUTABLE_VALIDATION = os.getenv('Q_SKIP_EXECUTABLE_VALIDATION','false')\n\nif not Q_SKIP_EXECUTABLE_VALIDATION == 'true':\n    Q_EXECUTABLE = os.path.abspath(Q_EXECUTABLE)\n    if not os.path.exists(Q_EXECUTABLE):\n        raise Exception(\"q executable must reside in {}\".format(Q_EXECUTABLE))\nelse:\n    Q_EXECUTABLE = os.getenv('Q_EXECUTABLE')\n    # Skip checking of executable (useful for testing that q is in the path)\n    pass\n\nDEBUG = '-v' in sys.argv\nif os.environ.get('Q_DEBUG'):\n    DEBUG = True\n\ndef batch(iterable, n=1):\n    r = []\n    l = len(iterable)\n    for ndx in range(0, l, n):\n        r += [iterable[ndx:min(ndx + n, l)]]\n    return r\n\ndef partition(pred, iterable):\n    t1, t2 = itertools.tee(iterable)\n    return list(itertools.filterfalse(pred, t1)), list(filter(pred, t2))\n\ndef run_command(cmd_to_run,env_to_inject=None):\n    global DEBUG\n    if DEBUG:\n        print(\"CMD: {}\".format(cmd_to_run))\n\n    if env_to_inject is None:\n        env_to_inject = os.environ\n\n    env = env_to_inject\n\n    p = Popen(cmd_to_run, stdout=PIPE, stderr=PIPE, shell=True,env=env)\n    o, e = p.communicate()\n    # remove last newline\n    o = o.rstrip()\n    e = e.strip()\n    # split rows\n    if o != six.b(''):\n        o = o.split(six.b(os.linesep))\n    else:\n        o = []\n    if e != six.b(''):\n        e = e.split(six.b(os.linesep))\n    else:\n        e = []\n\n    res = (p.returncode, o, e)\n    if DEBUG:\n        print(\"RESULT:{}\".format(res))\n    return res\n\n\nuneven_ls_output = six.b(\"\"\"drwxr-xr-x   2 root     root      4096 Jun 11  2012 /selinux\ndrwxr-xr-x   2 root     root      4096 Apr 19  2013 /mnt\ndrwxr-xr-x   2 root     root      4096 Apr 24  2013 /srv\ndrwx------   2 root     root     16384 Jun 21  2013 /lost+found\nlrwxrwxrwx   1 root     root        33 Jun 21  2013 /initrd.img.old -> /boot/initrd.img-3.8.0-19-generic\ndrwxr-xr-x   2 root     root      4096 Jun 21  2013 /cdrom\ndrwxr-xr-x   3 root     root      4096 Jun 21  2013 /home\nlrwxrwxrwx   1 root     root        29 Jun 21  2013 /vmlinuz -> boot/vmlinuz-3.8.0-19-generic\nlrwxrwxrwx   1 root     root        32 Jun 21  2013 /initrd.img -> boot/initrd.img-3.8.0-19-generic\n\"\"\")\n\n\nfind_output = six.b(\"\"\"8257537   32 drwxrwxrwt 218 root     root        28672 Mar  1 11:00 /tmp\n8299123    4 drwxrwxr-x   2 harel    harel        4096 Feb 27 10:06 /tmp/1628a3fd-b9fe-4dd1-bcdc-7eb869fe7461/supervisor/stormdist/testTopology3fad644a-54c0-4def-b19e-77ca97941595-1-1393513576\n8263229  964 -rw-rw-r--   1 mapred   mapred      984569 Feb 27 10:06 /tmp/1628a3fd-b9fe-4dd1-bcdc-7eb869fe7461/supervisor/stormdist/testTopology3fad644a-54c0-4def-b19e-77ca97941595-1-1393513576/stormcode.ser\n8263230    4 -rw-rw-r--   1 harel    harel        1223 Feb 27 10:06 /tmp/1628a3fd-b9fe-4dd1-bcdc-7eb869fe7461/supervisor/stormdist/testTopology3fad644a-54c0-4def-b19e-77ca97941595-1-1393513576/stormconf.ser\n8299113    4 drwxrwxr-x   2 harel    harel        4096 Feb 27 10:16 /tmp/1628a3fd-b9fe-4dd1-bcdc-7eb869fe7461/supervisor/localstate\n8263406    4 -rw-rw-r--   1 harel    harel        2002 Feb 27 10:16 /tmp/1628a3fd-b9fe-4dd1-bcdc-7eb869fe7461/supervisor/localstate/1393514168746\n8263476    0 -rw-rw-r--   1 harel    harel           0 Feb 27 10:16 /tmp/1628a3fd-b9fe-4dd1-bcdc-7eb869fe7461/supervisor/localstate/1393514168746.version\n8263607    0 -rw-rw-r--   1 harel    harel           0 Feb 27 10:16 /tmp/1628a3fd-b9fe-4dd1-bcdc-7eb869fe7461/supervisor/localstate/1393514169735.version\n8263533    0 -rw-rw-r--   1 harel    harel           0 Feb 27 10:16 /tmp/1628a3fd-b9fe-4dd1-bcdc-7eb869fe7461/supervisor/localstate/1393514172733.version\n8263604    0 -rw-rw-r--   1 harel    harel           0 Feb 27 10:16 /tmp/1628a3fd-b9fe-4dd1-bcdc-7eb869fe7461/supervisor/localstate/1393514175754.version\n\"\"\")\n\n\nheader_row = six.b('name,value1,value2')\nsample_data_rows = [six.b('a,1,0'), six.b('b,2,0'), six.b('c,,0')]\nsample_data_rows_with_empty_string = [six.b('a,aaa,0'), six.b('b,bbb,0'), six.b('c,,0')]\nsample_data_no_header = six.b(\"\\n\").join(sample_data_rows) + six.b(\"\\n\")\nsample_data_with_empty_string_no_header = six.b(\"\\n\").join(\n    sample_data_rows_with_empty_string) + six.b(\"\\n\")\nsample_data_with_header = header_row + six.b(\"\\n\") + sample_data_no_header\nsample_data_with_missing_header_names = six.b(\"name,value1\\n\") + sample_data_no_header\n\ndef generate_sample_data_with_header(header):\n    return header + six.b(\"\\n\") + sample_data_no_header\n\nsample_quoted_data = six.b('''non_quoted regular_double_quoted double_double_quoted escaped_double_quoted multiline_double_double_quoted multiline_escaped_double_quoted\ncontrol-value-1 \"control-value-2\" control-value-3 \"control-value-4\" control-value-5 \"control-value-6\"\nnon-quoted-value \"this is a quoted value\" \"this is a \"\"double double\"\" quoted value\" \"this is an escaped \\\\\"quoted value\\\\\"\" \"this is a double double quoted \"\"multiline\n  value\"\".\" \"this is an escaped \\\\\"multiline\n  value\\\\\".\"\ncontrol-value-1 \"control-value-2\" control-value-3 \"control-value-4\" control-value-5 \"control-value-6\"\n''')\n\ndouble_double_quoted_data = six.b('''regular_double_quoted double_double_quoted\n\"this is a quoted value\" \"this is a quoted value with \"\"double double quotes\"\"\"\n''')\n\nescaped_double_quoted_data = six.b('''regular_double_quoted escaped_double_quoted\n\"this is a quoted value\" \"this is a quoted value with \\\\\"escaped double quotes\\\\\"\"\n''')\n\ncombined_quoted_data = six.b('''regular_double_quoted double_double_quoted escaped_double_quoted\n\"this is a quoted value\" \"this is a quoted value with \"\"double double quotes\"\"\" \"this is a quoted value with \\\\\"escaped double quotes\\\\\"\"\n''')\n\nsample_quoted_data2 = six.b('\"quoted data\" 23\\nunquoted-data 54')\n\nsample_quoted_data2_with_newline = six.b('\"quoted data with\\na new line inside it\":23\\nunquoted-data:54')\n\none_column_data = six.b('''data without commas 1\ndata without commas 2\n''')\n\n# Values with leading whitespace\nsample_data_rows_with_spaces = [six.b('a,1,0'), six.b('   b,   2,0'), six.b('c,,0')]\nsample_data_with_spaces_no_header = six.b(\"\\n\").join(\n    sample_data_rows_with_spaces) + six.b(\"\\n\")\n\nheader_row_with_spaces = six.b('name,value 1,value2')\nsample_data_with_spaces_with_header = header_row_with_spaces + \\\n    six.b(\"\\n\") + sample_data_with_spaces_no_header\n\nlong_value1 = \"23683289372328372328373\"\nint_value = \"2328372328373\"\nsample_data_with_long_values = \"%s\\n%s\\n%s\" % (long_value1,int_value,int_value)\n\n\ndef one_column_warning(e):\n    return e[0].startswith(six.b('Warning: column count is one'))\n\ndef sqlite_dict_factory(cursor, row):\n    d = {}\n    for idx, col in enumerate(cursor.description):\n        d[col[0]] = row[idx]\n    return d\n\nclass AbstractQTestCase(unittest.TestCase):\n\n    def create_file_with_data(self, data, encoding=None,prefix=None,suffix=None,use_real_path=True):\n        if encoding is not None:\n            raise Exception('Deprecated: Encoding must be none')\n        tmpfile = NamedTemporaryFile(delete=False,prefix=prefix,suffix=suffix)\n        tmpfile.write(data)\n        tmpfile.close()\n        if use_real_path:\n            tmpfile.name = os.path.realpath(tmpfile.name)\n        return tmpfile\n\n    def generate_tmpfile_name(self,prefix=None,suffix=None):\n        tmpfile = NamedTemporaryFile(delete=False,prefix=prefix,suffix=suffix)\n        os.remove(tmpfile.name)\n        return os.path.realpath(tmpfile.name)\n\n    def arrays_to_csv_file_content(self,delimiter,header_row_list,cell_list):\n        all_rows = [delimiter.join(row) for row in [header_row_list] + cell_list]\n        return six.b(\"\\n\").join(all_rows)\n\n    def create_qsql_file_with_content_and_return_filename(self, header_row,cell_list):\n        csv_content = self.arrays_to_csv_file_content(six.b(','),header_row,cell_list)\n        tmpfile = self.create_file_with_data(csv_content)\n\n        cmd = '%s -d , -H \"select count(*) from %s\" -C readwrite' % (Q_EXECUTABLE,tmpfile.name)\n        r, o, e = run_command(cmd)\n        self.assertEqual(r, 0)\n\n        created_qsql_filename = '%s.qsql' % tmpfile.name\n        self.assertTrue(os.path.exists(created_qsql_filename))\n\n        return created_qsql_filename\n\n    def arrays_to_qsql_file_content(self, header_row,cell_list):\n        csv_content = self.arrays_to_csv_file_content(six.b(','),header_row,cell_list)\n        tmpfile = self.create_file_with_data(csv_content)\n\n        cmd = '%s -d , -H \"select count(*) from %s\" -C readwrite' % (Q_EXECUTABLE,tmpfile.name)\n        r, o, e = run_command(cmd)\n        self.assertEqual(r, 0)\n\n        matching_qsql_filename = '%s.qsql' % tmpfile.name\n        f = open(matching_qsql_filename,'rb')\n        qsql_file_bytes = f.read()\n        f.close()\n\n        self.assertEqual(matching_qsql_filename,'%s.qsql' % tmpfile.name)\n\n        return qsql_file_bytes\n\n    def write_file(self,filename,data):\n        f = open(filename,'wb')\n        f.write(data)\n        f.close()\n\n    def create_folder_with_files(self,filename_to_content_dict,prefix, suffix):\n        name = self.random_tmp_filename(prefix,suffix)\n        os.makedirs(name)\n        for filename,content in six.iteritems(filename_to_content_dict):\n            if os.path.sep in filename:\n                os.makedirs('%s/%s' % (name,os.path.split(filename)[0]))\n            f = open(os.path.join(name,filename),'wb')\n            f.write(content)\n            f.close()\n        return name\n\n    def cleanup_folder(self,tmpfolder):\n        if not tmpfolder.startswith(os.path.realpath('/var/tmp')):\n            raise Exception('Guard against accidental folder deletions: %s' % tmpfolder)\n        global DEBUG\n        if not DEBUG:\n            print(\"should have removed tmpfolder %s. Not doing it for the sake of safety. # TODO re-add\" % tmpfolder)\n            pass # os.remove(tmpfolder)\n\n    def cleanup(self, tmpfile):\n        global DEBUG\n        if not DEBUG:\n            os.remove(tmpfile.name)\n\n    def random_tmp_filename(self,prefix,postfix):\n        # TODO Use more robust method for this\n        path = '/var/tmp'\n        return os.path.realpath('%s/%s-%s.%s' % (path,prefix,random.randint(0,1000000000),postfix))\n\n\n\ndef get_sqlite_table_list(c,exclude_qcatalog=True):\n    if exclude_qcatalog:\n        r = c.execute(\"select tbl_name from sqlite_master where type='table' and tbl_name != '_qcatalog'\").fetchall()\n    else:\n        r = c.execute(\"select tbl_name from sqlite_master where type='table'\").fetchall()\n\n    return r\n\nclass SaveToSqliteTests(AbstractQTestCase):\n\n    # Returns a folder with files and a header in each, one column named 'a'\n    def generate_files_in_folder(self,batch_size, file_count):\n        numbers = list(range(1, 1 + batch_size * file_count))\n        numbers_as_text = batch([str(x) for x in numbers], n=batch_size)\n\n        content_list = list(map(six.b, ['a\\n' + \"\\n\".join(x) + '\\n' for x in numbers_as_text]))\n\n        filename_list = list(map(lambda x: 'file-%s' % x, range(file_count)))\n        d = collections.OrderedDict(zip(filename_list, content_list))\n\n        tmpfolder = self.create_folder_with_files(d, 'split-files', 'sqlite-stuff')\n        return (tmpfolder,filename_list)\n\n    # 11074  3.8.2021 10:53  bin/q.py \"select count(*) from xxxx/file-95 left join xxxx/file-96 left join xxxx/file-97 left join xxxx/file-97 left join xxxx/file-98 left join xxxx/*\" -c 1 -C readwrite -A\n    # # fails because it takes qsql files as well\n\n    def test_save_glob_files_to_sqlite(self):\n        BATCH_SIZE = 50\n        FILE_COUNT = 5\n\n        tmpfolder,filename_list = self.generate_files_in_folder(BATCH_SIZE,FILE_COUNT)\n\n        output_sqlite_file = self.random_tmp_filename(\"x\",\"sqlite\")\n\n        cmd = '%s -H \"select count(*) from %s/*\" -c 1 -S %s' % (Q_EXECUTABLE,tmpfolder,output_sqlite_file)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 4)\n\n        c = sqlite3.connect(output_sqlite_file)\n        results = c.execute('select a from file_dash_0').fetchall()\n        self.assertEqual(len(results),BATCH_SIZE*FILE_COUNT)\n        self.assertEqual(sum(map(lambda x:x[0],results)),sum(range(1,BATCH_SIZE*FILE_COUNT+1)))\n        tables = get_sqlite_table_list(c)\n        self.assertEqual(len(tables),1)\n\n        c.close()\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_save_multiple_files_to_sqlite(self):\n        BATCH_SIZE = 50\n        FILE_COUNT = 5\n\n        tmpfolder,filename_list = self.generate_files_in_folder(BATCH_SIZE,FILE_COUNT)\n\n        output_sqlite_file = self.random_tmp_filename(\"x\",\"sqlite\")\n\n        tables_as_str = \" left join \".join([\"%s/%s\" % (tmpfolder,x) for x in filename_list])\n        cmd = '%s -H \"select count(*) from %s\" -c 1 -S %s' % (Q_EXECUTABLE,tables_as_str,output_sqlite_file)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 4)\n\n        c = sqlite3.connect(output_sqlite_file)\n\n        tables = get_sqlite_table_list(c)\n        self.assertEqual(len(tables), FILE_COUNT)\n\n        for i in range(FILE_COUNT):\n            results = c.execute('select a from file_dash_%s' % i).fetchall()\n            self.assertEqual(len(results),BATCH_SIZE)\n            self.assertEqual(sum(map(lambda x:x[0],results)),sum(range(1+i*BATCH_SIZE,1+(i+1)*BATCH_SIZE)))\n\n        c.close()\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_save_multiple_files_to_sqlite_without_duplicates(self):\n        BATCH_SIZE = 50\n        FILE_COUNT = 5\n\n        tmpfolder,filename_list = self.generate_files_in_folder(BATCH_SIZE,FILE_COUNT)\n\n        output_sqlite_file = self.random_tmp_filename(\"x\",\"sqlite\")\n\n        tables_as_str = \" left join \".join([\"%s/%s\" % (tmpfolder,x) for x in filename_list])\n\n        # duplicate the left-joins for all the files, so the query will contain each filename twice\n        tables_as_str = \"%s left join %s\" % (tables_as_str,tables_as_str)\n\n        cmd = '%s -H \"select count(*) from %s\" -c 1 -S %s' % (Q_EXECUTABLE,tables_as_str,output_sqlite_file)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 4)\n\n        c = sqlite3.connect(output_sqlite_file)\n\n        tables = get_sqlite_table_list(c)\n        # total table count should still be FILE_COUNT, even with the duplications\n        self.assertEqual(len(tables), FILE_COUNT)\n\n        for i in range(FILE_COUNT):\n            results = c.execute('select a from file_dash_%s' % i).fetchall()\n            self.assertEqual(len(results),BATCH_SIZE)\n            self.assertEqual(sum(map(lambda x:x[0],results)),sum(range(1+i*BATCH_SIZE,1+(i+1)*BATCH_SIZE)))\n\n        c.close()\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_sqlite_file_is_not_created_if_some_table_does_not_exist(self):\n        BATCH_SIZE = 50\n        FILE_COUNT = 5\n\n        tmpfolder,filename_list = self.generate_files_in_folder(BATCH_SIZE,FILE_COUNT)\n\n        output_sqlite_file = self.random_tmp_filename(\"x\",\"sqlite\")\n\n        tables_as_str = \" left join \".join([\"%s/%s\" % (tmpfolder,x) for x in filename_list])\n\n        tables_as_str = tables_as_str + ' left join %s/non_existent_table' % (tmpfolder)\n\n        cmd = '%s -H \"select count(*) from %s\" -c 1 -S %s' % (Q_EXECUTABLE,tables_as_str,output_sqlite_file)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 30)\n        self.assertEqual(len(e), 2)\n        self.assertEqual(e[0],six.b(\"Going to save data into a disk database: %s\" % output_sqlite_file))\n        self.assertEqual(e[1],six.b(\"No files matching '%s/non_existent_table' have been found\" % tmpfolder))\n\n        self.assertTrue(not os.path.exists(output_sqlite_file))\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_recurring_glob_and_separate_files_in_same_query_when_writing_to_sqlite(self):\n        BATCH_SIZE = 50\n        FILE_COUNT = 5\n\n        tmpfolder,filename_list = self.generate_files_in_folder(BATCH_SIZE,FILE_COUNT)\n\n        output_sqlite_file = self.random_tmp_filename(\"x\",\"sqlite\")\n\n        tables_as_str = \" left join \".join([\"%s/%s\" % (tmpfolder,x) for x in filename_list])\n        # The same files are left-joined in the query as an additional \"left join <folder>/*\". This should create an additional table\n        # in the sqlite file, with all the data in it\n        cmd = '%s -H \"select count(*) from %s left join %s/*\" -c 1 -S %s' % (Q_EXECUTABLE,tables_as_str,tmpfolder,output_sqlite_file)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 4)\n\n        c = sqlite3.connect(output_sqlite_file)\n\n        tables = get_sqlite_table_list(c)\n        # plus the additional table from the glob\n        self.assertEqual(len(tables), FILE_COUNT+1)\n\n        # check all the per-file tables\n        for i in range(FILE_COUNT):\n            results = c.execute('select a from file_dash_%s' % i).fetchall()\n            self.assertEqual(len(results),BATCH_SIZE)\n            self.assertEqual(sum(map(lambda x:x[0],results)),sum(range(1+i*BATCH_SIZE,1+(i+1)*BATCH_SIZE)))\n\n        # ensure the glob-based table exists, with an _2 added to the name, as the original \"file_dash_0\" already exists in the sqlite db\n        results = c.execute('select a from file_dash_0_2').fetchall()\n        self.assertEqual(len(results),FILE_COUNT*BATCH_SIZE)\n        self.assertEqual(sum(map(lambda x:x[0],results)),sum(range(1,1+FILE_COUNT*BATCH_SIZE)))\n        c.close()\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_empty_sqlite_handling(self):\n        fn = self.generate_tmpfile_name(\"empty\",\".sqlite\")\n\n        c = sqlite3.connect(fn)\n        c.execute('create table x (a int)').fetchall()\n        c.execute('drop table x').fetchall()\n        c.close()\n\n        cmd = '%s \"select * from %s\"' % (Q_EXECUTABLE,fn)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,88)\n        self.assertEqual(len(o),0)\n        self.assertEqual(len(e),1)\n        self.assertEqual(e[0],six.b('sqlite file %s has no tables' % fn))\n\n    def test_storing_to_disk_too_many_qsql_files(self):\n        BATCH_SIZE = 10\n        MAX_ATTACHED_DBS = 5\n        FILE_COUNT = MAX_ATTACHED_DBS + 4\n\n        numbers_as_text = batch([str(x) for x in range(1, 1 + BATCH_SIZE * FILE_COUNT)], n=BATCH_SIZE)\n\n        content_list = map(six.b, [\"\\n\".join(x) for x in numbers_as_text])\n\n        filename_list = list(map(lambda x: 'file-%s' % x, range(FILE_COUNT)))\n        d = collections.OrderedDict(zip(filename_list, content_list))\n\n        tmpfolder = self.create_folder_with_files(d, 'split-files', 'attach-limit')\n\n        for fn in filename_list:\n            cmd = '%s -c 1 \"select count(*) from %s/%s\" -C readwrite' % (Q_EXECUTABLE,tmpfolder, fn)\n            retcode, o, e = run_command(cmd)\n\n            self.assertEqual(retcode, 0)\n\n        output_sqlite_file = self.generate_tmpfile_name(\"many-sqlites\",\".sqlite\")\n\n        table_refs = list(['select * from %s/%s.qsql' % (tmpfolder,x) for x in filename_list])\n        table_refs_str = \" UNION ALL \".join(table_refs)\n        # Limit max attached dbs according to the parameter (must be below the hardcoded sqlite limit, which is 10 when having a standard version compiled)\n        cmd = '%s \"select * from (%s)\" -S %s --max-attached-sqlite-databases=%s' % (Q_EXECUTABLE,table_refs_str,output_sqlite_file,MAX_ATTACHED_DBS)\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(o),0)\n        self.assertEqual(len(e),4)\n\n        c = sqlite3.connect(output_sqlite_file)\n        tables_results = c.execute(\"select tbl_name from sqlite_master where type='table'\").fetchall()\n        table_names = list(sorted([x[0] for x in tables_results]))\n        self.assertEqual(len(table_names),FILE_COUNT)\n\n        for i,tn in enumerate(table_names):\n            self.assertEqual(tn,'file_dash_%s' % i)\n\n            table_content = c.execute('select * from %s' % tn).fetchall()\n            self.assertEqual(len(table_content),BATCH_SIZE)\n\n            cmd = '%s \"select * from %s:::%s\"' % (Q_EXECUTABLE,output_sqlite_file,tn)\n            retcode, o, e = run_command(cmd)\n            self.assertEqual(retcode, 0)\n            self.assertEqual(len(e),0)\n            self.assertEqual(len(o),BATCH_SIZE)\n            self.assertEqual(o,list([six.b(str(x)) for x in range(1 + i*BATCH_SIZE,1+(i+1)*BATCH_SIZE)]))\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_storing_to_disk_too_many_sqlite_files(self):\n        # a variation of test_storing_to_disk_too_many_qsql_files, which deletes the qcatalog file from the caches,\n        # so they'll be just regular sqlite files\n\n        BATCH_SIZE = 10\n        MAX_ATTACHED_DBS = 5\n        FILE_COUNT = MAX_ATTACHED_DBS + 4\n\n        numbers_as_text = batch([str(x) for x in range(1, 1 + BATCH_SIZE * FILE_COUNT)], n=BATCH_SIZE)\n\n        content_list = map(six.b, [\"\\n\".join(x) for x in numbers_as_text])\n\n        filename_list = list(map(lambda x: 'file-%s' % x, range(FILE_COUNT)))\n        d = collections.OrderedDict(zip(filename_list, content_list))\n\n        tmpfolder = self.create_folder_with_files(d, 'split-files', 'attach-limit')\n\n        for fn in filename_list:\n            cmd = '%s -c 1 \"select count(*) from %s/%s\" -C readwrite' % (Q_EXECUTABLE,tmpfolder, fn)\n            retcode, o, e = run_command(cmd)\n\n            self.assertEqual(retcode, 0)\n\n            c = sqlite3.connect('%s/%s.qsql' % (tmpfolder,fn))\n            c.execute('drop table _qcatalog').fetchall()\n            c.close()\n            os.rename('%s/%s.qsql' % (tmpfolder,fn),'%s/%s.sqlite' % (tmpfolder,fn))\n\n        output_sqlite_file = self.generate_tmpfile_name(\"many-sqlites\",\".sqlite\")\n\n        table_refs = list(['select * from %s/%s.sqlite' % (tmpfolder,x) for x in filename_list])\n        table_refs_str = \" UNION ALL \".join(table_refs)\n        # Limit max attached dbs according to the parameter (must be below the hardcoded sqlite limit, which is 10 when having a standard version compiled)\n        cmd = '%s \"select * from (%s)\" -S %s --max-attached-sqlite-databases=%s' % (Q_EXECUTABLE,table_refs_str,output_sqlite_file,MAX_ATTACHED_DBS)\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(o),0)\n        self.assertEqual(len(e),4)\n\n        c = sqlite3.connect(output_sqlite_file)\n        tables_results = c.execute(\"select tbl_name from sqlite_master where type='table'\").fetchall()\n        table_names = list(sorted([x[0] for x in tables_results]))\n        self.assertEqual(len(table_names),FILE_COUNT)\n\n        for i,tn in enumerate(table_names):\n            self.assertEqual(tn,'file_dash_%s' % i)\n\n            table_content = c.execute('select * from %s' % tn).fetchall()\n            self.assertEqual(len(table_content),BATCH_SIZE)\n\n            cmd = '%s \"select * from %s:::%s\"' % (Q_EXECUTABLE,output_sqlite_file,tn)\n            retcode, o, e = run_command(cmd)\n            self.assertEqual(retcode, 0)\n            self.assertEqual(len(e),0)\n            self.assertEqual(len(o),BATCH_SIZE)\n            self.assertEqual(o,list([six.b(str(x)) for x in range(1 + i*BATCH_SIZE,1+(i+1)*BATCH_SIZE)]))\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_storing_to_disk_too_many_sqlite_files__over_the_sqlite_limit(self):\n        # a variation of test_storing_to_disk_too_many_sqlite_files, but with a limit above the sqlite hardcoded limit\n        MAX_ATTACHED_DBS = 20 # standard sqlite limit is 10, so q should throw an error\n\n        BATCH_SIZE = 10\n        FILE_COUNT = MAX_ATTACHED_DBS + 4\n\n        numbers_as_text = batch([str(x) for x in range(1, 1 + BATCH_SIZE * FILE_COUNT)], n=BATCH_SIZE)\n\n        content_list = map(six.b, [\"\\n\".join(x) for x in numbers_as_text])\n\n        filename_list = list(map(lambda x: 'file-%s' % x, range(FILE_COUNT)))\n        d = collections.OrderedDict(zip(filename_list, content_list))\n\n        tmpfolder = self.create_folder_with_files(d, 'split-files', 'attach-limit')\n\n        for fn in filename_list:\n            cmd = '%s -c 1 \"select count(*) from %s/%s\" -C readwrite' % (Q_EXECUTABLE,tmpfolder, fn)\n            retcode, o, e = run_command(cmd)\n\n            self.assertEqual(retcode, 0)\n\n            c = sqlite3.connect('%s/%s.qsql' % (tmpfolder,fn))\n            c.execute('drop table _qcatalog').fetchall()\n            c.close()\n            os.rename('%s/%s.qsql' % (tmpfolder,fn),'%s/%s.sqlite' % (tmpfolder,fn))\n\n        output_sqlite_file = self.generate_tmpfile_name(\"many-sqlites\",\".sqlite\")\n\n        table_refs = list(['select * from %s/%s.sqlite' % (tmpfolder,x) for x in filename_list])\n        table_refs_str = \" UNION ALL \".join(table_refs)\n        # Limit max attached dbs according to the parameter (must be below the hardcoded sqlite limit, which is 10 when having a standard version compiled)\n        cmd = '%s \"select * from (%s)\" -S %s --max-attached-sqlite-databases=%s' % (Q_EXECUTABLE,table_refs_str,output_sqlite_file,MAX_ATTACHED_DBS)\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode,89)\n        self.assertEqual(len(o),0)\n        self.assertEqual(len(e),2)\n        self.assertTrue(e[0].startswith(six.b('Going to save data into')))\n        self.assertTrue(e[1].startswith(six.b('There are too many attached databases. Use a proper --max-attached-sqlite-databases parameter which is below the maximum')))\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_qtable_name_normalization__starting_with_a_digit(self):\n        numbers = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 101)]\n\n        header = [six.b('aa'), six.b('bb'), six.b('cc')]\n\n        base_filename_with_digits = '010'\n\n        new_tmp_folder = self.create_folder_with_files({\n            base_filename_with_digits : self.arrays_to_csv_file_content(six.b(','),header,numbers)\n        },prefix='xx',suffix='digits')\n\n        effective_filename = '%s/010' % new_tmp_folder\n\n        output_sqlite_filename = self.generate_tmpfile_name(\"starting-with-digit\",\".sqlite\")\n        cmd = '%s -d , -H \"select count(aa),count(bb),count(cc) from %s\" -S %s' % (Q_EXECUTABLE,effective_filename,output_sqlite_filename)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(o),0)\n        self.assertEqual(len(e),4)\n\n        c = sqlite3.connect(output_sqlite_filename)\n        results = c.execute('select aa,bb,cc from t_%s' % base_filename_with_digits).fetchall()\n        self.assertEqual(results,list([(x,x,x) for x in range(1,101)]))\n        c.close()\n\n        self.cleanup_folder(new_tmp_folder)\n\n    def test_qtable_name_normalization(self):\n        x = [six.b(a) for a in map(str, range(1, 101))]\n        large_file_data = six.b(\"val\\n\") + six.b(\"\\n\").join(x)\n        tmpfile = self.create_file_with_data(large_file_data)\n\n        tmpfile_folder = os.path.dirname(tmpfile.name)\n        tmpfile_basename = os.path.basename(tmpfile.name)\n\n        cmd = 'cd %s && %s -c 1 -H -D , -O \"select a.val,b.val from %s a cross join ./%s b on (a.val = b.val * 2)\"' % (tmpfile_folder,Q_EXECUTABLE,tmpfile_basename,tmpfile_basename)\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 51)\n\n        evens = list(filter(lambda x: x%2 == 0,range(1,101)))\n        expected_result_rows = [six.b('val,val')] + [six.b('%d,%d' % (x,x / 2)) for x in evens]\n        self.assertEqual(o,expected_result_rows)\n\n    def test_qtable_name_normalization2(self):\n        cmd = '%s \"select * from\"' % Q_EXECUTABLE\n\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 118)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(e[0],six.b('FROM/JOIN is missing a table name after it'))\n\n    def test_qtable_name_normalization3(self):\n        # with a space after the from\n        cmd = '%s \"select * from \"' % Q_EXECUTABLE\n\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 118)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(e[0],six.b('FROM/JOIN is missing a table name after it'))\n\n    def test_save_multiple_files_to_sqlite_while_caching_them(self):\n        BATCH_SIZE = 50\n        FILE_COUNT = 5\n\n        tmpfolder,filename_list = self.generate_files_in_folder(BATCH_SIZE,FILE_COUNT)\n\n        output_sqlite_file = self.random_tmp_filename(\"x\",\"sqlite\")\n\n        tables_as_str = \" left join \".join([\"%s/%s\" % (tmpfolder,x) for x in filename_list])\n        cmd = '%s -H \"select count(*) from %s\" -c 1 -S %s -C readwrite' % (Q_EXECUTABLE,tables_as_str,output_sqlite_file)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 4)\n\n        c = sqlite3.connect(output_sqlite_file)\n\n        tables = get_sqlite_table_list(c)\n        self.assertEqual(len(tables), FILE_COUNT)\n\n        for i,filename in enumerate(filename_list):\n            matching_table_name = 'file_dash_%s' % i\n\n            results = c.execute('select a from %s' % matching_table_name).fetchall()\n            self.assertEqual(len(results),BATCH_SIZE)\n            self.assertEqual(sum(map(lambda x:x[0],results)),sum(range(1+i*BATCH_SIZE,1+(i+1)*BATCH_SIZE)))\n\n            # check actual resulting qsql file for the file\n            cmd = '%s -c 1 -H \"select a from %s/%s\"' % (Q_EXECUTABLE,tmpfolder,filename)\n            retcode, o, e = run_command(cmd)\n\n            self.assertEqual(retcode, 0)\n            self.assertEqual(len(o), BATCH_SIZE)\n            self.assertEqual(sum(map(int,o)),sum(range(1+i*BATCH_SIZE,1+(i+1)*BATCH_SIZE)))\n            self.assertEqual(len(e), 0)\n\n            # check analysis returns proper file-with-unused-qsql for each file, since by default `-C none` which means don't read the cache\n            # even if it exists\n            cmd = '%s -c 1 -H \"select a from %s/%s\" -A' % (Q_EXECUTABLE,tmpfolder,filename)\n            retcode, o, e = run_command(cmd)\n\n            self.assertEqual(retcode, 0)\n            self.assertEqual(len(o), 5)\n            self.assertEqual(o,[\n                six.b('Table: %s/file-%s' % (tmpfolder,i)),\n                six.b('  Sources:'),\n                six.b('    source_type: file-with-unused-qsql source: %s/file-%s' % (tmpfolder,i)),\n                six.b('  Fields:'),\n                six.b('    `a` - int')\n            ])\n\n            cmd = '%s -c 1 -H \"select a from %s/%s\" -A -C read' % (Q_EXECUTABLE,tmpfolder,filename)\n            retcode, o, e = run_command(cmd)\n\n            self.assertEqual(retcode, 0)\n            self.assertEqual(len(o), 5)\n            self.assertEqual(o,[\n                six.b('Table: %s/file-%s' % (tmpfolder,i)),\n                six.b('  Sources:'),\n                six.b('    source_type: qsql-file-with-original source: %s/file-%s.qsql' % (tmpfolder,i)),\n                six.b('  Fields:'),\n                six.b('    `a` - int')\n            ])\n\n            # check qsql file is readable directly through q\n            cmd = '%s -c 1 -H \"select a from %s/%s.qsql\"' % (Q_EXECUTABLE,tmpfolder,filename)\n            retcode, o, e = run_command(cmd)\n\n            self.assertEqual(retcode, 0)\n            self.assertEqual(len(o), BATCH_SIZE)\n            self.assertEqual(sum(map(int,o)),sum(range(1+i*BATCH_SIZE,1+(i+1)*BATCH_SIZE)))\n            self.assertEqual(len(e), 0)\n\n            # check analysis returns proper qsql-with-original for each file when running directly against the qsql file\n            cmd = '%s -c 1 -H \"select a from %s/%s.qsql\" -A' % (Q_EXECUTABLE,tmpfolder,filename)\n            retcode, o, e = run_command(cmd)\n\n            self.assertEqual(retcode, 0)\n            self.assertEqual(len(o), 5)\n            self.assertEqual(o,[\n                six.b('Table: %s/file-%s.qsql' % (tmpfolder,i)),\n                six.b('  Sources:'),\n                six.b('    source_type: qsql-file source: %s/file-%s.qsql' % (tmpfolder,i)),\n                six.b('  Fields:'),\n                six.b('    `a` - int')\n            ])\n        c.close()\n\n        import glob\n        filename_list_with_qsql = list(map(lambda x: x+'.qsql',filename_list))\n\n        files_in_folder = glob.glob('%s/*' % tmpfolder)\n        regular_files,qsql_files = partition(lambda x: x.endswith('.qsql'),files_in_folder)\n\n        self.assertEqual(len(files_in_folder),2*FILE_COUNT)\n        self.assertEqual(sorted(list(map(os.path.basename,regular_files))),sorted(list(map(os.path.basename,filename_list))))\n        self.assertEqual(sorted(list(map(os.path.basename,qsql_files))),sorted(list(map(os.path.basename,filename_list_with_qsql))))\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_globs_ignore_matching_qsql_files(self):\n        BATCH_SIZE = 10\n        FILE_COUNT = 5\n\n        tmpfolder,filename_list = self.generate_files_in_folder(BATCH_SIZE,FILE_COUNT)\n\n        tables_as_str = \" left join \".join([\"%s/%s\" % (tmpfolder,x) for x in filename_list])\n        cmd = '%s -H \"select count(*) from %s\" -c 1 -C readwrite' % (Q_EXECUTABLE,tables_as_str)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b(str(pow(BATCH_SIZE,FILE_COUNT))))\n\n        cmd = '%s -H \"select a from %s/*\" -c 1 -C read' % (Q_EXECUTABLE,tmpfolder)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), BATCH_SIZE*FILE_COUNT)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(sum(map(int,o)),sum(range(1,1+BATCH_SIZE*FILE_COUNT)))\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_error_on_reading_from_multi_table_sqlite_without_explicit_table_name(self):\n        BATCH_SIZE = 50\n        FILE_COUNT = 5\n\n        tmpfolder,filename_list = self.generate_files_in_folder(BATCH_SIZE,FILE_COUNT)\n\n        output_sqlite_file = self.random_tmp_filename(\"x\",\"sqlite\")\n\n        tables_as_str = \" left join \".join([\"%s/%s\" % (tmpfolder,x) for x in filename_list])\n        cmd = '%s -H \"select count(*) from %s\" -c 1 -S %s' % (Q_EXECUTABLE,tables_as_str,output_sqlite_file)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 4)\n\n\n        cmd = '%s -H \"select count(*) from %s\"' % (Q_EXECUTABLE,output_sqlite_file)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 87)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(e[0],six.b(\"Could not autodetect table name in sqlite file %s . Existing tables: file_dash_0,file_dash_1,file_dash_2,file_dash_3,file_dash_4\" % output_sqlite_file))\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_error_on_trying_to_specify_an_explicit_non_existent_qsql_file(self):\n        cmd = '%s -H \"select count(*) from /non-existent-folder/non-existent.qsql:::mytable\"' % (Q_EXECUTABLE)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 30)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(e[0],six.b(\"Could not find file /non-existent-folder/non-existent.qsql\"))\n\n    def test_error_on_providing_a_non_qsql_file_when_specifying_an_explicit_table(self):\n        data = six.b(\"\\x1f\\x8b\\x08\\x00\\tZ\\x0ea\\x00\\x03\\xed\\x93\\xdd\\n\\xc20\\x0cF\\xf3(}\\x01ij\\x93\\xf6y:\\xd9P\\x10)\\xb3\\xbe\\xbf\\x9d\\x1d\\xbbQ\\xc6\\x06F\\x10rn\\xbe\\x9b\\xd0\\xfc\\x1c\\x9a-\\x88\\x83\\x88\\x91\\xd9\\xbc2\\xb4\\xc4#\\xb5\\x9c1\\x8e\\x1czb\\x8a\\xd1\\x19t\\xdeS\\x00\\xc3\\xf2\\xa3\\x01<\\xee%\\x8du\\x94s\\x1a\\xfbk\\xd7\\xdf\\x0e\\xa9\\x94Kz\\xaf\\xabe\\xc3\\xb0\\xf2\\xce\\xbc\\xc7\\x92\\x7fB\\xb6\\x1fv\\xfd2\\xf5\\x1e\\x81h\\xa3\\xff\\x10'\\xff\\x8c\\x04\\x06\\xc5'\\x03\\xf5oO\\xe2=v\\xf9o\\xff\\x9f\\xd1\\xa9\\xff_\\x90m'\\xdec\\x9f\\x7f\\x9c\\xfc\\xd7T\\xff\\x8a\\xa2(\\x92<\\x01WY\\x0c\\x06\\x00\\x0c\\x00\\x00\")\n        tmpfilename = self.random_tmp_filename('xx','yy')\n        f = open(tmpfilename,'wb')\n        f.write(data)\n        f.close()\n\n        cmd = '%s -H \"select count(*) from %s:::mytable1\"' % (Q_EXECUTABLE,tmpfilename)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 95)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(e[0],six.b(\"Cannot detect the type of table %s:::mytable1\" % tmpfilename))\n\n    def test_error_on_providing_a_non_qsql_file_when_not_specifying_an_explicit_table(self):\n        data = six.b(\"\\x1f\\x8b\\x08\\x00\\tZ\\x0ea\\x00\\x03\\xed\\x93\\xdd\\n\\xc20\\x0cF\\xf3(}\\x01ij\\x93\\xf6y:\\xd9P\\x10)\\xb3\\xbe\\xbf\\x9d\\x1d\\xbbQ\\xc6\\x06F\\x10rn\\xbe\\x9b\\xd0\\xfc\\x1c\\x9a-\\x88\\x83\\x88\\x91\\xd9\\xbc2\\xb4\\xc4#\\xb5\\x9c1\\x8e\\x1czb\\x8a\\xd1\\x19t\\xdeS\\x00\\xc3\\xf2\\xa3\\x01<\\xee%\\x8du\\x94s\\x1a\\xfbk\\xd7\\xdf\\x0e\\xa9\\x94Kz\\xaf\\xabe\\xc3\\xb0\\xf2\\xce\\xbc\\xc7\\x92\\x7fB\\xb6\\x1fv\\xfd2\\xf5\\x1e\\x81h\\xa3\\xff\\x10'\\xff\\x8c\\x04\\x06\\xc5'\\x03\\xf5oO\\xe2=v\\xf9o\\xff\\x9f\\xd1\\xa9\\xff_\\x90m'\\xdec\\x9f\\x7f\\x9c\\xfc\\xd7T\\xff\\x8a\\xa2(\\x92<\\x01WY\\x0c\\x06\\x00\\x0c\\x00\\x00\")\n        tmpfilename = self.random_tmp_filename('xx','yy')\n        f = open(tmpfilename,'wb')\n        f.write(data)\n        f.close()\n\n        cmd = '%s -H \"select count(*) from %s\"' % (Q_EXECUTABLE,tmpfilename)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 59)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n        self.assertTrue(e[0].startswith(six.b(\"Could not parse the input. Please make sure to set the proper -w input-wrapping parameter for your input, and that you use the proper input encoding (-e). Error:\")))\n\nclass OldSaveDbToDiskTests(AbstractQTestCase):\n\n    def test_join_with_stdin_and_save(self):\n        x = [six.b(a) for a in map(str,range(1,101))]\n        large_file_data = six.b(\"val\\n\") + six.b(\"\\n\").join(x)\n        tmpfile = self.create_file_with_data(large_file_data)\n        tmpfile_expected_table_name = os.path.basename(tmpfile.name)\n\n        disk_db_filename = self.random_tmp_filename('save-to-db','sqlite')\n\n        cmd = '(echo id ; seq 1 2 10) | ' + Q_EXECUTABLE + ' -c 1 -H -O \"select stdin.*,f.* from - stdin left join %s f on (stdin.id * 10 = f.val)\" -S %s' % \\\n            (tmpfile.name,disk_db_filename)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 4)\n\n        self.assertEqual(e[0],six.b('Going to save data into a disk database: %s' % disk_db_filename))\n        self.assertTrue(e[1].startswith(six.b('Data has been saved into %s . Saving has taken ' % disk_db_filename)))\n        self.assertEqual(e[2],six.b('Query to run on the database: select stdin.*,f.* from data_stream_stdin stdin left join %s f on (stdin.id * 10 = f.val);' % \\\n                         tmpfile_expected_table_name))\n        self.assertEqual(e[3],six.b('You can run the query directly from the command line using the following command: echo \"select stdin.*,f.* from data_stream_stdin stdin left join %s f on (stdin.id * 10 = f.val)\" | sqlite3 %s' %\n                                    (tmpfile_expected_table_name,disk_db_filename)))\n\n        P = re.compile(six.b(\"^Query to run on the database: (?P<query_to_run_on_db>.*)$\"))\n        m = P.search(e[2])\n        query_to_run_on_db = m.groupdict()['query_to_run_on_db']\n\n        self.assertTrue(os.path.exists(disk_db_filename))\n\n        # validate disk db content natively\n        c = sqlite3.connect(disk_db_filename)\n        c.row_factory = sqlite_dict_factory\n        t0_results = c.execute('select * from data_stream_stdin').fetchall()\n        self.assertEqual(len(t0_results),5)\n        self.assertEqual(sorted(list(t0_results[0].keys())), ['id'])\n        self.assertEqual(list(map(lambda x:x['id'],t0_results)),[1,3,5,7,9])\n        t1_results = c.execute('select * from %s' % tmpfile_expected_table_name).fetchall()\n        self.assertEqual(len(t1_results),100)\n        self.assertEqual(sorted(list(t1_results[0].keys())), ['val'])\n        self.assertEqual(\"\\n\".join(list(map(lambda x:str(x['val']),t1_results))),\"\\n\".join(map(str,range(1,101))))\n\n        query_results = c.execute(query_to_run_on_db.decode('utf-8')).fetchall()\n\n        self.assertEqual(query_results[0],{ 'id': 1 , 'val': 10})\n        self.assertEqual(query_results[1],{ 'id': 3 , 'val': 30})\n        self.assertEqual(query_results[2],{ 'id': 5 , 'val': 50})\n        self.assertEqual(query_results[3],{ 'id': 7 , 'val': 70})\n        self.assertEqual(query_results[4],{ 'id': 9 , 'val': 90})\n\n        self.cleanup(tmpfile)\n\n    def test_join_with_qsql_file(self):\n        numbers1 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 10001)]\n        numbers2 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 11)]\n\n        header = [six.b('aa'), six.b('bb'), six.b('cc')]\n\n        new_tmp_folder = self.create_folder_with_files({\n            'some_csv_file': self.arrays_to_csv_file_content(six.b(','),header,numbers1),\n            'some_qsql_database.qsql' : self.arrays_to_qsql_file_content(header,numbers2)\n        },prefix='xx',suffix='yy')\n\n        effective_filename1 = '%s/some_csv_file' % new_tmp_folder\n        effective_filename2 = '%s/some_qsql_database.qsql' % new_tmp_folder\n\n        cmd = Q_EXECUTABLE + ' -d , -H \"select sum(large_file.aa),sum(small_file.aa) from %s large_file left join %s small_file on (small_file.aa == large_file.bb)\"' % \\\n              (effective_filename1,effective_filename2)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(o),1)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0],six.b('50005000,55'))\n\n    # TODO RLRL Check if needed anymore\n\n    # def test_creation_of_qsql_database(self):\n    #     numbers = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 11)]\n    #     header = [six.b('aa'), six.b('bb'), six.b('cc')]\n    #\n    #     qsql_filename = self.create_qsql_file_with_content_and_return_filename(header,numbers)\n    #\n    #     conn = sqlite3.connect(qsql_filename)\n    #     qcatalog = conn.execute('select temp_table_name,source_type,source from _qcatalog').fetchall()\n    #     print(qcatalog)\n    #\n    #     cmd = '%s \"select count(*) from %s\" -A' % (Q_EXECUTABLE,qsql_filename)\n    #     retcode, o, e = run_command(cmd)\n    #     print(o)\n\n    def test_join_with_qsql_file_and_save(self):\n        numbers1 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 10001)]\n        numbers2 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 11)]\n\n        header = [six.b('aa'), six.b('bb'), six.b('cc')]\n\n        saved_qsql_with_multiple_tables = self.generate_tmpfile_name(suffix='.qsql')\n\n        new_tmp_folder = self.create_folder_with_files({\n            'some_csv_file': self.arrays_to_csv_file_content(six.b(','),header,numbers1),\n            'some_qsql_database' : self.arrays_to_csv_file_content(six.b(','),header,numbers2)\n        },prefix='xx',suffix='yy')\n        cmd = '%s -d , -H \"select count(*) from %s/some_qsql_database\" -C readwrite' % (Q_EXECUTABLE,new_tmp_folder)\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode,0)\n        os.remove('%s/some_qsql_database' % new_tmp_folder)\n\n        effective_filename1 = '%s/some_csv_file' % new_tmp_folder\n        effective_filename2 = '%s/some_qsql_database.qsql' % new_tmp_folder\n\n        cmd = Q_EXECUTABLE + ' -d , -H \"select sum(large_file.aa),sum(small_file.aa) from %s large_file left join %s small_file on (small_file.aa == large_file.bb)\" -S %s' % \\\n              (effective_filename1,effective_filename2,saved_qsql_with_multiple_tables)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n\n        conn = sqlite3.connect(saved_qsql_with_multiple_tables)\n        c1 = conn.execute('select count(*) from some_csv_file').fetchall()\n        c2 = conn.execute('select count(*) from some_qsql_database').fetchall()\n\n        self.assertEqual(c1[0][0],10000)\n        self.assertEqual(c2[0][0],10)\n\n\n    def test_saving_to_db_with_same_basename_files(self):\n        numbers1 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 10001)]\n        numbers2 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 11)]\n\n        header = [six.b('aa'), six.b('bb'), six.b('cc')]\n\n        qsql_with_multiple_tables = self.generate_tmpfile_name(suffix='.qsql')\n\n        new_tmp_folder = self.create_folder_with_files({\n            'filename1': self.arrays_to_csv_file_content(six.b(','),header,numbers1),\n            'otherfolder/filename1' : self.arrays_to_csv_file_content(six.b(','),header,numbers2)\n        },prefix='xx',suffix='yy')\n\n        effective_filename1 = '%s/filename1' % new_tmp_folder\n        effective_filename2 = '%s/otherfolder/filename1' % new_tmp_folder\n\n        expected_stored_table_name1 = 'filename1'\n        expected_stored_table_name2 = 'filename1_2'\n\n        cmd = Q_EXECUTABLE + ' -d , -H \"select sum(large_file.aa),sum(large_file.bb),sum(large_file.cc) from %s small_file left join %s large_file on (large_file.aa == small_file.bb)\" -S %s' % \\\n              (effective_filename1,effective_filename2,qsql_with_multiple_tables)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 4)\n        self.assertEqual(e[0], six.b('Going to save data into a disk database: %s' % qsql_with_multiple_tables))\n        self.assertTrue(e[1].startswith(six.b('Data has been saved into %s . Saving has taken' % qsql_with_multiple_tables)))\n        self.assertEqual(e[2],six.b('Query to run on the database: select sum(large_file.aa),sum(large_file.bb),sum(large_file.cc) from %s small_file left join %s large_file on (large_file.aa == small_file.bb);' % \\\n                                    (expected_stored_table_name1,expected_stored_table_name2)))\n        self.assertEqual(e[3],six.b('You can run the query directly from the command line using the following command: echo \"select sum(large_file.aa),sum(large_file.bb),sum(large_file.cc) from %s small_file left join %s large_file on (large_file.aa == small_file.bb)\" | sqlite3 %s' % \\\n                                    (expected_stored_table_name1,expected_stored_table_name2,qsql_with_multiple_tables)))\n\n        #self.assertTrue(False) # pxpx - need to actually test reading from the saved db file\n        conn = sqlite3.connect(qsql_with_multiple_tables)\n        c1 = conn.execute('select count(*) from filename1').fetchall()\n        c2 = conn.execute('select count(*) from filename1_2').fetchall()\n\n        self.assertEqual(c1[0][0],10000)\n        self.assertEqual(c2[0][0],10)\n\n\n    def test_error_when_not_specifying_table_name_in_multi_table_qsql(self):\n        numbers1 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 10001)]\n        numbers2 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 11)]\n\n        header = [six.b('aa'), six.b('bb'), six.b('cc')]\n\n        qsql_with_multiple_tables = self.generate_tmpfile_name(suffix='.qsql')\n\n        new_tmp_folder = self.create_folder_with_files({\n            'filename1': self.arrays_to_csv_file_content(six.b(','),header,numbers1),\n            'otherfolder/filename1' : self.arrays_to_csv_file_content(six.b(','),header,numbers2)\n        },prefix='xx',suffix='yy')\n\n        effective_filename1 = '%s/filename1' % new_tmp_folder\n        effective_filename2 = '%s/otherfolder/filename1' % new_tmp_folder\n\n        expected_stored_table_name1 = 'filename1'\n        expected_stored_table_name2 = 'filename1_2'\n\n        cmd = Q_EXECUTABLE + ' -d , -H \"select sum(large_file.aa),sum(large_file.bb),sum(large_file.cc) from %s small_file left join %s large_file on (large_file.aa == small_file.bb)\" -S %s' % \\\n              (effective_filename1,effective_filename2,qsql_with_multiple_tables)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 4)\n\n        # Actual tests\n\n        cmd = '%s \"select count(*) from %s\"' % (Q_EXECUTABLE,qsql_with_multiple_tables)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 87)\n        self.assertEqual(len(o),0)\n        self.assertEqual(len(e),1)\n        self.assertEqual(e[0],six.b('Could not autodetect table name in sqlite file %s . Existing tables: %s,%s' % (qsql_with_multiple_tables,expected_stored_table_name1,expected_stored_table_name2)))\n\n    def test_error_when_not_specifying_table_name_in_multi_table_sqlite(self):\n        sqlite_with_multiple_tables = self.generate_tmpfile_name(suffix='.sqlite')\n\n        c = sqlite3.connect(sqlite_with_multiple_tables)\n        c.execute('create table my_table_1 (x int, y int)').fetchall()\n        c.execute('create table my_table_2 (x int, y int)').fetchall()\n        c.close()\n\n        cmd = '%s \"select count(*) from %s\"' % (Q_EXECUTABLE,sqlite_with_multiple_tables)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 87)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n        print(e[0])\n        self.assertEqual(e[0],six.b('Could not autodetect table name in sqlite file %s . Existing tables: my_table_1,my_table_2' % sqlite_with_multiple_tables))\n\n    def test_querying_from_multi_table_sqlite_using_explicit_table_name(self):\n        sqlite_with_multiple_tables = self.generate_tmpfile_name(suffix='.sqlite')\n\n        c = sqlite3.connect(sqlite_with_multiple_tables)\n        c.execute('create table my_table_1 (x int, y int)').fetchall()\n        c.execute('insert into my_table_1 (x,y) values (100,200),(300,400)').fetchall()\n        c.execute('commit').fetchall()\n        c.execute('create table my_table_2 (x int, y int)').fetchall()\n        c.close()\n\n        cmd = '%s -d , \"select * from %s:::my_table_1\"' % (Q_EXECUTABLE,sqlite_with_multiple_tables)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 2)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('100,200'))\n        self.assertEqual(o[1],six.b('300,400'))\n\n        # Check again, this time with a different output delimiter and with explicit column names\n        cmd = '%s -t \"select x,y from %s:::my_table_1\"' % (Q_EXECUTABLE,sqlite_with_multiple_tables)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 2)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('100\\t200'))\n        self.assertEqual(o[1],six.b('300\\t400'))\n\n\n    def test_error_when_specifying_nonexistent_table_name_in_multi_table_qsql(self):\n        numbers1 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 10001)]\n        numbers2 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 11)]\n\n        header = [six.b('aa'), six.b('bb'), six.b('cc')]\n\n        qsql_with_multiple_tables = self.generate_tmpfile_name(suffix='.qsql')\n\n        new_tmp_folder = self.create_folder_with_files({\n            'filename1': self.arrays_to_csv_file_content(six.b(','),header,numbers1),\n            'otherfolder/filename1' : self.arrays_to_csv_file_content(six.b(','),header,numbers2)\n        },prefix='xx',suffix='yy')\n\n        effective_filename1 = '%s/filename1' % new_tmp_folder\n        effective_filename2 = '%s/otherfolder/filename1' % new_tmp_folder\n\n        expected_stored_table_name1 = 'filename1'\n        expected_stored_table_name2 = 'filename1_2'\n\n        cmd = Q_EXECUTABLE + ' -d , -H \"select sum(large_file.aa),sum(large_file.bb),sum(large_file.cc) from %s small_file left join %s large_file on (large_file.aa == small_file.bb)\" -S %s' % \\\n              (effective_filename1,effective_filename2,qsql_with_multiple_tables)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 4)\n\n        # Actual tests\n\n        cmd = '%s \"select count(*) from %s:::non_existent_table\"' % (Q_EXECUTABLE,qsql_with_multiple_tables)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 85)\n        self.assertEqual(len(o),0)\n        self.assertEqual(len(e),1)\n        self.assertEqual(e[0],six.b('Table non_existent_table could not be found in sqlite file %s . Existing table names: %s,%s' % \\\n                                    (qsql_with_multiple_tables,expected_stored_table_name1,expected_stored_table_name2)))\n\n    def test_querying_multi_table_qsql_file(self):\n        numbers1 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 10001)]\n        numbers2 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 11)]\n\n        header = [six.b('aa'), six.b('bb'), six.b('cc')]\n\n        qsql_with_multiple_tables = self.generate_tmpfile_name(suffix='.qsql')\n\n        new_tmp_folder = self.create_folder_with_files({\n            'filename1': self.arrays_to_csv_file_content(six.b(','),header,numbers1),\n            'otherfolder/filename1' : self.arrays_to_csv_file_content(six.b(','),header,numbers2)\n        },prefix='xx',suffix='yy')\n\n        effective_filename1 = '%s/filename1' % new_tmp_folder\n        effective_filename2 = '%s/otherfolder/filename1' % new_tmp_folder\n\n        expected_stored_table_name1 = 'filename1'\n        expected_stored_table_name2 = 'filename1_2'\n\n        cmd = Q_EXECUTABLE + ' -d , -H \"select sum(large_file.aa),sum(large_file.bb),sum(large_file.cc) from %s small_file left join %s large_file on (large_file.aa == small_file.bb)\" -S %s' % \\\n              (effective_filename1,effective_filename2,qsql_with_multiple_tables)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 4)\n\n        # Actual tests\n\n        cmd = '%s \"select count(*) from %s:::%s\"' % (Q_EXECUTABLE,qsql_with_multiple_tables,expected_stored_table_name1)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o),1)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0],six.b('10000'))\n\n        cmd = '%s \"select count(*) from %s:::%s\"' % (Q_EXECUTABLE,qsql_with_multiple_tables,expected_stored_table_name2)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o),1)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0],six.b('10'))\n\n    def test_preventing_db_overwrite(self):\n        db_filename = self.random_tmp_filename('store-to-disk', 'db')\n        self.assertFalse(os.path.exists(db_filename))\n\n        retcode, o, e = run_command('seq 1 1000 | ' + Q_EXECUTABLE + ' \"select count(*) from -\" -c 1 -S %s' % db_filename)\n\n        self.assertTrue(retcode == 0)\n        self.assertTrue(os.path.exists(db_filename))\n\n        retcode2, o2, e2 = run_command('seq 1 1000 | ' + Q_EXECUTABLE + ' \"select count(*) from -\" -c 1 -S %s' % db_filename)\n        self.assertTrue(retcode2 != 0)\n        self.assertTrue(e2[0].startswith(six.b('Going to save data into a disk database')))\n        self.assertTrue(e2[1] == six.b('Disk database file {} already exists.'.format(db_filename)))\n\n        os.remove(db_filename)\n\n\nclass BasicTests(AbstractQTestCase):\n\n    def test_basic_aggregation(self):\n        retcode, o, e = run_command(\n            'seq 1 10 | ' + Q_EXECUTABLE + ' \"select sum(c1),avg(c1) from -\"')\n        self.assertTrue(retcode == 0)\n        self.assertTrue(len(o) == 1)\n        self.assertTrue(len(e) == 0)\n\n        s = sum(range(1, 11))\n        self.assertTrue(o[0] == six.b('%s %s' % (s, s / 10.0)))\n\n    def test_select_one_column(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n\n        cmd = Q_EXECUTABLE + ' -d , \"select c1 from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(six.b(\" \").join(o), six.b('a b c'))\n\n        self.cleanup(tmpfile)\n\n    def test_column_separation(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n        cmd = Q_EXECUTABLE + ' -d , \"select c1,c2,c3 from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0], sample_data_rows[0])\n        self.assertEqual(o[1], sample_data_rows[1])\n        self.assertEqual(o[2], sample_data_rows[2])\n\n        self.cleanup(tmpfile)\n\n    def test_header_exception_on_numeric_header_data(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n        cmd = Q_EXECUTABLE + ' -d , \"select * from %s\" -A -H' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertNotEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 3)\n        self.assertTrue(\n            six.b('Bad header row: Header must contain only strings') in e[0])\n        self.assertTrue(six.b(\"Column name must be a string\") in e[1])\n        self.assertTrue(six.b(\"Column name must be a string\") in e[2])\n\n        self.cleanup(tmpfile)\n\n    def test_different_header_in_second_file(self):\n        folder_name = self.create_folder_with_files({\n            'file1': self.arrays_to_csv_file_content(six.b(','),[six.b('a'),six.b('b')],[[six.b(str(x)),six.b(str(x))] for x in range(1,6)]),\n            'file2': self.arrays_to_csv_file_content(six.b(','),[six.b('c'),six.b('d')],[[six.b(str(x)),six.b(str(x))] for x in range(1,6)])\n        },prefix=\"xx\",suffix=\"aa\")\n\n        cmd = Q_EXECUTABLE + ' -d , \"select * from %s/*\" -H' % (folder_name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 35)\n        self.assertEqual(len(e),1)\n        self.assertEqual(e[0],six.b(\"Bad header row: Extra header 'c,d' in file '%s/file2' mismatches original header 'a,b' from file '%s/file1'. Table name is '%s/*'\" % (folder_name,folder_name,folder_name)))\n\n    def test_data_with_header(self):\n        tmpfile = self.create_file_with_data(sample_data_with_header)\n        cmd = Q_EXECUTABLE + ' -d , \"select name from %s\" -H' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(six.b(\" \").join(o), six.b(\"a b c\"))\n\n        self.cleanup(tmpfile)\n\n    def test_output_header_when_input_header_exists(self):\n        tmpfile = self.create_file_with_data(sample_data_with_header)\n        cmd = Q_EXECUTABLE + ' -d , \"select name from %s\" -H -O' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 4)\n        self.assertEqual(o[0],six.b('name'))\n        self.assertEqual(o[1],six.b('a'))\n        self.assertEqual(o[2],six.b('b'))\n        self.assertEqual(o[3],six.b('c'))\n\n        self.cleanup(tmpfile)\n\n    def test_generated_column_name_warning_when_header_line_exists(self):\n        tmpfile = self.create_file_with_data(sample_data_with_header)\n        cmd = Q_EXECUTABLE + ' -d , \"select c3 from %s\" -H' % tmpfile.name\n\n        retcode, o, e = run_command(cmd)\n\n        self.assertNotEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 2)\n        self.assertTrue(six.b('no such column: c3') in e[0])\n        self.assertTrue(\n            e[1].startswith(six.b('Warning - There seems to be a \"no such column\" error, and -H (header line) exists. Please make sure that you are using the column names from the header line and not the default (cXX) column names')))\n\n        self.cleanup(tmpfile)\n\n    def test_empty_data(self):\n        tmpfile = self.create_file_with_data(six.b(''))\n        cmd = Q_EXECUTABLE + ' -d , \"select * from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n\n        self.assertTrue(six.b('Warning - data is empty') in e[0])\n\n        self.cleanup(tmpfile)\n\n    def test_empty_data_with_header_param(self):\n        tmpfile = self.create_file_with_data(six.b(''))\n        cmd = Q_EXECUTABLE + ' -d , \"select c1 from %s\" -H' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertNotEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n\n        m = six.b(\"Header line is expected but missing in file %s\" % tmpfile.name)\n        self.assertTrue(m in e[0])\n\n        self.cleanup(tmpfile)\n\n    def test_one_row_of_data_without_header_param(self):\n        tmpfile = self.create_file_with_data(header_row)\n        cmd = Q_EXECUTABLE + ' -d , \"select c2 from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0], six.b('value1'))\n\n        self.cleanup(tmpfile)\n\n    def test_one_row_of_data_with_header_param(self):\n        tmpfile = self.create_file_with_data(header_row)\n        cmd = Q_EXECUTABLE + ' -d , \"select name from %s\" -H' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n\n        self.assertTrue(six.b('Warning - data is empty') in e[0])\n\n        self.cleanup(tmpfile)\n\n    def test_dont_leading_keep_whitespace_in_values(self):\n        tmpfile = self.create_file_with_data(sample_data_with_spaces_no_header)\n        cmd = Q_EXECUTABLE + ' -d , \"select c1 from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 3)\n\n        self.assertEqual(o[0], six.b('a'))\n        self.assertEqual(o[1], six.b('b'))\n        self.assertEqual(o[2], six.b('c'))\n\n        self.cleanup(tmpfile)\n\n    def test_keep_leading_whitespace_in_values(self):\n        tmpfile = self.create_file_with_data(sample_data_with_spaces_no_header)\n        cmd = Q_EXECUTABLE + ' -d , \"select c1 from %s\" -k' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 3)\n\n        self.assertEqual(o[0], six.b('a'))\n        self.assertEqual(o[1], six.b('   b'))\n        self.assertEqual(o[2], six.b('c'))\n\n        self.cleanup(tmpfile)\n\n    def test_no_impact_of_keeping_leading_whitespace_on_integers(self):\n        tmpfile = self.create_file_with_data(sample_data_with_spaces_no_header)\n        cmd = Q_EXECUTABLE + ' -d , \"select c2 from %s\" -k -A' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        f = open(\"/var/tmp/XXX\",\"wb\")\n        f.write(six.b(\"\\n\").join(o))\n        f.write(six.b(\"STDERR:\"))\n        f.write(six.b(\"\\n\").join(e))\n        f.close()\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 7)\n\n\n        self.assertEqual(o[0], six.b('Table: %s' % tmpfile.name))\n        self.assertEqual(o[1], six.b('  Sources:'))\n        self.assertEqual(o[2], six.b('    source_type: file source: %s') % six.b(tmpfile.name))\n        self.assertEqual(o[3], six.b('  Fields:'))\n        self.assertEqual(o[4], six.b('    `c1` - text'))\n        self.assertEqual(o[5], six.b('    `c2` - int'))\n        self.assertEqual(o[6], six.b('    `c3` - int'))\n\n\n        self.cleanup(tmpfile)\n\n    def test_spaces_in_header_row(self):\n        tmpfile = self.create_file_with_data(\n            header_row_with_spaces + six.b(\"\\n\") + sample_data_no_header)\n        cmd = Q_EXECUTABLE + ' -d , \"select name,\\\\`value 1\\\\` from %s\" -H' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 3)\n\n        self.assertEqual(o[0], six.b('a,1'))\n        self.assertEqual(o[1], six.b('b,2'))\n        self.assertEqual(o[2], six.b('c,'))\n\n        self.cleanup(tmpfile)\n\n    def test_no_query_in_command_line(self):\n        cmd = Q_EXECUTABLE + ' -d , \"\"'\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 1)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(len(o), 0)\n\n        self.assertEqual(e[0],six.b('Query cannot be empty (query number 1)'))\n\n    def test_empty_query_in_command_line(self):\n        cmd = Q_EXECUTABLE + ' -d , \"  \"'\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 1)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(len(o), 0)\n\n        self.assertEqual(e[0],six.b('Query cannot be empty (query number 1)'))\n\n    def test_failure_in_query_stops_processing_queries(self):\n        cmd = Q_EXECUTABLE + ' -d , \"select 500\" \"select 300\" \"wrong-query\" \"select 8000\"'\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 1)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(len(o), 2)\n        self.assertEqual(o[0],six.b('500'))\n        self.assertEqual(o[1],six.b('300'))\n\n    def test_multiple_queries_in_command_line(self):\n        cmd = Q_EXECUTABLE + ' -d , \"select 500\" \"select 300+100\" \"select 300\" \"select 200\"'\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 4)\n\n        self.assertEqual(o[0],six.b('500'))\n        self.assertEqual(o[1],six.b('400'))\n        self.assertEqual(o[2],six.b('300'))\n        self.assertEqual(o[3],six.b('200'))\n\n    def test_literal_calculation_query(self):\n        cmd = Q_EXECUTABLE + ' -d , \"select 1+40/6\"'\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 1)\n\n        self.assertEqual(o[0],six.b('7'))\n\n    def test_literal_calculation_query_float_result(self):\n        cmd = Q_EXECUTABLE + ' -d , \"select 1+40/6.0\"'\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 1)\n\n        self.assertEqual(o[0],six.b('7.666666666666667'))\n\n    def test_use_query_file(self):\n        tmp_data_file = self.create_file_with_data(sample_data_with_header)\n        tmp_query_file = self.create_file_with_data(six.b(\"select name from %s\" % tmp_data_file.name))\n\n        cmd = Q_EXECUTABLE + ' -d , -q %s -H' % tmp_query_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 3)\n\n        self.assertEqual(o[0], six.b('a'))\n        self.assertEqual(o[1], six.b('b'))\n        self.assertEqual(o[2], six.b('c'))\n\n        self.cleanup(tmp_data_file)\n        self.cleanup(tmp_query_file)\n\n    def test_use_query_file_with_incorrect_query_encoding(self):\n        tmp_data_file = self.create_file_with_data(sample_data_with_header)\n        tmp_query_file = self.create_file_with_data(six.b(\"select name,'Hr\\xc3\\xa1\\xc4\\x8d' from %s\" % tmp_data_file.name),encoding=None)\n\n        cmd = Q_EXECUTABLE + ' -d , -q %s -H -Q ascii' % tmp_query_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,3)\n        self.assertEqual(len(o),0)\n        self.assertEqual(len(e),1)\n\n        self.assertTrue(e[0].startswith(six.b('Could not decode query number 1 using the provided query encoding (ascii)')))\n\n        self.cleanup(tmp_data_file)\n        self.cleanup(tmp_query_file)\n\n    def test_output_header_with_non_ascii_names(self):\n        OUTPUT_ENCODING = 'utf-8'\n\n        tmp_data_file = self.create_file_with_data(sample_data_with_header)\n        tmp_query_file = self.create_file_with_data(six.b(\"select name,'Hr\\xc3\\xa1\\xc4\\x8d' Hr\\xc3\\xa1\\xc4\\x8d from %s\" % tmp_data_file.name),encoding=None)\n\n        cmd = Q_EXECUTABLE + ' -d , -q %s -H -Q utf-8 -O -E %s' % (tmp_query_file.name,OUTPUT_ENCODING)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(o),4)\n        self.assertEqual(len(e),0)\n\n        self.assertEqual(o[0].decode(OUTPUT_ENCODING), u'name,Hr\\xe1\\u010d')\n        self.assertEqual(o[1].decode(OUTPUT_ENCODING), u'a,Hr\\xe1\\u010d')\n        self.assertEqual(o[2].decode(OUTPUT_ENCODING), u'b,Hr\\xe1\\u010d')\n        self.assertEqual(o[3].decode(OUTPUT_ENCODING), u'c,Hr\\xe1\\u010d')\n\n        self.cleanup(tmp_data_file)\n        self.cleanup(tmp_query_file)\n\n    def test_use_query_file_with_query_encoding(self):\n        OUTPUT_ENCODING = 'utf-8'\n\n        tmp_data_file = self.create_file_with_data(sample_data_with_header)\n        tmp_query_file = self.create_file_with_data(six.b(\"select name,'Hr\\xc3\\xa1\\xc4\\x8d' from %s\" % tmp_data_file.name),encoding=None)\n\n        cmd = Q_EXECUTABLE + ' -d , -q %s -H -Q utf-8 -E %s' % (tmp_query_file.name,OUTPUT_ENCODING)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 3)\n\n        self.assertEqual(o[0].decode(OUTPUT_ENCODING), u'a,Hr\\xe1\\u010d')\n        self.assertEqual(o[1].decode(OUTPUT_ENCODING), u'b,Hr\\xe1\\u010d')\n        self.assertEqual(o[2].decode(OUTPUT_ENCODING), u'c,Hr\\xe1\\u010d')\n\n        self.cleanup(tmp_data_file)\n        self.cleanup(tmp_query_file)\n\n    def test_use_query_file_and_command_line(self):\n        tmp_data_file = self.create_file_with_data(sample_data_with_header)\n        tmp_query_file = self.create_file_with_data(six.b(\"select name from %s\" % tmp_data_file.name))\n\n        cmd = Q_EXECUTABLE + ' -d , -q %s -H \"select * from ppp\"' % tmp_query_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 1)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(len(o), 0)\n\n        self.assertTrue(e[0].startswith(six.b(\"Can't provide both a query file and a query on the command line\")))\n\n        self.cleanup(tmp_data_file)\n        self.cleanup(tmp_query_file)\n\n    def test_select_output_encoding(self):\n        tmp_data_file = self.create_file_with_data(sample_data_with_header)\n        tmp_query_file = self.create_file_with_data(six.b(\"select 'Hr\\xc3\\xa1\\xc4\\x8d' from %s\" % tmp_data_file.name),encoding=None)\n\n        for target_encoding in ['utf-8','ibm852']:\n            cmd = Q_EXECUTABLE + ' -d , -q %s -H -Q utf-8 -E %s' % (tmp_query_file.name,target_encoding)\n            retcode, o, e = run_command(cmd)\n\n            self.assertEqual(retcode, 0)\n            self.assertEqual(len(e), 0)\n            self.assertEqual(len(o), 3)\n\n            self.assertEqual(o[0].decode(target_encoding), u'Hr\\xe1\\u010d')\n            self.assertEqual(o[1].decode(target_encoding), u'Hr\\xe1\\u010d')\n            self.assertEqual(o[2].decode(target_encoding), u'Hr\\xe1\\u010d')\n\n        self.cleanup(tmp_data_file)\n        self.cleanup(tmp_query_file)\n\n    def test_select_failed_output_encoding(self):\n        tmp_data_file = self.create_file_with_data(sample_data_with_header)\n        tmp_query_file = self.create_file_with_data(six.b(\"select 'Hr\\xc3\\xa1\\xc4\\x8d' from %s\" % tmp_data_file.name),encoding=None)\n\n        cmd = Q_EXECUTABLE + ' -d , -q %s -H -Q utf-8 -E ascii' % tmp_query_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 3)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(len(o), 0)\n\n        self.assertTrue(e[0].startswith(six.b('Cannot encode data')))\n\n        self.cleanup(tmp_data_file)\n        self.cleanup(tmp_query_file)\n\n\n    def test_use_query_file_with_empty_query(self):\n        tmp_query_file = self.create_file_with_data(six.b(\"   \"))\n\n        cmd = Q_EXECUTABLE + ' -d , -q %s -H' % tmp_query_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 1)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(len(o), 0)\n\n        self.assertTrue(e[0].startswith(six.b(\"Query cannot be empty\")))\n\n        self.cleanup(tmp_query_file)\n\n    def test_use_non_existent_query_file(self):\n        cmd = Q_EXECUTABLE + ' -d , -q non-existent-query-file -H'\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 1)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(len(o), 0)\n\n        self.assertTrue(e[0].startswith(six.b(\"Could not read query from file\")))\n\n    def test_nonexistent_file(self):\n        cmd = Q_EXECUTABLE + ' \"select * from non-existent-file\"'\n\n        retcode, o, e = run_command(cmd)\n\n        self.assertNotEqual(retcode,0)\n        self.assertEqual(len(o),0)\n        self.assertEqual(len(e),1)\n\n        self.assertEqual(e[0],six.b(\"No files matching '%s/non-existent-file' have been found\" % os.getcwd()))\n\n    def test_default_column_max_length_parameter__short_enough(self):\n        huge_text = six.b(\"x\" * 131000)\n\n        file_data = six.b(\"a,b,c\\n1,{},3\\n\".format(huge_text))\n\n        tmpfile = self.create_file_with_data(file_data)\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0],six.b('1'))\n\n        self.cleanup(tmpfile)\n\n    def test_default_column_max_length_parameter__too_long(self):\n        huge_text = six.b(\"x\") * 132000\n\n        file_data = six.b(\"a,b,c\\n1,{},3\\n\".format(huge_text))\n\n        tmpfile = self.create_file_with_data(file_data)\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 31)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n\n        self.assertTrue(e[0].startswith(six.b(\"Column length is larger than the maximum\")))\n        self.assertTrue(six.b(\"Offending file is '{}'\".format(tmpfile.name)) in e[0])\n        self.assertTrue(six.b('Line is 2') in e[0])\n\n        self.cleanup(tmpfile)\n\n    def test_column_max_length_parameter(self):\n        file_data = six.b(\"a,b,c\\nvery-long-text,2,3\\n\")\n        tmpfile = self.create_file_with_data(file_data)\n\n        cmd = Q_EXECUTABLE + ' -H -d , -M 3 \"select a from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 31)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n\n        self.assertTrue(e[0].startswith(six.b(\"Column length is larger than the maximum\")))\n        self.assertTrue((six.b(\"Offending file is '%s'\" % tmpfile.name)) in e[0])\n        self.assertTrue(six.b('Line is 2') in e[0])\n\n        cmd2 = Q_EXECUTABLE + ' -H -d , -M 300 -H \"select a from %s\"' % tmpfile.name\n        retcode2, o2, e2 = run_command(cmd2)\n\n        self.assertEqual(retcode2, 0)\n        self.assertEqual(len(o2), 1)\n        self.assertEqual(len(e2), 0)\n\n        self.assertEqual(o2[0],six.b('very-long-text'))\n\n        self.cleanup(tmpfile)\n\n    def test_invalid_column_max_length_parameter(self):\n        file_data = six.b(\"a,b,c\\nvery-long-text,2,3\\n\")\n        tmpfile = self.create_file_with_data(file_data)\n\n        cmd = Q_EXECUTABLE + ' -H -d , -M xx \"select a from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 31)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n\n        self.assertEqual(e[0],six.b('Max column length limit must be an integer larger than 2 (xx)'))\n\n        self.cleanup(tmpfile)\n\n    def test_duplicate_column_name_detection(self):\n        file_data = six.b(\"a,b,a\\n10,20,30\\n30,40,50\")\n        tmpfile = self.create_file_with_data(file_data)\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 35)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 2)\n\n        self.assertTrue(e[0].startswith(six.b('Bad header row:')))\n        self.assertEqual(e[1],six.b(\"'a': Column name is duplicated\"))\n\n        self.cleanup(tmpfile)\n\n    def test_join_with_stdin(self):\n        x = [six.b(a) for a in map(str,range(1,101))]\n        large_file_data = six.b(\"val\\n\") + six.b(\"\\n\").join(x)\n        tmpfile = self.create_file_with_data(large_file_data)\n\n        cmd = '(echo id ; seq 1 2 10) | %s -c 1 -H -O \"select stdin.*,f.* from - stdin left join %s f on (stdin.id * 10 = f.val)\"' % (Q_EXECUTABLE,tmpfile.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 6)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0],six.b('id val'))\n        self.assertEqual(o[1],six.b('1 10'))\n        self.assertEqual(o[2],six.b('3 30'))\n        self.assertEqual(o[3],six.b('5 50'))\n        self.assertEqual(o[4],six.b('7 70'))\n        self.assertEqual(o[5],six.b('9 90'))\n\n        self.cleanup(tmpfile)\n\n    def test_concatenated_files(self):\n        file_data1 = six.b(\"a,b,c\\n10,11,12\\n20,21,22\")\n        tmpfile1 = self.create_file_with_data(file_data1)\n        tmpfile1_folder = os.path.dirname(tmpfile1.name)\n        tmpfile1_filename = os.path.basename(tmpfile1.name)\n        expected_cache_filename1 = os.path.join(tmpfile1_folder,tmpfile1_filename + '.qsql')\n\n        file_data2 = six.b(\"a,b,c\\n30,31,32\\n40,41,42\")\n        tmpfile2 = self.create_file_with_data(file_data2)\n        tmpfile2_folder = os.path.dirname(tmpfile2.name)\n        tmpfile2_filename = os.path.basename(tmpfile2.name)\n        expected_cache_filename2 = os.path.join(tmpfile2_folder,tmpfile2_filename + '.qsql')\n\n        cmd = Q_EXECUTABLE + ' -O -H -d , \"select * from %s UNION ALL select * from %s\" -C none' % (tmpfile1.name,tmpfile2.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 5)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('a,b,c'))\n        self.assertEqual(o[1],six.b('10,11,12'))\n        self.assertEqual(o[2],six.b('20,21,22'))\n        self.assertEqual(o[3],six.b('30,31,32'))\n        self.assertEqual(o[4],six.b('40,41,42'))\n\n        self.cleanup(tmpfile1)\n        self.cleanup(tmpfile2)\n\n    def test_out_of_range_expected_column_count(self):\n        cmd = '%s \"select count(*) from some_table\" -c -1' % Q_EXECUTABLE\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 90)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(e[0], six.b('Column count must be between 1 and 131072'))\n\n    def test_out_of_range_expected_column_count__with_explicit_limit(self):\n        cmd = '%s \"select count(*) from some_table\" -c -1 -M 100' % Q_EXECUTABLE\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 90)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(e[0], six.b('Column count must be between 1 and 100'))\n\n    def test_other_out_of_range_expected_column_count__with_explicit_limit(self):\n        cmd = '%s \"select count(*) from some_table\" -c 101 -M 100' % Q_EXECUTABLE\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 90)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(e[0], six.b('Column count must be between 1 and 100'))\n\n    def test_explicit_limit_of_columns__data_is_ok(self):\n        file_data1 = six.b(\"191\\n192\\n\")\n        tmpfile1 = self.create_file_with_data(file_data1)\n\n        cmd = '%s \"select count(*) from %s\" -c 1 -M 3' % (Q_EXECUTABLE,tmpfile1.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0], six.b('2'))\n\n        self.cleanup(tmpfile1)\n\nclass ManyOpenFilesTests(AbstractQTestCase):\n\n\n    def test_multi_file_header_skipping(self):\n        BATCH_SIZE = 50\n        FILE_COUNT = 5\n\n        numbers = list(range(1,1+BATCH_SIZE*FILE_COUNT))\n        numbers_as_text = batch([str(x) for x in numbers],n=BATCH_SIZE)\n\n        content_list = list(map(six.b,['a\\n' + \"\\n\".join(x)+'\\n' for x in numbers_as_text]))\n\n        filename_list = list(map(lambda x: 'file-%s' % x,range(FILE_COUNT)))\n        d = collections.OrderedDict(zip(filename_list, content_list))\n\n        tmpfolder = self.create_folder_with_files(d,'split-files','multi-header')\n\n        cmd = '%s -d , -H -c 1 \"select count(a),sum(a) from %s/*\" -C none' % (Q_EXECUTABLE,tmpfolder)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0],six.b(\"%s,%s\" % (BATCH_SIZE*FILE_COUNT,sum(numbers))))\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_that_globs_dont_max_out_sqlite_attached_database_limits(self):\n        BATCH_SIZE = 50\n        FILE_COUNT = 40\n\n        numbers_as_text = batch([str(x) for x in range(1,1+BATCH_SIZE*FILE_COUNT)],n=BATCH_SIZE)\n\n        content_list = map(six.b,[\"\\n\".join(x)+'\\n' for x in numbers_as_text])\n\n        filename_list = list(map(lambda x: 'file-%s' % x,range(FILE_COUNT)))\n        d = collections.OrderedDict(zip(filename_list, content_list))\n\n        tmpfolder = self.create_folder_with_files(d,'split-files','attach-limit')\n        #expected_cache_filename = os.path.join(tmpfile_folder,tmpfile_filename + '.qsql')\n\n        cmd = 'cd %s && %s -c 1 \"select count(*) from *\" -C none --max-attached-sqlite-databases=10' % (tmpfolder,Q_EXECUTABLE)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0],six.b(str(BATCH_SIZE*FILE_COUNT)))\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_maxing_out_max_attached_database_limits__regular_files(self):\n        BATCH_SIZE = 50\n        FILE_COUNT = 40\n\n        numbers_as_text = batch([str(x) for x in range(1,1+BATCH_SIZE*FILE_COUNT)],n=BATCH_SIZE)\n\n        content_list = map(six.b,[\"\\n\".join(x)+'\\n' for x in numbers_as_text])\n\n        filename_list = list(map(lambda x: 'file-%s' % x,range(FILE_COUNT)))\n        d = collections.OrderedDict(zip(filename_list, content_list))\n\n        tmpfolder = self.create_folder_with_files(d,'split-files','attach-limit')\n        #expected_cache_filename = os.path.join(tmpfile_folder,tmpfile_filename + '.qsql')\n\n        unioned_subquery = \" UNION ALL \".join([\"select * from %s/%s\" % (tmpfolder,filename) for filename in filename_list])\n        cmd = 'cd %s && %s -c 1 \"select count(*) from (%s)\" -C none --max-attached-sqlite-databases=10' % (tmpfolder,Q_EXECUTABLE,unioned_subquery)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0],six.b(str(BATCH_SIZE*FILE_COUNT)))\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_maxing_out_max_attached_database_limits__with_qsql_files_below_attached_limit(self):\n        MAX_ATTACHED_SQLITE_DATABASES = 10\n\n        BATCH_SIZE = 50\n        FILE_COUNT = MAX_ATTACHED_SQLITE_DATABASES - 1\n\n        numbers_as_text = batch([str(x) for x in range(1,1+BATCH_SIZE*FILE_COUNT)],n=BATCH_SIZE)\n\n        content_list = map(six.b,[\"\\n\".join(x)+'\\n' for x in numbers_as_text])\n\n        filename_list = list(map(lambda x: 'file-%s' % x,range(FILE_COUNT)))\n        d = collections.OrderedDict(zip(filename_list, content_list))\n\n        tmpfolder = self.create_folder_with_files(d,'split-files','attach-limit')\n        #expected_cache_filename = os.path.join(tmpfile_folder,tmpfile_filename + '.qsql')\n\n        # Execute the query with -C readwrite, so all qsql files will be created\n        unioned_subquery = \" UNION ALL \".join([\"select * from %s/%s\" % (tmpfolder,filename) for filename in filename_list])\n        cmd = 'cd %s && %s -c 1 \"select count(*) from (%s)\" -C readwrite --max-attached-sqlite-databases=%s' % (tmpfolder,Q_EXECUTABLE,unioned_subquery,MAX_ATTACHED_SQLITE_DATABASES)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b(str(BATCH_SIZE*FILE_COUNT)))\n\n        # Now execute the same query with -C readwrite, so all files will be read directly from the qsql files\n        cmd = 'cd %s && %s -c 1 \"select count(*) from (%s)\" -C readwrite' % (tmpfolder,Q_EXECUTABLE,unioned_subquery)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b(str(BATCH_SIZE*FILE_COUNT)))\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_maxing_out_max_attached_database_limits__with_qsql_files_above_attached_limit(self):\n        MAX_ATTACHED_SQLITE_DATABASES = 10\n\n        BATCH_SIZE = 50\n        # Here's the difference from test_maxing_out_max_attached_database_limits__with_qsql_files_below_attached_limit\n        # We're trying to cache 2 times the number of files than the number of databases that can be attached.\n        # Expectation is that only a part of the files will be cached\n        FILE_COUNT = MAX_ATTACHED_SQLITE_DATABASES * 2\n\n        numbers_as_text = batch([str(x) for x in range(1,1+BATCH_SIZE*FILE_COUNT)],n=BATCH_SIZE)\n\n        content_list = map(six.b,[\"\\n\".join(x)+'\\n' for x in numbers_as_text])\n\n        filename_list = list(map(lambda x: 'file-%s' % x,range(FILE_COUNT)))\n        d = collections.OrderedDict(zip(filename_list, content_list))\n\n        tmpfolder = self.create_folder_with_files(d,'split-files','attach-limit')\n        #expected_cache_filename = os.path.join(tmpfile_folder,tmpfile_filename + '.qsql')\n\n        # Execute the query with -C readwrite, so all qsql files will be created\n        unioned_subquery = \" UNION ALL \".join([\"select * from %s/%s\" % (tmpfolder,filename) for filename in filename_list])\n        cmd = 'cd %s && %s -c 1 \"select count(*) from (%s)\" -C readwrite --max-attached-sqlite-databases=%s' % (tmpfolder,Q_EXECUTABLE,unioned_subquery,MAX_ATTACHED_SQLITE_DATABASES)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b(str(BATCH_SIZE*FILE_COUNT)))\n\n        # Now execute the same query with -C readwrite, so all files will be read directly from the qsql files\n        cmd = 'cd %s && %s -c 1 \"select count(*) from (%s)\" -C readwrite' % (tmpfolder,Q_EXECUTABLE,unioned_subquery)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b(str(BATCH_SIZE*FILE_COUNT)))\n\n        from glob import glob\n        files_in_folder = [os.path.basename(x) for x in glob('%s/*' % (tmpfolder))]\n\n        expected_files_in_folder = filename_list + list(map(lambda x: 'file-%s.qsql' % x,range(MAX_ATTACHED_SQLITE_DATABASES-2)))\n\n        self.assertEqual(sorted(files_in_folder),sorted(expected_files_in_folder))\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_maxing_out_max_attached_database_limits__with_directly_using_qsql_files(self):\n        MAX_ATTACHED_SQLITE_DATABASES = 10\n\n        BATCH_SIZE = 50\n        FILE_COUNT = MAX_ATTACHED_SQLITE_DATABASES * 2\n\n        numbers_as_text = batch([str(x) for x in range(1,1+BATCH_SIZE*FILE_COUNT)],n=BATCH_SIZE)\n\n        content_list = map(six.b,[\"\\n\".join(x)+'\\n' for x in numbers_as_text])\n\n        filename_list = list(map(lambda x: 'file-%s' % x,range(FILE_COUNT)))\n        d = collections.OrderedDict(zip(filename_list, content_list))\n\n        tmpfolder = self.create_folder_with_files(d,'split-files','attach-limit')\n        #expected_cache_filename = os.path.join(tmpfile_folder,tmpfile_filename + '.qsql')\n\n        # Prepare qsql for each of the files (separately, just for simplicity)\n        for fn in filename_list:\n            cmd = 'cd %s && %s -c 1 \"select count(*) from %s\" -C readwrite' % (tmpfolder,Q_EXECUTABLE,fn)\n            retcode, o, e = run_command(cmd)\n\n            self.assertEqual(retcode, 0)\n            self.assertEqual(len(o), 1)\n            self.assertEqual(len(e), 0)\n\n        # Now execute a big query which uses the created qsql files\n        unioned_subquery = \" UNION ALL \".join([\"select * from %s/%s.qsql\" % (tmpfolder,filename) for filename in filename_list])\n\n        cmd = 'cd %s && %s -c 1 \"select count(*) from (%s)\" -C readwrite' % (tmpfolder,Q_EXECUTABLE,unioned_subquery)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b(str(BATCH_SIZE*FILE_COUNT)))\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_too_many_open_files_for_one_table(self):\n        # Previously file opening was parallel, causing too-many-open-files\n\n        MAX_ALLOWED_FILES = 500\n\n        BATCH_SIZE = 2\n        FILE_COUNT = MAX_ALLOWED_FILES + 1\n\n        numbers_as_text = batch([str(x) for x in range(1,1+BATCH_SIZE*FILE_COUNT)],n=BATCH_SIZE)\n\n        content_list = map(six.b,[\"\\n\".join(x) for x in numbers_as_text])\n\n        filename_list = list(map(lambda x: 'file-%s' % x,range(FILE_COUNT)))\n        d = collections.OrderedDict(zip(filename_list, content_list))\n\n        tmpfolder = self.create_folder_with_files(d,'split-files','attach-limit')\n\n        cmd = 'cd %s && %s -c 1 \"select count(*) from * where 1 = 1 or c1 != 2\" -C none' % (tmpfolder,Q_EXECUTABLE)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 82)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n        x = six.b('Maximum source files for table must be %s. Table is name is %s/* Number of actual files is %s' % (MAX_ALLOWED_FILES,os.path.realpath(tmpfolder),FILE_COUNT))\n        print(x)\n        self.assertEqual(e[0],x)\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_many_open_files_for_one_table(self):\n        # Previously file opening was parallel, causing too-many-open-files\n\n        BATCH_SIZE = 2\n        FILE_COUNT = 500\n\n        numbers_as_text = batch([str(x) for x in range(1,1+BATCH_SIZE*FILE_COUNT)],n=BATCH_SIZE)\n\n        content_list = map(six.b,[\"\\n\".join(x) for x in numbers_as_text])\n\n        filename_list = list(map(lambda x: 'file-%s' % x,range(FILE_COUNT)))\n        d = collections.OrderedDict(zip(filename_list, content_list))\n\n        tmpfolder = self.create_folder_with_files(d,'split-files','attach-limit')\n        #expected_cache_filename = os.path.join(tmpfile_folder,tmpfile_filename + '.qsql')\n\n        cmd = 'cd %s && %s -c 1 \"select count(*) from * where 1 = 1 or c1 != 2\" -C none' % (tmpfolder,Q_EXECUTABLE)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0],six.b(str(BATCH_SIZE*FILE_COUNT)))\n\n        self.cleanup_folder(tmpfolder)\n\n    def test_many_open_files_for_two_tables(self):\n        BATCH_SIZE = 2\n        FILE_COUNT = 500\n\n        numbers_as_text = batch([str(x) for x in range(1, 1 + BATCH_SIZE * FILE_COUNT)], n=BATCH_SIZE)\n\n        content_list = map(six.b, [\"\\n\".join(x) for x in numbers_as_text])\n\n        filename_list = list(map(lambda x: 'file-%s' % x, range(FILE_COUNT)))\n        d = collections.OrderedDict(zip(filename_list, content_list))\n\n        tmpfolder1 = self.create_folder_with_files(d, 'split-files1', 'blah')\n        tmpfolder2 = self.create_folder_with_files(d, 'split-files1', 'blah')\n\n        cmd = '%s -c 1 \"select count(*) from %s/* a left join %s/* b on (a.c1 = b.c1)\" -C none' % (\n            Q_EXECUTABLE,\n            tmpfolder1,\n            tmpfolder2)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0], six.b(str(BATCH_SIZE * FILE_COUNT)))\n\n        self.cleanup_folder(tmpfolder1)\n        self.cleanup_folder(tmpfolder2)\n\n\nclass GzippingTests(AbstractQTestCase):\n\n    def test_gzipped_file(self):\n        tmpfile = self.create_file_with_data(\n            six.b('\\x1f\\x8b\\x08\\x08\\xf2\\x18\\x12S\\x00\\x03xxxxxx\\x003\\xe42\\xe22\\xe62\\xe12\\xe52\\xe32\\xe7\\xb2\\xe0\\xb2\\xe424\\xe0\\x02\\x00\\xeb\\xbf\\x8a\\x13\\x15\\x00\\x00\\x00'))\n\n        cmd = Q_EXECUTABLE + ' -z \"select sum(c1),avg(c1) from %s\"' % tmpfile.name\n\n        retcode, o, e = run_command(cmd)\n        self.assertTrue(retcode == 0)\n        self.assertTrue(len(o) == 1)\n        self.assertTrue(len(e) == 0)\n\n        s = sum(range(1, 11))\n        self.assertTrue(o[0] == six.b('%s %s' % (s, s / 10.0)))\n\n        self.cleanup(tmpfile)\n\n\nclass DelimiterTests(AbstractQTestCase):\n\n    def test_delimition_mistake_with_header(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n\n        cmd = Q_EXECUTABLE + ' -d \" \" \"select * from %s\" -H' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertNotEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 2)\n\n        self.assertTrue(e[0].startswith(six.b(\"Bad header row\")))\n        self.assertTrue(six.b(\"Column name cannot contain commas\") in e[1])\n\n        self.cleanup(tmpfile)\n\n    def test_tab_delimition_parameter(self):\n        tmpfile = self.create_file_with_data(\n            sample_data_no_header.replace(six.b(\",\"), six.b(\"\\t\")))\n        cmd = Q_EXECUTABLE + ' -t \"select c1,c2,c3 from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0], sample_data_rows[0].replace(six.b(\",\"), six.b(\"\\t\")))\n        self.assertEqual(o[1], sample_data_rows[1].replace(six.b(\",\"), six.b(\"\\t\")))\n        self.assertEqual(o[2], sample_data_rows[2].replace(six.b(\",\"), six.b(\"\\t\")))\n\n        self.cleanup(tmpfile)\n\n    def test_pipe_delimition_parameter(self):\n        tmpfile = self.create_file_with_data(\n            sample_data_no_header.replace(six.b(\",\"), six.b(\"|\")))\n        cmd = Q_EXECUTABLE + ' -p \"select c1,c2,c3 from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0], sample_data_rows[0].replace(six.b(\",\"), six.b(\"|\")))\n        self.assertEqual(o[1], sample_data_rows[1].replace(six.b(\",\"), six.b(\"|\")))\n        self.assertEqual(o[2], sample_data_rows[2].replace(six.b(\",\"), six.b(\"|\")))\n\n        self.cleanup(tmpfile)\n\n    def test_tab_delimition_parameter__with_manual_override_attempt(self):\n        tmpfile = self.create_file_with_data(\n            sample_data_no_header.replace(six.b(\",\"), six.b(\"\\t\")))\n        cmd = Q_EXECUTABLE + ' -t -d , \"select c1,c2,c3 from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(o[0], sample_data_rows[0].replace(six.b(\",\"), six.b(\"\\t\")))\n        self.assertEqual(o[1], sample_data_rows[1].replace(six.b(\",\"), six.b(\"\\t\")))\n        self.assertEqual(o[2], sample_data_rows[2].replace(six.b(\",\"), six.b(\"\\t\")))\n        self.assertEqual(e[0],six.b('Warning: -t parameter overrides -d parameter (,)'))\n\n        self.cleanup(tmpfile)\n\n    def test_pipe_delimition_parameter__with_manual_override_attempt(self):\n        tmpfile = self.create_file_with_data(\n            sample_data_no_header.replace(six.b(\",\"), six.b(\"|\")))\n        cmd = Q_EXECUTABLE + ' -p -d , \"select c1,c2,c3 from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(o[0], sample_data_rows[0].replace(six.b(\",\"), six.b(\"|\")))\n        self.assertEqual(o[1], sample_data_rows[1].replace(six.b(\",\"), six.b(\"|\")))\n        self.assertEqual(o[2], sample_data_rows[2].replace(six.b(\",\"), six.b(\"|\")))\n        self.assertEqual(e[0],six.b('Warning: -p parameter overrides -d parameter (,)'))\n\n        self.cleanup(tmpfile)\n\n    def test_output_delimiter(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n        cmd = Q_EXECUTABLE + ' -d , -D \"|\" \"select c1,c2,c3 from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0], sample_data_rows[0].replace(six.b(\",\"), six.b(\"|\")))\n        self.assertEqual(o[1], sample_data_rows[1].replace(six.b(\",\"), six.b(\"|\")))\n        self.assertEqual(o[2], sample_data_rows[2].replace(six.b(\",\"), six.b(\"|\")))\n\n        self.cleanup(tmpfile)\n\n    def test_output_delimiter_tab_parameter(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n        cmd = Q_EXECUTABLE + ' -d , -T \"select c1,c2,c3 from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0], sample_data_rows[0].replace(six.b(\",\"), six.b(\"\\t\")))\n        self.assertEqual(o[1], sample_data_rows[1].replace(six.b(\",\"), six.b(\"\\t\")))\n        self.assertEqual(o[2], sample_data_rows[2].replace(six.b(\",\"), six.b(\"\\t\")))\n\n        self.cleanup(tmpfile)\n\n    def test_output_delimiter_pipe_parameter(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n        cmd = Q_EXECUTABLE + ' -d , -P \"select c1,c2,c3 from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0], sample_data_rows[0].replace(six.b(\",\"), six.b(\"|\")))\n        self.assertEqual(o[1], sample_data_rows[1].replace(six.b(\",\"), six.b(\"|\")))\n        self.assertEqual(o[2], sample_data_rows[2].replace(six.b(\",\"), six.b(\"|\")))\n\n        self.cleanup(tmpfile)\n\n    def test_output_delimiter_tab_parameter__with_manual_override_attempt(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n        cmd = Q_EXECUTABLE + ' -d , -T -D \"|\" \"select c1,c2,c3 from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(len(e), 1)\n\n        self.assertEqual(o[0], sample_data_rows[0].replace(six.b(\",\"), six.b(\"\\t\")))\n        self.assertEqual(o[1], sample_data_rows[1].replace(six.b(\",\"), six.b(\"\\t\")))\n        self.assertEqual(o[2], sample_data_rows[2].replace(six.b(\",\"), six.b(\"\\t\")))\n        self.assertEqual(e[0], six.b('Warning: -T parameter overrides -D parameter (|)'))\n\n        self.cleanup(tmpfile)\n\n    def test_output_delimiter_pipe_parameter__with_manual_override_attempt(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n        cmd = Q_EXECUTABLE + ' -d , -P -D \":\" \"select c1,c2,c3 from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(len(e), 1)\n\n        self.assertEqual(o[0], sample_data_rows[0].replace(six.b(\",\"), six.b(\"|\")))\n        self.assertEqual(o[1], sample_data_rows[1].replace(six.b(\",\"), six.b(\"|\")))\n        self.assertEqual(o[2], sample_data_rows[2].replace(six.b(\",\"), six.b(\"|\")))\n        self.assertEqual(e[0],six.b('Warning: -P parameter overrides -D parameter (:)'))\n\n        self.cleanup(tmpfile)\n\n\nclass AnalysisTests(AbstractQTestCase):\n\n    def test_analyze_result(self):\n        d = \"\\n\".join(['%s\\t%s\\t%s' % (x+1,x+1,x+1) for x in range(100)])\n        tmpfile = self.create_file_with_data(six.b(d))\n\n        cmd = Q_EXECUTABLE + ' -c 1 \"select count(*) from %s\" -A' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 5)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0], six.b('Table: %s' % tmpfile.name))\n        self.assertEqual(o[1], six.b('  Sources:'))\n        self.assertEqual(o[2], six.b('    source_type: file source: %s' %(tmpfile.name)))\n        self.assertEqual(o[3], six.b('  Fields:'))\n        self.assertEqual(o[4], six.b('    `c1` - text'))\n\n        self.cleanup(tmpfile)\n\n    def test_analyze_result_with_data_stream(self):\n        d = \"\\n\".join(['%s\\t%s\\t%s' % (x+1,x+1,x+1) for x in range(100)])\n        tmpfile = self.create_file_with_data(six.b(d))\n\n        cmd = 'cat %s | %s  -c 1 \"select count(*) from -\" -A' % (tmpfile.name,Q_EXECUTABLE)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 5)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0], six.b('Table: -'))\n        self.assertEqual(o[1], six.b('  Sources:'))\n        self.assertEqual(o[2], six.b('    source_type: data-stream source: stdin'))\n        self.assertEqual(o[3], six.b('  Fields:'))\n        self.assertEqual(o[4], six.b('    `c1` - text'))\n\n        self.cleanup(tmpfile)\n\n    def test_column_analysis(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n\n        cmd = Q_EXECUTABLE + ' -d , \"select c1 from %s\" -A' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(o[0], six.b('Table: %s' % tmpfile.name))\n        self.assertEqual(o[1],six.b('  Sources:'))\n        self.assertEqual(o[2],six.b('    source_type: file source: %s' % tmpfile.name))\n        self.assertEqual(o[3],six.b('  Fields:'))\n        self.assertEqual(o[4], six.b('    `c1` - text'))\n        self.assertEqual(o[5], six.b('    `c2` - int'))\n        self.assertEqual(o[6], six.b('    `c3` - int'))\n\n        self.cleanup(tmpfile)\n\n    def test_column_analysis_with_mixed_ints_and_floats(self):\n        tmpfile = self.create_file_with_data(six.b(\"\"\"planet_id,name,diameter_km,length_of_day_hours\\n1000,Earth,12756,24\\n2000,Mars,6792,24.7\\n3000,Jupiter,142984,9.9\"\"\"))\n\n        cmd = Q_EXECUTABLE + ' -d , -H \"select * from %s\" -A' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o),8)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0], six.b('Table: %s' % tmpfile.name))\n        self.assertEqual(o[1],six.b('  Sources:'))\n        self.assertEqual(o[2],six.b('    source_type: file source: %s' % tmpfile.name))\n        self.assertEqual(o[3],six.b('  Fields:'))\n        self.assertEqual(o[4], six.b('    `planet_id` - int'))\n        self.assertEqual(o[5], six.b('    `name` - text'))\n        self.assertEqual(o[6], six.b('    `diameter_km` - int'))\n        self.assertEqual(o[7], six.b('    `length_of_day_hours` - real'))\n\n        self.cleanup(tmpfile)\n\n    def test_column_analysis_with_mixed_ints_and_floats_and_nulls(self):\n        tmpfile = self.create_file_with_data(six.b(\"\"\"planet_id,name,diameter_km,length_of_day_hours\\n1000,Earth,12756,24\\n2000,Mars,6792,24.7\\n2500,Venus,,\\n3000,Jupiter,142984,9.9\"\"\"))\n\n        cmd = Q_EXECUTABLE + ' -d , -H \"select * from %s\" -A' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o),8)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0], six.b('Table: %s' % tmpfile.name))\n        self.assertEqual(o[1],six.b('  Sources:'))\n        self.assertEqual(o[2],six.b('    source_type: file source: %s' % tmpfile.name))\n        self.assertEqual(o[3],six.b('  Fields:'))\n        self.assertEqual(o[4], six.b('    `planet_id` - int'))\n        self.assertEqual(o[5], six.b('    `name` - text'))\n        self.assertEqual(o[6], six.b('    `diameter_km` - int'))\n        self.assertEqual(o[7], six.b('    `length_of_day_hours` - real'))\n\n        self.cleanup(tmpfile)\n\n    def test_column_analysis_no_header(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n\n        cmd = Q_EXECUTABLE + ' -d , \"select c1 from %s\" -A' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(o[0], six.b('Table: %s' % tmpfile.name))\n        self.assertEqual(o[1],six.b('  Sources:'))\n        self.assertEqual(o[2],six.b('    source_type: file source: %s' % tmpfile.name))\n        self.assertEqual(o[3],six.b('  Fields:'))\n        self.assertEqual(o[4], six.b('    `c1` - text'))\n        self.assertEqual(o[5], six.b('    `c2` - int'))\n        self.assertEqual(o[6], six.b('    `c3` - int'))\n\n    def test_column_analysis_with_unexpected_header(self):\n        tmpfile = self.create_file_with_data(sample_data_with_header)\n        cmd = Q_EXECUTABLE + ' -d , \"select c1 from %s\" -A' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 7)\n        self.assertEqual(len(e), 1)\n\n        self.assertEqual(o[0], six.b('Table: %s' % tmpfile.name))\n        self.assertEqual(o[1],six.b('  Sources:'))\n        self.assertEqual(o[2],six.b('    source_type: file source: %s' % tmpfile.name))\n        self.assertEqual(o[3],six.b('  Fields:'))\n        self.assertEqual(o[4],six.b('    `c1` - text'))\n        self.assertEqual(o[5],six.b('    `c2` - text'))\n        self.assertEqual(o[6],six.b('    `c3` - text'))\n\n        self.assertEqual(\n            e[0], six.b('Warning - There seems to be header line in the file, but -H has not been specified. All fields will be detected as text fields, and the header line will appear as part of the data'))\n\n        self.cleanup(tmpfile)\n\n    def test_column_analysis_for_spaces_in_header_row(self):\n        tmpfile = self.create_file_with_data(\n            header_row_with_spaces + six.b(\"\\n\") + sample_data_no_header)\n        cmd = Q_EXECUTABLE + ' -d , \"select name,\\\\`value 1\\\\` from %s\" -H -A' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 7)\n\n        self.assertEqual(o[0], six.b('Table: %s' % tmpfile.name))\n        self.assertEqual(o[1],six.b('  Sources:'))\n        self.assertEqual(o[2],six.b('    source_type: file source: %s' % tmpfile.name))\n        self.assertEqual(o[3],six.b('  Fields:'))\n        self.assertEqual(o[4], six.b('    `name` - text'))\n        self.assertEqual(o[5], six.b('    `value 1` - int'))\n        self.assertEqual(o[6], six.b('    `value2` - int'))\n\n        self.cleanup(tmpfile)\n\n    def test_column_analysis_with_header(self):\n        tmpfile = self.create_file_with_data(sample_data_with_header)\n        cmd = Q_EXECUTABLE + ' -d , \"select c1 from %s\" -A -H' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertNotEqual(retcode, 0)\n        self.assertEqual(len(o),7)\n        self.assertEqual(len(e),2)\n        self.assertEqual(o[0], six.b('Table: %s' % tmpfile.name))\n        self.assertEqual(o[1],six.b('  Sources:'))\n        self.assertEqual(o[2],six.b('    source_type: file source: %s' % tmpfile.name))\n        self.assertEqual(o[3],six.b('  Fields:'))\n        self.assertEqual(o[4], six.b('    `name` - text'))\n        self.assertEqual(o[5], six.b('    `value1` - int'))\n        self.assertEqual(o[6], six.b('    `value2` - int'))\n\n        self.assertEqual(e[0],six.b('query error: no such column: c1'))\n        self.assertTrue(e[1].startswith(six.b('Warning - There seems to be a ')))\n\n        self.cleanup(tmpfile)\n\n\n\nclass StdInTests(AbstractQTestCase):\n\n    def test_stdin_input(self):\n        cmd = six.b('printf \"%s\" | ' + Q_EXECUTABLE + ' -d , \"select c1,c2,c3 from -\"') % sample_data_no_header\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0], sample_data_rows[0])\n        self.assertEqual(o[1], sample_data_rows[1])\n        self.assertEqual(o[2], sample_data_rows[2])\n\n    def test_attempt_to_unzip_stdin(self):\n        tmpfile = self.create_file_with_data(\n            six.b('\\x1f\\x8b\\x08\\x08\\xf2\\x18\\x12S\\x00\\x03xxxxxx\\x003\\xe42\\xe22\\xe62\\xe12\\xe52\\xe32\\xe7\\xb2\\xe0\\xb2\\xe424\\xe0\\x02\\x00\\xeb\\xbf\\x8a\\x13\\x15\\x00\\x00\\x00'))\n\n        cmd = 'cat %s | ' % tmpfile.name + Q_EXECUTABLE + ' -z \"select sum(c1),avg(c1) from -\"'\n\n        retcode, o, e = run_command(cmd)\n        self.assertTrue(retcode != 0)\n        self.assertTrue(len(o) == 0)\n        self.assertTrue(len(e) == 1)\n\n        self.assertEqual(e[0],six.b('Cannot decompress standard input. Pipe the input through zcat in order to decompress.'))\n\n        self.cleanup(tmpfile)\n\nclass QuotingTests(AbstractQTestCase):\n    def test_non_quoted_values_in_quoted_data(self):\n        tmp_data_file = self.create_file_with_data(sample_quoted_data)\n\n        cmd = Q_EXECUTABLE + ' -d \" \" \"select c1 from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),4)\n\n        self.assertTrue(o[0],'non_quoted')\n        self.assertTrue(o[1],'control-value-1')\n        self.assertTrue(o[2],'non-quoted-value')\n        self.assertTrue(o[3],'control-value-1')\n\n        self.cleanup(tmp_data_file)\n\n    def test_regular_quoted_values_in_quoted_data(self):\n        tmp_data_file = self.create_file_with_data(sample_quoted_data)\n\n        cmd = Q_EXECUTABLE + ' -d \" \" \"select c2 from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),4)\n\n        self.assertTrue(o[0],'regular_double_quoted')\n        self.assertTrue(o[1],'control-value-2')\n        self.assertTrue(o[2],'this is a quoted value')\n        self.assertTrue(o[3],'control-value-2')\n\n        self.cleanup(tmp_data_file)\n\n    def test_double_double_quoted_values_in_quoted_data(self):\n        tmp_data_file = self.create_file_with_data(sample_quoted_data)\n\n        cmd = Q_EXECUTABLE + ' -d \" \" \"select c3 from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),4)\n\n        self.assertTrue(o[0],'double_double_quoted')\n        self.assertTrue(o[1],'control-value-3')\n        self.assertTrue(o[2],'this is a \"double double\" quoted value')\n        self.assertTrue(o[3],'control-value-3')\n\n        self.cleanup(tmp_data_file)\n\n    def test_escaped_double_quoted_values_in_quoted_data(self):\n        tmp_data_file = self.create_file_with_data(sample_quoted_data)\n\n        cmd = Q_EXECUTABLE + ' -d \" \" \"select c4 from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),4)\n\n        self.assertTrue(o[0],'escaped_double_quoted')\n        self.assertTrue(o[1],'control-value-4')\n        self.assertTrue(o[2],'this is an escaped \"quoted value\"')\n        self.assertTrue(o[3],'control-value-4')\n\n        self.cleanup(tmp_data_file)\n\n    def test_none_input_quoting_mode_in_relaxed_mode(self):\n        tmp_data_file = self.create_file_with_data(sample_quoted_data2)\n\n        cmd = Q_EXECUTABLE + ' -d \" \" -m relaxed -D , -w none -W none \"select * from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b('\"quoted,data\",23'))\n        self.assertEqual(o[1],six.b('unquoted-data,54,'))\n\n        self.cleanup(tmp_data_file)\n\n    def test_none_input_quoting_mode_in_strict_mode(self):\n        tmp_data_file = self.create_file_with_data(sample_quoted_data2)\n\n        cmd = Q_EXECUTABLE + ' -d \" \" -m strict -D , -w none \"select * from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertNotEqual(retcode,0)\n        self.assertEqual(len(e),1)\n        self.assertEqual(len(o),0)\n\n        self.assertTrue(e[0].startswith(six.b('Strict mode. Column Count is expected to identical')))\n\n        self.cleanup(tmp_data_file)\n\n    def test_minimal_input_quoting_mode(self):\n        tmp_data_file = self.create_file_with_data(sample_quoted_data2)\n\n        cmd = Q_EXECUTABLE + ' -d \" \" -D , -w minimal \"select * from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b('quoted data,23'))\n        self.assertEqual(o[1],six.b('unquoted-data,54'))\n\n        self.cleanup(tmp_data_file)\n\n    def test_all_input_quoting_mode(self):\n        tmp_data_file = self.create_file_with_data(sample_quoted_data2)\n\n        cmd = Q_EXECUTABLE + ' -d \" \" -D , -w all \"select * from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b('quoted data,23'))\n        self.assertEqual(o[1],six.b('unquoted-data,54'))\n\n        self.cleanup(tmp_data_file)\n\n    def test_incorrect_input_quoting_mode(self):\n        tmp_data_file = self.create_file_with_data(sample_quoted_data2)\n\n        cmd = Q_EXECUTABLE + ' -d \" \" -D , -w unknown_wrapping_mode \"select * from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertNotEqual(retcode,0)\n        self.assertEqual(len(e),1)\n        self.assertEqual(len(o),0)\n\n        self.assertTrue(e[0].startswith(six.b('Input quoting mode can only be one of all,minimal,none')))\n        self.assertTrue(six.b('unknown_wrapping_mode') in e[0])\n\n        self.cleanup(tmp_data_file)\n\n    def test_none_output_quoting_mode(self):\n        tmp_data_file = self.create_file_with_data(sample_quoted_data2)\n\n        cmd = Q_EXECUTABLE + ' -d \" \" -D , -w all -W none \"select * from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b('quoted data,23'))\n        self.assertEqual(o[1],six.b('unquoted-data,54'))\n\n        self.cleanup(tmp_data_file)\n\n    def test_minimal_output_quoting_mode__without_need_to_quote_in_output(self):\n        tmp_data_file = self.create_file_with_data(sample_quoted_data2)\n\n        cmd = Q_EXECUTABLE + ' -d \" \" -D , -w all -W minimal \"select * from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b('quoted data,23'))\n        self.assertEqual(o[1],six.b('unquoted-data,54'))\n\n        self.cleanup(tmp_data_file)\n\n    def test_minimal_output_quoting_mode__with_need_to_quote_in_output_due_to_delimiter(self):\n        tmp_data_file = self.create_file_with_data(sample_quoted_data2)\n\n        # output delimiter is set to space, so the output will contain it\n        cmd = Q_EXECUTABLE + ' -d \" \" -D \" \" -w all -W minimal \"select * from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b('\"quoted data\" 23'))\n        self.assertEqual(o[1],six.b('unquoted-data 54'))\n\n        self.cleanup(tmp_data_file)\n\n    def test_minimal_output_quoting_mode__with_need_to_quote_in_output_due_to_newline(self):\n        tmp_data_file = self.create_file_with_data(sample_quoted_data2_with_newline)\n\n        # Delimiter is set to colon (:), so it will not be inside the data values (this will make sure that the newline is the one causing the quoting)\n        cmd = Q_EXECUTABLE + \" -d ':' -w all -W minimal \\\"select c1,c2,replace(c1,'with' || x'0a' || 'a new line inside it','NEWLINE-REMOVED') from %s\\\"\" % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),3)\n\n        self.assertEqual(o[0],six.b('\"quoted data with'))\n        # Notice that the third column here is not quoted, because we replaced the newline with something else\n        self.assertEqual(o[1],six.b('a new line inside it\":23:quoted data NEWLINE-REMOVED'))\n        self.assertEqual(o[2],six.b('unquoted-data:54:unquoted-data'))\n\n        self.cleanup(tmp_data_file)\n\n    def test_nonnumeric_output_quoting_mode(self):\n        tmp_data_file = self.create_file_with_data(sample_quoted_data2)\n\n        cmd = Q_EXECUTABLE + ' -d \" \" -D , -w all -W nonnumeric \"select * from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b('\"quoted data\",23'))\n        self.assertEqual(o[1],six.b('\"unquoted-data\",54'))\n\n        self.cleanup(tmp_data_file)\n\n    def test_all_output_quoting_mode(self):\n        tmp_data_file = self.create_file_with_data(sample_quoted_data2)\n\n        cmd = Q_EXECUTABLE + ' -d \" \" -D , -w all -W all \"select * from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b('\"quoted data\",\"23\"'))\n        self.assertEqual(o[1],six.b('\"unquoted-data\",\"54\"'))\n\n        self.cleanup(tmp_data_file)\n\n    def _internal_test_consistency_of_chaining_output_to_input(self,input_data,input_wrapping_mode,output_wrapping_mode):\n\n        tmp_data_file = self.create_file_with_data(input_data)\n\n        basic_cmd = Q_EXECUTABLE + ' -w %s -W %s \"select * from -\"' % (input_wrapping_mode,output_wrapping_mode)\n        chained_cmd = 'cat %s | %s | %s | %s' % (tmp_data_file.name,basic_cmd,basic_cmd,basic_cmd)\n\n        retcode, o, e = run_command(chained_cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(six.b(\"\\n\").join(o),input_data)\n\n        self.cleanup(tmp_data_file)\n\n    def test_consistency_of_chaining_minimal_wrapping_to_minimal_wrapping(self):\n        input_data = six.b('\"quoted data\" 23\\nunquoted-data 54')\n        self._internal_test_consistency_of_chaining_output_to_input(input_data,'minimal','minimal')\n\n    def test_consistency_of_chaining_all_wrapping_to_all_wrapping(self):\n        input_data = six.b('\"quoted data\" \"23\"\\n\"unquoted-data\" \"54\"')\n        self._internal_test_consistency_of_chaining_output_to_input(input_data,'all','all')\n\n    def test_input_field_quoting_and_data_types_with_encoding(self):\n        OUTPUT_ENCODING = 'utf-8'\n\n        # Checks combination of minimal input field quoting, with special characters that need to be decoded -\n        # Both content and proper data types are verified\n        data = six.b('111,22.22,\"testing text with special characters - citt\\xc3\\xa0 \",http://somekindofurl.com,12.13.14.15,12.1\\n')\n        tmp_data_file = self.create_file_with_data(data)\n\n        cmd = Q_EXECUTABLE + ' -d , \"select * from %s\" -E %s' % (tmp_data_file.name,OUTPUT_ENCODING)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),1)\n\n        self.assertEqual(o[0].decode('utf-8'),u'111,22.22,testing text with special characters - citt\\xe0 ,http://somekindofurl.com,12.13.14.15,12.1')\n\n        cmd = Q_EXECUTABLE + ' -d , \"select * from %s\" -A' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),10)\n\n        self.assertEqual(o[0],six.b('Table: %s' % tmp_data_file.name))\n        self.assertEqual(o[1],six.b('  Sources:'))\n        self.assertEqual(o[2],six.b('    source_type: file source: %s' % tmp_data_file.name))\n        self.assertEqual(o[3],six.b('  Fields:'))\n        self.assertEqual(o[4],six.b('    `c1` - int'))\n        self.assertEqual(o[5],six.b('    `c2` - real'))\n        self.assertEqual(o[6],six.b('    `c3` - text'))\n        self.assertEqual(o[7],six.b('    `c4` - text'))\n        self.assertEqual(o[8],six.b('    `c5` - text'))\n        self.assertEqual(o[9],six.b('    `c6` - real'))\n\n        self.cleanup(tmp_data_file)\n\n    def test_multiline_double_double_quoted_values_in_quoted_data(self):\n        tmp_data_file = self.create_file_with_data(sample_quoted_data)\n\n        # FIXME Need to convert \\0a to proper encoding suitable for the person running the tests.\n        cmd = Q_EXECUTABLE + ' -d \" \" \"select replace(c5,X\\'0A\\',\\'::\\') from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),4)\n\n        self.assertTrue(o[0],six.b('multiline_double_double_quoted'))\n        self.assertTrue(o[1],six.b('control-value-5'))\n        self.assertTrue(o[2],six.b('this is a double double quoted \"multiline\\n value\".'))\n        self.assertTrue(o[3],six.b('control-value-5'))\n\n        self.cleanup(tmp_data_file)\n\n    def test_multiline_escaped_double_quoted_values_in_quoted_data(self):\n        tmp_data_file = self.create_file_with_data(sample_quoted_data)\n\n        # FIXME Need to convert \\0a to proper encoding suitable for the person running the tests.\n        cmd = Q_EXECUTABLE + ' -d \" \" \"select replace(c6,X\\'0A\\',\\'::\\') from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),4)\n\n        self.assertTrue(o[0],'multiline_escaped_double_quoted')\n        self.assertTrue(o[1],'control-value-6')\n        self.assertTrue(o[2],'this is an escaped \"multiline:: value\".')\n        self.assertTrue(o[3],'control-value-6')\n\n        self.cleanup(tmp_data_file)\n\n    def test_disable_double_double_quoted_data_flag__values(self):\n        # This test (and flag) is meant to verify backward comptibility only. It is possible that\n        # this flag will be removed completely in the future\n\n        tmp_data_file = self.create_file_with_data(double_double_quoted_data)\n\n        cmd = Q_EXECUTABLE + ' -d \" \" --disable-double-double-quoting \"select c2 from %s\" -W none' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b('double_double_quoted'))\n        self.assertEqual(o[1],six.b('this is a quoted value with \"double'))\n\n        cmd = Q_EXECUTABLE + ' -d \" \" --disable-double-double-quoting \"select c3 from %s\" -W none' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b(''))\n        self.assertEqual(o[1],six.b('double'))\n\n        cmd = Q_EXECUTABLE + ' -d \" \" --disable-double-double-quoting \"select c4 from %s\" -W none' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b(''))\n        self.assertEqual(o[1],six.b('quotes\"\"\"'))\n\n        self.cleanup(tmp_data_file)\n\n    def test_disable_escaped_double_quoted_data_flag__values(self):\n        # This test (and flag) is meant to verify backward comptibility only. It is possible that\n        # this flag will be removed completely in the future\n\n        tmp_data_file = self.create_file_with_data(escaped_double_quoted_data)\n\n        cmd = Q_EXECUTABLE + ' -d \" \" --disable-escaped-double-quoting \"select c2 from %s\" -W none' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b('escaped_double_quoted'))\n        self.assertEqual(o[1],six.b('this is a quoted value with \\\\escaped'))\n\n        cmd = Q_EXECUTABLE + ' -d \" \" --disable-escaped-double-quoting \"select c3 from %s\" -W none' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b(''))\n        self.assertEqual(o[1],six.b('double'))\n\n        cmd = Q_EXECUTABLE + ' -d \" \" --disable-escaped-double-quoting \"select c4 from %s\" -W none' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b(''))\n        self.assertEqual(o[1],six.b('quotes\\\\\"\"'))\n\n        self.cleanup(tmp_data_file)\n\n    def test_combined_quoted_data_flags__number_of_columns_detected(self):\n        # This test (and flags) is meant to verify backward comptibility only. It is possible that\n        # these flags will be removed completely in the future\n        tmp_data_file = self.create_file_with_data(combined_quoted_data)\n\n        cmd = Q_EXECUTABLE + ' -d \" \" --disable-double-double-quoting --disable-escaped-double-quoting \"select * from %s\" -A' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        o = o[o.index(six.b('  Fields:'))+1:]\n\n        self.assertEqual(len(o),7) # found 7 fields\n\n        cmd = Q_EXECUTABLE + ' -d \" \" --disable-escaped-double-quoting \"select * from %s\" -A' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        o = o[o.index(six.b('  Fields:'))+1:]\n\n        self.assertEqual(len(o),5) # found 5 fields\n\n        cmd = Q_EXECUTABLE + ' -d \" \" --disable-double-double-quoting \"select * from %s\" -A' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        o = o[o.index(six.b('  Fields:'))+1:]\n\n        self.assertEqual(len(o),5) # found 5 fields\n\n        cmd = Q_EXECUTABLE + ' -d \" \" \"select * from %s\" -A' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        o = o[o.index(six.b('  Fields:'))+1:]\n\n        self.assertEqual(len(o),3) # found only 3 fields, which is the correct amount\n\n        self.cleanup(tmp_data_file)\n\n\nclass EncodingTests(AbstractQTestCase):\n\n    def test_utf8_with_bom_encoding(self):\n        utf_8_data_with_bom = six.b('\\xef\\xbb\\xbf\"typeid\",\"limit\",\"apcost\",\"date\",\"checkpointId\"\\n\"1\",\"2\",\"5\",\"1,2,3,4,5,6,7\",\"3000,3001,3002\"\\n\"2\",\"2\",\"5\",\"1,2,3,4,5,6,7\",\"3003,3004,3005\"\\n')\n        tmp_data_file = self.create_file_with_data(utf_8_data_with_bom,encoding=None)\n\n        cmd = Q_EXECUTABLE + ' -d , -H -O -e utf-8-sig \"select * from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(e),0)\n        self.assertEqual(len(o),3)\n\n        self.assertEqual(o[0],six.b('typeid,limit,apcost,date,checkpointId'))\n        self.assertEqual(o[1],six.b('1,2,5,\"1,2,3,4,5,6,7\",\"3000,3001,3002\"'))\n        self.assertEqual(o[2],six.b('2,2,5,\"1,2,3,4,5,6,7\",\"3003,3004,3005\"'))\n\n        self.cleanup(tmp_data_file)\n\n\nclass QrcTests(AbstractQTestCase):\n\n    def test_explicit_qrc_filename_not_found(self):\n        non_existent_filename = str(uuid.uuid4())\n        env_to_inject = { 'QRC_FILENAME': non_existent_filename}\n        cmd = Q_EXECUTABLE + ' \"select 1\"'\n        retcode, o, e = run_command(cmd, env_to_inject=env_to_inject)\n\n        self.assertEqual(retcode, 244)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n        self.assertTrue(e[0] == six.b('QRC_FILENAME env var exists, but cannot find qrc file at %s' % non_existent_filename))\n\n    def test_explicit_qrc_filename_that_exists(self):\n        tmp_qrc_file = self.create_file_with_data(six.b('''[options]\noutput_delimiter=|\n'''))\n        env_to_inject = { 'QRC_FILENAME': tmp_qrc_file.name}\n        cmd = Q_EXECUTABLE + ' \"select 1,2\"'\n        retcode, o, e = run_command(cmd, env_to_inject=env_to_inject)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertTrue(o[0] == six.b('1|2'))\n\n        self.cleanup(tmp_qrc_file)\n\n    def test_all_default_options(self):\n        # Create a qrc file that contains all default values inside the qrc file, but with some different values than the regular defaults\n        tmp_qrc_file = self.create_file_with_data(six.b('''[options]\nanalyze_only=True\nbeautify=True\ncaching_mode=readwrite\ncolumn_count=32\ndelimiter=,\ndisable_column_type_detection=True\ndisable_double_double_quoting=False\ndisable_escaped_double_quoting=False\nencoding=ascii\nformatting=xxx\ngzipped=True\ninput_quoting_mode=all\nkeep_leading_whitespace_in_values=True\nlist_user_functions=True\nmax_attached_sqlite_databases=888\nmax_column_length_limit=8888\nmode=strict\noutput_delimiter=|\noutput_encoding=utf-8\noutput_header=True\noutput_quoting_mode=all\noverwrite_qsql=False\npipe_delimited=True\npipe_delimited_output=True\nquery_encoding=ascii\nquery_filename=query-filename\nsave_db_to_disk_filename=save-db-to-disk-filename\nskip_header=True\ntab_delimited=True\ntab_delimited_output=true\nverbose=True\nwith_universal_newlines=True\n'''))\n        env_to_inject = { 'QRC_FILENAME': tmp_qrc_file.name}\n        cmd = Q_EXECUTABLE + ' --dump-defaults'\n        retcode, o, e = run_command(cmd, env_to_inject=env_to_inject)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 34)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0],six.b('[options]'))\n        o = o[1:]\n\n        m = {}\n        for r in o:\n            key,val = r.split(six.b(\"=\"),1)\n            m[key] = val\n\n        self.assertEqual(m[six.b('analyze_only')],six.b('True'))\n        self.assertEqual(m[six.b('beautify')],six.b('True'))\n        self.assertEqual(m[six.b('caching_mode')],six.b('readwrite'))\n        self.assertEqual(m[six.b('column_count')],six.b('32'))\n        self.assertEqual(m[six.b('delimiter')],six.b(','))\n        self.assertEqual(m[six.b('disable_column_type_detection')],six.b('True'))\n        self.assertEqual(m[six.b('disable_double_double_quoting')],six.b('False'))\n        self.assertEqual(m[six.b('disable_escaped_double_quoting')],six.b('False'))\n        self.assertEqual(m[six.b('encoding')],six.b('ascii'))\n        self.assertEqual(m[six.b('formatting')],six.b('xxx'))\n        self.assertEqual(m[six.b('gzipped')],six.b('True'))\n        self.assertEqual(m[six.b('input_quoting_mode')],six.b('all'))\n        self.assertEqual(m[six.b('keep_leading_whitespace_in_values')],six.b('True'))\n        self.assertEqual(m[six.b('list_user_functions')],six.b('True'))\n        self.assertEqual(m[six.b('max_attached_sqlite_databases')],six.b('888'))\n        self.assertEqual(m[six.b('max_column_length_limit')],six.b('8888'))\n        self.assertEqual(m[six.b('mode')],six.b('strict'))\n        self.assertEqual(m[six.b('output_delimiter')],six.b('|'))\n        self.assertEqual(m[six.b('output_encoding')],six.b('utf-8'))\n        self.assertEqual(m[six.b('output_header')],six.b('True'))\n        self.assertEqual(m[six.b('output_quoting_mode')],six.b('all'))\n        self.assertEqual(m[six.b('overwrite_qsql')],six.b('False'))\n        self.assertEqual(m[six.b('pipe_delimited')],six.b('True'))\n        self.assertEqual(m[six.b('pipe_delimited_output')],six.b('True'))\n        self.assertEqual(m[six.b('query_encoding')],six.b('ascii'))\n        self.assertEqual(m[six.b('query_filename')],six.b('query-filename'))\n        self.assertEqual(m[six.b('save_db_to_disk_filename')],six.b('save-db-to-disk-filename'))\n        self.assertEqual(m[six.b('skip_header')],six.b('True'))\n        self.assertEqual(m[six.b('tab_delimited')],six.b('True'))\n        self.assertEqual(m[six.b('tab_delimited_output')],six.b('True'))\n        self.assertEqual(m[six.b('verbose')],six.b('True'))\n        self.assertEqual(m[six.b('with_universal_newlines')],six.b('True'))\n\n        self.cleanup(tmp_qrc_file)\n\n    def test_caching_readwrite_using_qrc_file(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n        tmpfile_folder = os.path.dirname(tmpfile.name)\n        tmpfile_filename = os.path.basename(tmpfile.name)\n        expected_cache_filename = os.path.join(tmpfile_folder,tmpfile_filename + '.qsql')\n\n        cmd = Q_EXECUTABLE + ' -d , \"select * from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(o),3)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0],six.b('a,1,0'))\n        self.assertEqual(o[1],six.b('b,2,0'))\n        self.assertEqual(o[2],six.b('c,,0'))\n\n        # Ensure default does not create a cache file\n        self.assertTrue(not os.path.exists(expected_cache_filename))\n\n        tmp_qrc_file = self.create_file_with_data(six.b('''[options]\ncaching_mode=readwrite\n'''))\n        env_to_inject = { 'QRC_FILENAME': tmp_qrc_file.name}\n        cmd = Q_EXECUTABLE + ' -d , \"select * from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd, env_to_inject=env_to_inject)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o),3)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0],six.b('a,1,0'))\n        self.assertEqual(o[1],six.b('b,2,0'))\n        self.assertEqual(o[2],six.b('c,,0'))\n\n        # Ensure that qrc file caching is being used and caching is activated (cache file should exist)\n        self.assertTrue(os.path.exists(expected_cache_filename))\n\n        self.cleanup(tmp_qrc_file)\n        self.cleanup(tmpfile)\n\n\nclass QsqlUsageTests(AbstractQTestCase):\n\n    def test_concatenate_same_qsql_file_with_single_table(self):\n        numbers = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 10001)]\n\n        qsql_file_data = self.arrays_to_qsql_file_content([six.b('aa'), six.b('bb'), six.b('cc')], numbers)\n\n        tmpfile = self.create_file_with_data(qsql_file_data,suffix='.qsql')\n\n        cmd = Q_EXECUTABLE + ' -t \"select count(*) from (select * from %s union all select * from %s)\"' % (tmpfile.name,tmpfile.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('20000'))\n\n    def test_query_qsql_with_single_table(self):\n        numbers = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 10001)]\n\n        qsql_file_data = self.arrays_to_qsql_file_content([six.b('aa'), six.b('bb'), six.b('cc')], numbers)\n\n        tmpfile = self.create_file_with_data(qsql_file_data)\n\n        cmd = Q_EXECUTABLE + ' -t \"select sum(aa),sum(bb),sum(cc) from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('50005000\\t50005000\\t50005000'))\n\n    def test_query_qsql_with_single_table_with_explicit_non_existent_tablename(self):\n        numbers = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 10001)]\n\n        qsql_file_data = self.arrays_to_qsql_file_content([six.b('aa'), six.b('bb'), six.b('cc')], numbers)\n\n        tmpfile = self.create_file_with_data(qsql_file_data)\n\n        c = sqlite3.connect(tmpfile.name)\n        actual_table_name = c.execute('select temp_table_name from _qcatalog').fetchall()[0][0]\n        c.close()\n\n\n        cmd = '%s -t \"select sum(aa),sum(bb),sum(cc) from %s:::non-existent\"' % (Q_EXECUTABLE,tmpfile.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 84)\n        self.assertEqual(len(o),0)\n        self.assertEqual(len(e),1)\n        self.assertEqual(e[0],six.b('Table non-existent could not be found in qsql file %s . Existing table names: %s' % (tmpfile.name,actual_table_name)))\n\n    def test_query_qsql_with_single_table_with_explicit_table_name(self):\n        numbers = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 10001)]\n\n        qsql_file_data = self.arrays_to_qsql_file_content([six.b('aa'), six.b('bb'), six.b('cc')], numbers)\n\n        tmpfile = self.create_file_with_data(qsql_file_data)\n\n        c = sqlite3.connect(tmpfile.name)\n        actual_table_name = c.execute('select temp_table_name from _qcatalog').fetchall()[0][0]\n        c.close()\n\n\n        cmd = '%s -t \"select sum(aa),sum(bb),sum(cc) from %s:::%s\"' % (Q_EXECUTABLE,tmpfile.name,actual_table_name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o),1)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0],six.b('50005000\\t50005000\\t50005000'))\n\n    def test_query_multi_qsql_with_single_table(self):\n        numbers1 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 10001)]\n        qsql_file_data1 = self.arrays_to_qsql_file_content([six.b('aa'), six.b('bb'), six.b('cc')], numbers1)\n        tmpfile1 = self.create_file_with_data(qsql_file_data1,suffix='.qsql')\n\n        numbers2 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 11)]\n        qsql_file_data2 = self.arrays_to_qsql_file_content([six.b('aa'), six.b('bb'), six.b('cc')], numbers2)\n        tmpfile2 = self.create_file_with_data(qsql_file_data2,suffix='.qsql')\n\n        cmd = Q_EXECUTABLE + ' -t \"select sum(large_file.aa),sum(large_file.bb),sum(large_file.cc) from %s small_file left join %s large_file on (large_file.aa == small_file.bb)\"' % (tmpfile2.name,tmpfile1.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('55\\t55\\t55'))\n\n    def test_query_concatenated_qsqls_each_with_single_table(self):\n        numbers1 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 10001)]\n        qsql_file_data1 = self.arrays_to_qsql_file_content([six.b('aa'), six.b('bb'), six.b('cc')], numbers1)\n        tmpfile1 = self.create_file_with_data(qsql_file_data1,suffix='.qsql')\n\n        numbers2 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 11)]\n        qsql_file_data2 = self.arrays_to_qsql_file_content([six.b('aa'), six.b('bb'), six.b('cc')], numbers2)\n        tmpfile2 = self.create_file_with_data(qsql_file_data2,suffix='.qsql')\n\n        cmd = Q_EXECUTABLE + ' -t \"select sum(aa),sum(bb),sum(cc) from (select * from %s union all select * from %s)\"' % (tmpfile2.name,tmpfile1.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('50005055\\t50005055\\t50005055'))\n\n    def test_concatenated_qsql_and_data_stream__column_names_mismatch(self):\n        N1 = 10000\n        N2 = 100\n\n        numbers1 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, N1 + 1)]\n        csv_file_data1 = self.arrays_to_csv_file_content(six.b('\\t'),[six.b('aa'), six.b('bb'), six.b('cc')], numbers1)\n        tmpfile1 = self.create_file_with_data(csv_file_data1)\n        expected_cache_filename1 = '%s.qsql' % tmpfile1.name\n\n        cmd = Q_EXECUTABLE + ' -H -t \"select count(*) from %s\" -C readwrite' % tmpfile1.name\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 0)\n        self.assertTrue(os.path.exists(expected_cache_filename1))\n\n        cmd = 'seq 1 %s | %s -c 1 \"select count(*) from (select * from %s UNION ALL select * from -)\"' % (N2, Q_EXECUTABLE,expected_cache_filename1)\n\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 1)\n        self.assertEqual(len(o),0)\n        self.assertEqual(len(e),1)\n        self.assertEqual(e[0],six.b('query error: SELECTs to the left and right of UNION ALL do not have the same number of result columns'))\n\n    def test_concatenated_qsql_and_data_stream(self):\n        N1 = 10000\n        N2 = 100\n\n        numbers1 = [[six.b(str(i))] for i in range(1, N1 + 1)]\n        csv_file_data1 = self.arrays_to_csv_file_content(six.b('\\t'),[six.b('c1')], numbers1)\n        tmpfile1 = self.create_file_with_data(csv_file_data1)\n        expected_cache_filename1 = '%s.qsql' % tmpfile1.name\n\n        cmd = Q_EXECUTABLE + ' -H -t \"select count(*) from %s\" -C readwrite' % tmpfile1.name\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 0)\n        self.assertTrue(os.path.exists(expected_cache_filename1))\n\n        cmd = 'seq 1 %s | %s -t -c 1 \"select count(*),sum(c1) from (select * from %s UNION ALL select * from -)\"' % (N2, Q_EXECUTABLE,expected_cache_filename1)\n\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o),1)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0],six.b('%s\\t%s' % (N1+N2,sum(range(1,N1+1)) + sum(range(1,N2+1)))))\n\n    def test_concatenated_qsql_and_data_stream__explicit_table_name(self):\n        N1 = 10000\n        N2 = 100\n\n        numbers1 = [[six.b(str(i))] for i in range(1, N1 + 1)]\n        csv_file_data1 = self.arrays_to_csv_file_content(six.b('\\t'),[six.b('c1')], numbers1)\n        tmpfile1 = self.create_file_with_data(csv_file_data1)\n        tmpfile1_expected_table_name = os.path.basename(tmpfile1.name)\n\n        expected_cache_filename1 = '%s.qsql' % tmpfile1.name\n\n        cmd = Q_EXECUTABLE + ' -H -t \"select count(*) from %s\" -C readwrite' % tmpfile1.name\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 0)\n        self.assertTrue(os.path.exists(expected_cache_filename1))\n\n        cmd = 'seq 1 %s | %s -t -c 1 \"select count(*),sum(c1) from (select * from %s:::%s UNION ALL select * from -)\"' % (N2, Q_EXECUTABLE,expected_cache_filename1,tmpfile1_expected_table_name)\n\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o),1)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0],six.b('%s\\t%s' % (N1+N2,sum(range(1,N1+1)) + sum(range(1,N2+1)))))\n\n    def test_write_to_qsql__check_chosen_table_name(self):\n        numbers1 = [[six.b(str(i))] for i in range(1, 10001)]\n        csv_file_data1 = self.arrays_to_csv_file_content(six.b('\\t'),[six.b('c1')], numbers1)\n        tmpfile1 = self.create_file_with_data(csv_file_data1)\n        expected_cache_filename1 = '%s.qsql' % tmpfile1.name\n\n        cmd = Q_EXECUTABLE + ' -c 1 -H -t \"select count(*) from %s\" -C readwrite' % tmpfile1.name\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 0)\n        self.assertTrue(os.path.exists(expected_cache_filename1))\n\n        c = sqlite3.connect(expected_cache_filename1)\n        qcatalog_entries = c.execute('select temp_table_name from _qcatalog').fetchall()\n        self.assertEqual(len(qcatalog_entries),1)\n        self.assertEqual(qcatalog_entries[0][0],os.path.basename(tmpfile1.name))\n\n    def test_concatenated_mixes_qsql_with_single_table_and_csv(self):\n        numbers1 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 10001)]\n        csv_file_data1 = self.arrays_to_csv_file_content(six.b('\\t'),[six.b('aa'), six.b('bb'), six.b('cc')], numbers1)\n        tmpfile1 = self.create_file_with_data(csv_file_data1)\n        expected_cache_filename1 = '%s.qsql' % tmpfile1.name\n\n        numbers2 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 11)]\n        csv_file_data2 = self.arrays_to_csv_file_content(six.b('\\t'),[six.b('aa'), six.b('bb'), six.b('cc')], numbers2)\n        tmpfile2 = self.create_file_with_data(csv_file_data2)\n        expected_cache_filename2 = '%s.qsql' % tmpfile2.name\n\n\n        cmd = Q_EXECUTABLE + ' -H -t \"select count(*) from %s\" -C readwrite' % tmpfile1.name\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 0)\n        self.assertTrue(os.path.exists(expected_cache_filename1))\n\n        cmd = Q_EXECUTABLE + ' -H -t \"select count(*) from %s\" -C readwrite' % tmpfile2.name\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 0)\n        self.assertTrue(os.path.exists(expected_cache_filename2))\n\n        # csv and qsql files prepared. now test all four combinations\n\n        cmd = Q_EXECUTABLE + ' -O -H -t \"select count(*) cnt,sum(aa) sum_aa,sum(bb) sum_bb,sum(cc) sum_cc from (select * from %s union all select * from %s)\"' % (tmpfile1.name,tmpfile2.name)\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o),2)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0],six.b('cnt\\tsum_aa\\tsum_bb\\tsum_cc'))\n        self.assertEqual(o[1],six.b('10010\\t50005055\\t50005055\\t50005055'))\n\n        cmd = Q_EXECUTABLE + ' -O -H -t \"select count(*) cnt,sum(aa) sum_aa,sum(bb) sum_bb,sum(cc) sum_cc from (select * from %s union all select * from %s.qsql)\"' % (tmpfile1.name,tmpfile2.name)\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o),2)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0],six.b('cnt\\tsum_aa\\tsum_bb\\tsum_cc'))\n        self.assertEqual(o[1],six.b('10010\\t50005055\\t50005055\\t50005055'))\n\n        cmd = Q_EXECUTABLE + ' -O -H -t \"select count(*) cnt,sum(aa) sum_aa,sum(bb) sum_bb,sum(cc) sum_cc from (select * from %s.qsql union all select * from %s)\"' % (tmpfile1.name,tmpfile2.name)\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o),2)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0],six.b('cnt\\tsum_aa\\tsum_bb\\tsum_cc'))\n        self.assertEqual(o[1],six.b('10010\\t50005055\\t50005055\\t50005055'))\n\n        cmd = Q_EXECUTABLE + ' -O -H -t \"select count(*) cnt,sum(aa) sum_aa,sum(bb) sum_bb,sum(cc) sum_cc from (select * from %s.qsql union all select * from %s.qsql)\"' % (tmpfile1.name,tmpfile2.name)\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o),2)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0],six.b('cnt\\tsum_aa\\tsum_bb\\tsum_cc'))\n        self.assertEqual(o[1],six.b('10010\\t50005055\\t50005055\\t50005055'))\n\n    def test_analysis_of_concatenated_mixes_qsql_with_single_table_and_csv(self):\n        numbers1 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 10001)]\n        csv_file_data1 = self.arrays_to_csv_file_content(six.b('\\t'),[six.b('aa'), six.b('bb'), six.b('cc')], numbers1)\n        tmpfile1 = self.create_file_with_data(csv_file_data1)\n        expected_cache_filename1 = '%s.qsql' % tmpfile1.name\n\n        numbers2 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 11)]\n        csv_file_data2 = self.arrays_to_csv_file_content(six.b('\\t'),[six.b('aa'), six.b('bb'), six.b('cc')], numbers2)\n        tmpfile2 = self.create_file_with_data(csv_file_data2)\n        expected_cache_filename2 = '%s.qsql' % tmpfile2.name\n\n        cmd = Q_EXECUTABLE + ' -H -t \"select count(*) from %s\" -C readwrite' % tmpfile1.name\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 0)\n        self.assertTrue(os.path.exists(expected_cache_filename1))\n\n        cmd = Q_EXECUTABLE + ' -H -t \"select count(*) from %s\" -C readwrite' % tmpfile2.name\n        retcode, o, e = run_command(cmd)\n        self.assertEqual(retcode, 0)\n        self.assertTrue(os.path.exists(expected_cache_filename2))\n\n        # csv and qsql files prepared\n\n        # Test function, will be used multiple times, each time with a different combination\n\n        def do_check(caching_mode,\n                     file1_source_type,file1_table_postfix,file1_postfix,\n                     file2_source_type,file2_table_postfix,file2_postfix):\n            cmd = '%s -C %s -O -H -t \"select count(*) cnt,sum(aa) sum_aa,sum(bb) sum_bb,sum(cc) sum_cc from (select * from %s%s UNION ALL select * from %s%s)\" -A' % (\n                Q_EXECUTABLE,\n                caching_mode,\n                tmpfile1.name,\n                file1_table_postfix,\n                tmpfile2.name,\n                file2_table_postfix)\n\n            retcode, o, e = run_command(cmd)\n            self.assertEqual(retcode, 0)\n            self.assertEqual(len(o),14)\n            self.assertEqual(len(e),0)\n            self.assertEqual(o, [\n                six.b('Table: %s%s' % (tmpfile1.name,file1_table_postfix)),\n                six.b('  Sources:'),\n                six.b('    source_type: %s source: %s%s' % (file1_source_type,tmpfile1.name,file1_postfix)),\n                six.b('  Fields:'),\n                six.b('    `aa` - int'),\n                six.b('    `bb` - int'),\n                six.b('    `cc` - int'),\n                six.b('Table: %s%s' % (tmpfile2.name,file2_table_postfix)),\n                six.b('  Sources:'),\n                six.b('    source_type: %s source: %s%s' % (file2_source_type,tmpfile2.name,file2_postfix)),\n                six.b('  Fields:'),\n                six.b('    `aa` - int'),\n                six.b('    `bb` - int'),\n                six.b('    `cc` - int')])\n\n        # now test *the analysis results* of all four combinations, adding `-C read`, so the\n        # qsql will be used. Running with `-C none`, would have caused the qsql not to be used even if the qsql file exists\n\n        do_check(caching_mode='read',\n                 file1_source_type='qsql-file-with-original',file1_table_postfix='',file1_postfix='.qsql',\n                 file2_source_type='qsql-file-with-original',file2_table_postfix='',file2_postfix='.qsql')\n        do_check('read',\n                 file1_source_type='qsql-file-with-original',file1_table_postfix='',file1_postfix='.qsql',\n                 file2_source_type='qsql-file',file2_table_postfix='.qsql',file2_postfix='.qsql')\n        do_check('read',\n                 file1_source_type='qsql-file',file1_table_postfix='.qsql',file1_postfix='.qsql',\n                 file2_source_type='qsql-file-with-original',file2_table_postfix='',file2_postfix='.qsql')\n        do_check('read',\n                 file1_source_type='qsql-file',file1_table_postfix='.qsql',file1_postfix='.qsql',\n                 file2_source_type='qsql-file',file2_table_postfix='.qsql',file2_postfix='.qsql')\n\n        # Now test the all combinations again, this time with `-C none`, to make sure that by\n        # default, the qsql file is not used, and -A shows that fact\n\n        do_check(caching_mode='none',\n                 file1_source_type='file-with-unused-qsql',file1_table_postfix='',file1_postfix='',\n                 file2_source_type='file-with-unused-qsql',file2_table_postfix='',file2_postfix='')\n        do_check('none',\n                 file1_source_type='file-with-unused-qsql',file1_table_postfix='',file1_postfix='',\n                 file2_source_type='qsql-file',file2_table_postfix='.qsql',file2_postfix='.qsql')\n        do_check('none',\n                 file1_source_type='qsql-file',file1_table_postfix='.qsql',file1_postfix='.qsql',\n                 file2_source_type='file-with-unused-qsql',file2_table_postfix='',file2_postfix='')\n        do_check('none',\n                 file1_source_type='qsql-file',file1_table_postfix='.qsql',file1_postfix='.qsql',\n                 file2_source_type='qsql-file',file2_table_postfix='.qsql',file2_postfix='.qsql')\n\n    def test_mixed_qsql_with_single_table_and_csv__missing_header_parameter_for_csv(self):\n        numbers1 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 10001)]\n        qsql_file_data1 = self.arrays_to_qsql_file_content([six.b('aa'), six.b('bb'), six.b('cc')], numbers1)\n        tmpfile1 = self.create_file_with_data(qsql_file_data1,suffix='.qsql')\n\n        numbers2 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 11)]\n        csv_file_data2 = self.arrays_to_csv_file_content(six.b('\\t'),[six.b('aa'), six.b('bb'), six.b('cc')], numbers2)\n        tmpfile2 = self.create_file_with_data(csv_file_data2)\n\n        cmd = Q_EXECUTABLE + ' -t \"select sum(aa),sum(bb),sum(cc) from (select * from %s union all select * from %s)\"' % (tmpfile1.name,tmpfile2.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(e[0],six.b('Warning - There seems to be header line in the file, but -H has not been specified. All fields will be detected as text fields, and the header line will appear as part of the data'))\n        self.assertEqual(o[0],six.b('50005055.0\\t50005055.0\\t50005055.0'))\n\n    def test_qsql_with_multiple_tables_direct_use(self):\n        numbers1 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 10001)]\n        qsql_filename1 = self.create_qsql_file_with_content_and_return_filename([six.b('aa'), six.b('bb'), six.b('cc')],numbers1)\n        expected_stored_table_name1 = os.path.basename(qsql_filename1)[:-5]\n\n        numbers2 = [[six.b(str(i)), six.b(str(i)), six.b(str(i))] for i in range(1, 11)]\n        qsql_filename2 = self.create_qsql_file_with_content_and_return_filename([six.b('aa'), six.b('bb'), six.b('cc')],numbers2)\n        expected_stored_table_name2 = os.path.basename(qsql_filename2)[:-5]\n\n        qsql_with_multiple_tables = self.generate_tmpfile_name(suffix='.qsql')\n\n        cmd = '%s -t \"select sum(large_file.aa),sum(large_file.bb),sum(large_file.cc) from %s large_file left join %s small_file on (large_file.aa == small_file.bb)\" -S %s' % \\\n              (Q_EXECUTABLE,qsql_filename1,qsql_filename2,qsql_with_multiple_tables)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 4)\n        self.assertEqual(e[0], six.b('Going to save data into a disk database: %s' % qsql_with_multiple_tables))\n        self.assertTrue(e[1].startswith(six.b('Data has been saved into %s . Saving has taken' % qsql_with_multiple_tables)))\n        self.assertEqual(e[2],six.b('Query to run on the database: select sum(large_file.aa),sum(large_file.bb),sum(large_file.cc) from %s large_file left join %s small_file on (large_file.aa == small_file.bb);' % \\\n                                    (expected_stored_table_name1,expected_stored_table_name2)))\n        self.assertEqual(e[3],six.b('You can run the query directly from the command line using the following command: echo \"select sum(large_file.aa),sum(large_file.bb),sum(large_file.cc) from %s large_file left join %s small_file on (large_file.aa == small_file.bb)\" | sqlite3 %s' % \\\n                                    (expected_stored_table_name1,expected_stored_table_name2,qsql_with_multiple_tables)))\n\n        cmd = '%s -d , \"select count(*) cnt,sum(aa),sum(bb),sum(cc) from %s:::%s\"' % (Q_EXECUTABLE,qsql_with_multiple_tables,expected_stored_table_name1)\n        r, o, e = run_command(cmd)\n\n        self.assertEqual(r,0)\n        self.assertEqual(len(o),1)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0],six.b('10000,50005000,50005000,50005000'))\n\n    def test_direct_use_of_sqlite_db_with_one_table(self):\n        tmpfile = self.create_file_with_data(six.b(''),suffix='.sqlite')\n        os.remove(tmpfile.name)\n        c = sqlite3.connect(tmpfile.name)\n        c.execute(' create table mytable (x int, y int)').fetchall()\n        c.execute(' insert into mytable (x,y) values (100,200),(300,400)').fetchall()\n        c.commit()\n        c.close()\n\n        cmd = Q_EXECUTABLE + ' -t \"select sum(x),sum(y) from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('400\\t600'))\n\n        cmd = Q_EXECUTABLE + ' -t \"select sum(x),sum(y) from %s:::mytable\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('400\\t600'))\n\n    def test_direct_use_of_sqlite_db_with_one_table__nonexistent_table(self):\n        tmpfile = self.create_file_with_data(six.b(''),suffix='.sqlite')\n        os.remove(tmpfile.name)\n        c = sqlite3.connect(tmpfile.name)\n        c.execute(' create table some_numbers (x int, y int)').fetchall()\n        c.execute(' insert into some_numbers (x,y) values (100,200),(300,400)').fetchall()\n        c.commit()\n        c.close()\n\n        cmd = Q_EXECUTABLE + ' -t \"select sum(x),sum(y) from %s:::non_existent\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 85)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(e[0],six.b('Table non_existent could not be found in sqlite file %s . Existing table names: some_numbers' % (tmpfile.name)))\n\n\n    def test_qsql_creation_and_direct_use(self):\n        numbers = [[six.b(str(i)),six.b(str(i)),six.b(str(i))] for i in range(1,10001)]\n\n        file_data = self.arrays_to_csv_file_content(six.b('\\t'),[six.b('aa'),six.b('bb'),six.b('cc')],numbers)\n\n        tmpfile = self.create_file_with_data(file_data)\n        tmpfile_folder = os.path.dirname(tmpfile.name)\n        tmpfile_filename = os.path.basename(tmpfile.name)\n        expected_cache_filename = os.path.join(tmpfile_folder,tmpfile_filename + '.qsql')\n\n        cmd = Q_EXECUTABLE + ' -H -t \"select sum(aa),sum(bb),sum(cc) from %s\" -H -C readwrite' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('50005000\\t50005000\\t50005000'))\n\n        self.assertTrue(os.path.exists(expected_cache_filename))\n\n        self.cleanup(tmpfile)\n\n        # Get the data using a comma delimiter, to make sure that column parsing was done correctlyAdding to qcatalog table:\n        cmd = Q_EXECUTABLE + ' -D , \"select count(*),sum(aa),sum(bb),sum(cc) from %s\"' % expected_cache_filename\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('10000,50005000,50005000,50005000'))\n\n    def test_analysis_of_qsql_direct_usage(self):\n        numbers = [[six.b(str(i)),six.b(str(i)),six.b(str(i))] for i in range(1,10001)]\n\n        file_data = self.arrays_to_csv_file_content(six.b('\\t'),[six.b('aa'),six.b('bb'),six.b('cc')],numbers)\n\n        tmpfile = self.create_file_with_data(file_data)\n        tmpfile_folder = os.path.dirname(tmpfile.name)\n        tmpfile_filename = os.path.basename(tmpfile.name)\n        expected_cache_filename = os.path.join(tmpfile_folder,tmpfile_filename + '.qsql')\n\n        cmd = Q_EXECUTABLE + ' -H -t \"select sum(aa),sum(bb),sum(cc) from %s\" -H -C readwrite' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('50005000\\t50005000\\t50005000'))\n\n        self.assertTrue(os.path.exists(expected_cache_filename))\n\n        self.cleanup(tmpfile)\n\n        cmd = Q_EXECUTABLE + ' \"select * from %s\" -A' % expected_cache_filename\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 7)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('Table: %s' % expected_cache_filename))\n        self.assertEqual(o[1],six.b(\"  Sources:\"))\n        self.assertEqual(o[2],six.b('    source_type: qsql-file source: %s' % expected_cache_filename))\n        self.assertEqual(o[3],six.b(\"  Fields:\"))\n        self.assertEqual(o[4],six.b('    `aa` - int'))\n        self.assertEqual(o[5],six.b('    `bb` - int'))\n        self.assertEqual(o[6],six.b('    `cc` - int'))\n\n    def test_analysis_of_qsql_direct_usage2(self):\n        numbers = [[six.b(str(i)),six.b(str(i)),six.b(str(i))] for i in range(1,10001)]\n\n        file_data = self.arrays_to_csv_file_content(six.b('\\t'),[six.b('aa'),six.b('bb'),six.b('cc')],numbers)\n\n        tmpfile = self.create_file_with_data(file_data)\n        tmpfile_folder = os.path.dirname(tmpfile.name)\n        tmpfile_filename = os.path.basename(tmpfile.name)\n        expected_cache_filename = os.path.join(tmpfile_folder,tmpfile_filename + '.qsql')\n\n        cmd = Q_EXECUTABLE + ' -H -t \"select sum(aa),sum(bb),sum(cc) from %s\" -H -C readwrite' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('50005000\\t50005000\\t50005000'))\n\n        self.assertTrue(os.path.exists(expected_cache_filename))\n\n        self.cleanup(tmpfile)\n\n        cmd = Q_EXECUTABLE + ' \"select * from %s\" -A' % expected_cache_filename\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 7)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('Table: %s' % expected_cache_filename))\n        self.assertEqual(o[1],six.b(\"  Sources:\"))\n        self.assertEqual(o[2],six.b('    source_type: qsql-file source: %s' % expected_cache_filename))\n        self.assertEqual(o[3],six.b(\"  Fields:\"))\n        self.assertEqual(o[4],six.b('    `aa` - int'))\n        self.assertEqual(o[5],six.b('    `bb` - int'))\n        self.assertEqual(o[6],six.b('    `cc` - int'))\n\n    def test_direct_qsql_usage_for_single_table_qsql_file(self):\n        disk_db_filename = self.random_tmp_filename('save-to-db','qsql')\n\n        cmd = 'seq 1 10000 | %s -t \"select sum(aa),sum(bb),sum(cc) from -\" -S %s' % (Q_EXECUTABLE,disk_db_filename)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n\n        cmd = '%s -D, \"select count(*),sum(c1) from %s:::data_stream_stdin\"' % (Q_EXECUTABLE,disk_db_filename)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o),1)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0],six.b('10000,50005000'))\n\n    def test_direct_qsql_usage_for_single_table_qsql_file__nonexistent_table(self):\n        disk_db_filename = self.random_tmp_filename('save-to-db','qsql')\n\n        cmd = 'seq 1 10000 | %s -t \"select sum(aa),sum(bb),sum(cc) from -\" -S %s' % (Q_EXECUTABLE,disk_db_filename)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n\n        cmd = '%s -D, \"select count(*),sum(c1) from %s:::unknown_table_name\"' % (Q_EXECUTABLE,disk_db_filename)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 85)\n        self.assertEqual(len(o),0)\n        self.assertEqual(len(e),1)\n        self.assertEqual(e[0],six.b('Table unknown_table_name could not be found in sqlite file %s . Existing table names: data_stream_stdin' % (disk_db_filename)))\n\n    def test_direct_qsql_usage_from_written_data_stream(self):\n        disk_db_filename = self.random_tmp_filename('save-to-db','qsql')\n\n        cmd = 'seq 1 10000 | %s -t \"select sum(aa),sum(bb),sum(cc) from -\" -S %s' % (Q_EXECUTABLE,disk_db_filename)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n\n        cmd = '%s -D, \"select count(*),sum(c1) from %s:::data_stream_stdin\"' % (Q_EXECUTABLE,disk_db_filename)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o),1)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0],six.b('10000,50005000'))\n\n    def test_direct_qsql_self_join(self):\n        disk_db_filename = self.random_tmp_filename('save-to-db','qsql')\n\n        N = 100\n        cmd = 'seq 1 %s | %s -t \"select count(*),sum(c1) from -\" -S %s' % (N,Q_EXECUTABLE,disk_db_filename)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n\n        cmd = '%s -D, \"select count(*),sum(a.c1),sum(b.c1) from %s:::data_stream_stdin a left join %s:::data_stream_stdin b\"' % (Q_EXECUTABLE,disk_db_filename,disk_db_filename)\n        retcode, o, e = run_command(cmd)\n\n        expected_sum = sum(range(1,N+1))*N\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o),1)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[0],six.b('10000,%s,%s' % (expected_sum,expected_sum)))\n\n\nclass CachingTests(AbstractQTestCase):\n\n    def test_cache_empty_file(self):\n        file_data = six.b(\"a,b,c\")\n        tmpfile = self.create_file_with_data(file_data)\n        tmpfile_folder = os.path.dirname(tmpfile.name)\n        tmpfile_filename = os.path.basename(tmpfile.name)\n        tmpfile_expected_table_name = os.path.basename(tmpfile.name)\n        expected_cache_filename = os.path.join(tmpfile_folder,tmpfile_filename + '.qsql')\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C none' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(e[0],six.b(\"Warning - data is empty\"))\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C readwrite' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(e[0],six.b(\"Warning - data is empty\"))\n\n        # After readwrite caching has been activated, the cache file is expected to exist\n        self.assertTrue(os.path.exists(expected_cache_filename))\n\n        # Read the cache file directly, to make sure it's a valid sqlite file\n        import sqlite3\n        db = sqlite3.connect(expected_cache_filename)\n        table_list = db.execute(\"select content_signature_key,temp_table_name,content_signature,creation_time,source_type,source from _qcatalog where temp_table_name == '%s'\" % (tmpfile_expected_table_name)).fetchall()\n        self.assertTrue(len(table_list) == 1)\n        table_metadata = table_list[0]\n        results = db.execute(\"select * from %s\" % table_metadata[1]).fetchall()\n        self.assertTrue(len(results) == 0)\n\n        self.cleanup(tmpfile)\n\n    def test_reading_the_wrong_cache__original_file_having_different_data(self):\n        file_data1 = six.b(\"a,b,c\\n10,20,30\\n30,40,50\")\n\n        tmpfile1 = self.create_file_with_data(file_data1)\n        tmpfile1_folder = os.path.dirname(tmpfile1.name)\n        tmpfile1_filename = os.path.basename(tmpfile1.name)\n        expected_cache_filename = os.path.join(tmpfile1_folder,tmpfile1_filename + '.qsql')\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C readwrite' % tmpfile1.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 2)\n        self.assertEqual(len(e), 0)\n        self.assertTrue(o[0], six.b('10'))\n        self.assertEqual(o[1], six.b('30'))\n\n        # Ensure cache has been created\n        self.assertTrue(os.path.exists(expected_cache_filename))\n\n        # Overwrite the original file\n        file_data2 = six.b(\"a,b,c\\n10,20,30\\n30,40,50\\n50,60,70\")\n        self.write_file(tmpfile1.name,file_data2)\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C read' % tmpfile1.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 81)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n        self.assertEqual(e[0], six.b('%s vs %s.qsql: Content Signatures differ at inferer.rows (actual analysis data differs)' % \\\n                                     (tmpfile1.name,tmpfile1.name)))\n\n\n    def test_reading_the_wrong_cache__original_file_having_different_delimiter(self):\n        file_data1 = six.b(\"a,b,c\\n10,20,30\\n30,40,50\")\n\n        tmpfile1 = self.create_file_with_data(file_data1)\n        tmpfile1_folder = os.path.dirname(tmpfile1.name)\n        tmpfile1_filename = os.path.basename(tmpfile1.name)\n        expected_cache_filename = os.path.join(tmpfile1_folder,tmpfile1_filename + '.qsql')\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C readwrite' % tmpfile1.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 2)\n        self.assertEqual(len(e), 0)\n        self.assertTrue(o[0], six.b('10'))\n        self.assertEqual(o[1], six.b('30'))\n\n        # Ensure cache has been created\n        self.assertTrue(os.path.exists(expected_cache_filename))\n\n        # Overwrite the original file\n        file_data2 = six.b(\"a\\tb\\tc\\n10\\t20\\t30\\n30\\t40\\t50\")\n        self.write_file(tmpfile1.name,file_data2)\n\n        cmd = Q_EXECUTABLE + ' -H -t \"select a from %s\" -C read' % tmpfile1.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 80)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n        x = six.b(\"%s vs %s.qsql: Content Signatures for table %s differ at input_delimiter (source value '\\t' disk signature value ',')\" % \\\n                                     (tmpfile1.name,tmpfile1.name,tmpfile1.name))\n        self.assertEqual(e[0], x)\n\n    def test_rename_cache_and_read_from_it(self):\n        # create a file, along with its qsql\n        file_data1 = six.b(\"a,b,c\\n10,20,30\\n30,40,50\")\n\n        tmpfile1 = self.create_file_with_data(file_data1)\n        tmpfile1_folder = os.path.dirname(tmpfile1.name)\n        tmpfile1_filename = os.path.basename(tmpfile1.name)\n        expected_cache_filename1 = os.path.join(tmpfile1_folder,tmpfile1_filename + '.qsql')\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C readwrite' % tmpfile1.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 2)\n        self.assertEqual(len(e), 0)\n        self.assertTrue(o[0], six.b('10'))\n        self.assertEqual(o[1], six.b('30'))\n        # Ensure cache has been created\n        self.assertTrue(os.path.exists(expected_cache_filename1))\n\n        tmp_fn = self.generate_tmpfile_name(\"aa\",\"qsql\")\n        os.rename(expected_cache_filename1,tmp_fn)\n\n        cmd = '%s \"select a from %s\"' % (Q_EXECUTABLE,tmp_fn)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 2)\n        self.assertEqual(len(e), 0)\n        self.assertTrue(o[0], six.b('10'))\n        self.assertEqual(o[1], six.b('30'))\n\n\n    def test_reading_the_wrong_cache__qsql_file_not_having_a_matching_content_signature(self):\n        # create a file, along with its qsql\n        file_data1 = six.b(\"a,b,c\\n10,20,30\\n30,40,50\")\n\n        tmpfile1 = self.create_file_with_data(file_data1)\n        tmpfile1_folder = os.path.dirname(tmpfile1.name)\n        tmpfile1_filename = os.path.basename(tmpfile1.name)\n        expected_cache_filename1 = os.path.join(tmpfile1_folder,tmpfile1_filename + '.qsql')\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C readwrite' % tmpfile1.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 2)\n        self.assertEqual(len(e), 0)\n        self.assertTrue(o[0], six.b('10'))\n        self.assertEqual(o[1], six.b('30'))\n        # Ensure cache has been created\n        self.assertTrue(os.path.exists(expected_cache_filename1))\n\n        file_data2 = six.b(\"c,d,e\\n10,20,30\\n30,40,50\")\n\n        # create another file with a different header, along with its qsql\n        tmpfile2 = self.create_file_with_data(file_data2)\n        tmpfile2_folder = os.path.dirname(tmpfile2.name)\n        tmpfile2_filename = os.path.basename(tmpfile2.name)\n        expected_cache_filename2 = os.path.join(tmpfile2_folder,tmpfile2_filename + '.qsql')\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select c from %s\" -C readwrite' % tmpfile2.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 2)\n        self.assertEqual(len(e), 0)\n        self.assertTrue(o[0], six.b('10'))\n        self.assertEqual(o[1], six.b('30'))\n        # Ensure cache has been created\n        self.assertTrue(os.path.exists(expected_cache_filename2))\n\n        # now take the second qsql file as if it was the first. Execution on file 1 should fail, since the qsql file\n        # does not really contain the table we're after\n\n        os.remove(expected_cache_filename1)\n        os.rename(expected_cache_filename2,expected_cache_filename1)\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C read' % tmpfile1.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 80)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n        x = six.b(\"%s vs %s.qsql: Content Signatures for table %s differ at inferer.header_row (source value '['a', 'b', 'c']' disk signature value '['c', 'd', 'e']')\" % (tmpfile1.name,tmpfile1.name,tmpfile1.name))\n        self.assertEqual(e[0], x)\n\n    def test_reading_the_wrong_cache__qsql_file_not_having_any_content_signature(self):\n        # create a file, along with its qsql\n        file_data1 = six.b(\"a,b,c\\n10,20,30\\n30,40,50\")\n\n        tmpfile1 = self.create_file_with_data(file_data1)\n        tmpfile1_folder = os.path.dirname(tmpfile1.name)\n        tmpfile1_filename = os.path.basename(tmpfile1.name)\n        expected_cache_filename1 = os.path.join(tmpfile1_folder,tmpfile1_filename + '.qsql')\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C readwrite' % tmpfile1.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 2)\n        self.assertEqual(len(e), 0)\n        self.assertTrue(o[0], six.b('10'))\n        self.assertEqual(o[1], six.b('30'))\n        # Ensure cache has been created\n        self.assertTrue(os.path.exists(expected_cache_filename1))\n\n        file_data2 = six.b(\"c,d,e\\n10,20,30\\n30,40,50\")\n\n        # delete qcatalog content, so no entries will be available\n        c = sqlite3.connect(expected_cache_filename1)\n        c.execute('delete from _qcatalog').fetchall()\n        c.commit()\n        c.close()\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C read' % tmpfile1.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 97)\n        self.assertEqual(len(o),0)\n        self.assertEqual(len(e),1)\n        self.assertEqual(e[0],six.b(\"Could not autodetect table name in qsql file. File contains no record of a table\"))\n\n\n    def test_cache_full_flow(self):\n        file_data = six.b(\"a,b,c\\n10,20,30\\n30,40,50\")\n        tmpfile = self.create_file_with_data(file_data)\n        tmpfile_folder = os.path.dirname(tmpfile.name)\n        tmpfile_filename = os.path.basename(tmpfile.name)\n        expected_tmpfile_table_name = tmpfile_filename\n        expected_cache_filename = os.path.join(tmpfile_folder,tmpfile_filename + '.qsql')\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C none' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 2)\n        self.assertEqual(len(e), 0)\n        self.assertTrue(o[0],six.b('10'))\n        self.assertEqual(o[1],six.b('30'))\n\n        # Ensure cache has not been created\n        self.assertTrue(not os.path.exists(expected_cache_filename))\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C read' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 2)\n        self.assertEqual(len(e), 0)\n        self.assertTrue(o[0],six.b('10'))\n        self.assertEqual(o[1],six.b('30'))\n\n        # Ensure cache has not been created, as cache mode is \"read\" only\n        self.assertTrue(not os.path.exists(expected_cache_filename))\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C readwrite' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 2)\n        self.assertEqual(len(e), 0)\n        self.assertTrue(o[0],six.b('10'))\n        self.assertEqual(o[1],six.b('30'))\n\n        # After readwrite caching has been activated, the cache file is expected to exist\n        self.assertTrue(os.path.exists(expected_cache_filename))\n\n        # Read the cache file directly, to make sure it's a valid sqlite file\n        db = sqlite3.connect(expected_cache_filename)\n        table_list = db.execute(\"select content_signature_key,temp_table_name,content_signature,creation_time,source_type,source from _qcatalog where temp_table_name == '%s'\" % expected_tmpfile_table_name).fetchall()\n        self.assertTrue(len(table_list) == 1)\n        table_metadata = table_list[0]\n        results = db.execute(\"select * from %s\" % table_metadata[1]).fetchall()\n        self.assertEqual(results[0],(10,20,30))\n        self.assertEqual(results[1],(30,40,50))\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C read' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 2)\n        self.assertEqual(len(e), 0)\n        self.assertTrue(o[0],six.b('10'))\n        self.assertEqual(o[1],six.b('30'))\n\n        # After readwrite caching has been activated, the cache file is expected to exist\n        self.assertTrue(os.path.exists(expected_cache_filename))\n\n        self.cleanup(tmpfile)\n\n    def test_cache_full_flow_with_concatenated_files(self):\n        file_data1 = six.b(\"a,b,c\\n10,11,12\\n20,21,22\")\n        tmpfile1 = self.create_file_with_data(file_data1)\n        tmpfile1_folder = os.path.dirname(tmpfile1.name)\n        tmpfile1_filename = os.path.basename(tmpfile1.name)\n        expected_cache_filename1 = os.path.join(tmpfile1_folder,tmpfile1_filename + '.qsql')\n\n        file_data2 = six.b(\"a,b,c\\n30,31,32\\n40,41,42\")\n        tmpfile2 = self.create_file_with_data(file_data2)\n        tmpfile2_folder = os.path.dirname(tmpfile2.name)\n        tmpfile2_filename = os.path.basename(tmpfile2.name)\n        expected_cache_filename2 = os.path.join(tmpfile2_folder,tmpfile2_filename + '.qsql')\n\n        cmd = Q_EXECUTABLE + ' -O -H -d , \"select * from (select * from %s UNION ALL select * from %s)\" -C readwrite' % (tmpfile1.name,tmpfile2.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 5)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('a,b,c'))\n        self.assertEqual(o[1],six.b('10,11,12'))\n        self.assertEqual(o[2],six.b('20,21,22'))\n        self.assertEqual(o[3],six.b('30,31,32'))\n        self.assertEqual(o[4],six.b('40,41,42'))\n\n        self.assertTrue(os.path.exists(expected_cache_filename1))\n        self.assertTrue(os.path.exists(expected_cache_filename2))\n\n        self.cleanup(tmpfile1)\n        self.cleanup(tmpfile2)\n\n\n    def test_analyze_result_with_cache_file(self):\n        file_data = six.b(\"a,b,c\\n10,20,30\\n30,40,50\")\n        tmpfile = self.create_file_with_data(file_data)\n        tmpfile_folder = os.path.dirname(tmpfile.name)\n        tmpfile_filename = os.path.basename(tmpfile.name)\n        expected_cache_filename = os.path.join(tmpfile_folder,tmpfile_filename + '.qsql')\n\n        # Ensure cache has not been created yet\n        self.assertTrue(not os.path.exists(expected_cache_filename))\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C readwrite' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 2)\n        self.assertEqual(len(e), 0)\n        self.assertTrue(o[0],six.b('10'))\n        self.assertEqual(o[1],six.b('30'))\n\n        # Ensure cache is now created\n        self.assertTrue(os.path.exists(expected_cache_filename))\n\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C read -A' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o),7)\n        self.assertEqual(len(e),0)\n\n        self.assertEqual(o[0],six.b('Table: %s' % tmpfile.name))\n        self.assertEqual(o[1],six.b('  Sources:'))\n        self.assertEqual(o[2],six.b('    source_type: qsql-file-with-original source: %s.qsql' % tmpfile.name))\n        self.assertEqual(o[3],six.b('  Fields:'))\n        self.assertEqual(o[4],six.b('    `a` - int'))\n        self.assertEqual(o[5],six.b('    `b` - int'))\n        self.assertEqual(o[6],six.b('    `c` - int'))\n\n        # delete the newly created cache\n        os.remove(expected_cache_filename)\n\n        # Now rerun the analysis without the cache file\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C read -A' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o),7)\n        self.assertEqual(len(e),0)\n\n        self.assertEqual(o[0],six.b('Table: %s' % tmpfile.name))\n        self.assertEqual(o[1],six.b('  Sources:'))\n        self.assertEqual(o[2],six.b('    source_type: file source: %s' % tmpfile.name))\n        self.assertEqual(o[3],six.b('  Fields:'))\n        self.assertEqual(o[4],six.b('    `a` - int'))\n        self.assertEqual(o[5],six.b('    `b` - int'))\n        self.assertEqual(o[6],six.b('    `c` - int'))\n\n        self.cleanup(tmpfile)\n\n    def test_partial_caching_exists(self):\n        file1_data = six.b(\"a,b,c\\n10,20,30\\n30,40,50\\n60,70,80\")\n        tmpfile1 = self.create_file_with_data(file1_data)\n        tmpfile1_folder = os.path.dirname(tmpfile1.name)\n        tmpfile1_filename = os.path.basename(tmpfile1.name)\n        expected_cache_filename1 = os.path.join(tmpfile1_folder,tmpfile1_filename + '.qsql')\n\n        file2_data = six.b(\"b,x\\n10,linewith10\\n20,linewith20\\n30,linewith30\\n40,linewith40\")\n        tmpfile2 = self.create_file_with_data(file2_data)\n        tmpfile2_folder = os.path.dirname(tmpfile2.name)\n        tmpfile2_filename = os.path.basename(tmpfile2.name)\n        expected_cache_filename2 = os.path.join(tmpfile2_folder,tmpfile2_filename + '.qsql')\n\n        # Use only first file, and cache\n        cmd = Q_EXECUTABLE + ' -H -d , \"select a from %s\" -C readwrite' % tmpfile1.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(len(e), 0)\n        self.assertTrue(o[0],six.b('10'))\n        self.assertEqual(o[1],six.b('30'))\n\n        # Ensure cache has been created for file 1\n        self.assertTrue(os.path.exists(expected_cache_filename1))\n\n        # Use both files with read caching, one should be read from cache, the other from the file\n        cmd = Q_EXECUTABLE + ' -H -d , \"select file1.a,file1.b,file1.c,file2.x from %s file1 left join %s file2 on (file1.b = file2.b)\" -C read' % (tmpfile1.name,tmpfile2.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('10,20,30,linewith20'))\n        self.assertEqual(o[1],six.b('30,40,50,linewith40'))\n        self.assertEqual(o[2],six.b('60,70,80,'))\n\n        # Ensure cache has NOT been created for file 2\n        self.assertTrue(not os.path.exists(expected_cache_filename2))\n\n        # Now rerun the query, this time with readwrite caching, so the second file cache will be written\n        cmd = Q_EXECUTABLE + ' -H -d , \"select file1.a,file1.b,file1.c,file2.x from %s file1 left join %s file2 on (file1.b = file2.b)\" -C readwrite' % (tmpfile1.name,tmpfile2.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(o[0],six.b('10,20,30,linewith20'))\n        self.assertEqual(o[1],six.b('30,40,50,linewith40'))\n        self.assertEqual(o[2],six.b('60,70,80,'))\n\n        # Ensure cache has now been created for file 2\n        self.assertTrue(os.path.exists(expected_cache_filename2))\n\n        self.cleanup(tmpfile1)\n        self.cleanup(tmpfile2)\n\n\nclass UserFunctionTests(AbstractQTestCase):\n    def test_regexp_int_data_handling(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n\n        cmd = Q_EXECUTABLE + ' -d , \"select c2 from %s where regexp(\\'^1\\',c2)\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0],six.b(\"1\"))\n\n        self.cleanup(tmpfile)\n\n    def test_percentile_func(self):\n        cmd = 'seq 1000 1999 | %s \"select substr(c1,0,3),percentile(c1,0),percentile(c1,0.5),percentile(c1,1) from - group by substr(c1,0,3)\" -c 1' % Q_EXECUTABLE\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 10)\n        self.assertEqual(len(e), 0)\n\n        output_table = [l.split(six.b(\" \")) for l in o]\n        group_labels = [int(row[0]) for row in output_table]\n        minimum_values = [float(row[1]) for row in output_table]\n        median_values = [float(row[2]) for row in output_table]\n        max_values = [float(row[3]) for row in output_table]\n\n        base_values = list(range(1000,2000,100))\n\n        self.assertEqual(group_labels,list(range(10,20)))\n        self.assertEqual(minimum_values,base_values)\n        self.assertEqual(median_values,list(map(lambda x: x + 49.5,base_values)))\n        self.assertEqual(max_values,list(map(lambda x: x + 99,base_values)))\n\n    def test_regexp_null_data_handling(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n\n        cmd = Q_EXECUTABLE + ' -d , \"select count(*) from %s where regexp(\\'^\\',c2)\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0],six.b(\"2\"))\n\n        self.cleanup(tmpfile)\n\n    def test_md5_function(self):\n        cmd = 'seq 1 4 | %s -c 1 -d , \"select c1,md5(c1,\\'utf-8\\') from -\"' % Q_EXECUTABLE\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(o),4)\n        self.assertEqual(len(e),0)\n\n        self.assertEqual(tuple(o[0].split(six.b(','),1)),(six.b('1'),six.b('c4ca4238a0b923820dcc509a6f75849b')))\n        self.assertEqual(tuple(o[1].split(six.b(','),1)),(six.b('2'),six.b('c81e728d9d4c2f636f067f89cc14862c')))\n        self.assertEqual(tuple(o[2].split(six.b(','),1)),(six.b('3'),six.b('eccbc87e4b5ce2fe28308fd9f2a7baf3')))\n        self.assertEqual(tuple(o[3].split(six.b(','),1)),(six.b('4'),six.b('a87ff679a2f3e71d9181a67b7542122c')))\n\n    def test_stddev_functions(self):\n        tmpfile = self.create_file_with_data(six.b(\"\\n\".join(map(str,[234,354,3234,123,4234,234,634,56,65]))))\n\n        cmd = '%s -c 1 -d , \"select round(stddev_pop(c1),10),round(stddev_sample(c1),10) from %s\"' % (Q_EXECUTABLE,tmpfile.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(o),1)\n        self.assertEqual(len(e),0)\n\n        self.assertEqual(o[0],six.b('1479.7015464838,1569.4604964764'))\n\n        self.cleanup(tmpfile)\n\n    def test_sqrt_function(self):\n        cmd = 'seq 1 5 | %s -c 1 -d , \"select round(sqrt(c1),10) from -\"' % Q_EXECUTABLE\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(o),5)\n        self.assertEqual(len(e),0)\n\n        self.assertEqual(o[0],six.b('1.0'))\n        self.assertEqual(o[1],six.b('1.4142135624'))\n        self.assertEqual(o[2],six.b('1.7320508076'))\n        self.assertEqual(o[3],six.b('2.0'))\n        self.assertEqual(o[4],six.b('2.2360679775'))\n\n    def test_power_function(self):\n        cmd = 'seq 1 5 | %s -c 1 -d , \"select round(power(c1,2.5),10) from -\"' % Q_EXECUTABLE\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(o),5)\n        self.assertEqual(len(e),0)\n\n        self.assertEqual(o[0],six.b('1.0'))\n        self.assertEqual(o[1],six.b('5.6568542495'))\n        self.assertEqual(o[2],six.b('15.5884572681'))\n        self.assertEqual(o[3],six.b('32.0'))\n        self.assertEqual(o[4],six.b('55.9016994375'))\n\n    def test_file_functions(self):\n        filenames = [\n            \"file1\",\n            \"file2.csv\",\n            \"/var/tmp/file3\",\n            \"/var/tmp/file4.gz\",\n            \"\"\n        ]\n        data = \"\\n\".join(filenames)\n\n        cmd = 'echo \"%s\" | %s -c 1 -d , \"select file_folder(c1),file_ext(c1),file_basename(c1),file_basename_no_ext(c1) from -\"' % (data,Q_EXECUTABLE)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(o),5)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o,[\n            b',,file1,file1',\n            b',.csv,file2.csv,file2',\n            b'/var/tmp,,file3,file3',\n            b'/var/tmp,.gz,file4.gz,file4',\n            b',,,'\n        ])\n\n\n    def test_sha1_function(self):\n        cmd = 'seq 1 4 | %s -c 1 -d , \"select c1,sha1(c1) from -\"' % Q_EXECUTABLE\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(o),4)\n        self.assertEqual(len(e),0)\n\n        self.assertEqual(o[0],six.b('1,356a192b7913b04c54574d18c28d46e6395428ab'))\n        self.assertEqual(o[1],six.b('2,da4b9237bacccdf19c0760cab7aec4a8359010b0'))\n        self.assertEqual(o[2],six.b('3,77de68daecd823babbb58edb1c8e14d7106e83bb'))\n        self.assertEqual(o[3],six.b('4,1b6453892473a467d07372d45eb05abc2031647a'))\n\n    def test_regexp_extract_function(self):\n        query = \"\"\"\n            select \n              regexp_extract('was ([0-9]+) seconds and ([0-9]+) ms',c1,0),\n              regexp_extract('was ([0-9]+) seconds and ([0-9]+) ms',c1,1),\n              regexp_extract('non-existent-(regexp)',c1,0) \n            from\n              -\n        \"\"\"\n\n        cmd = 'echo \"Duration was 322 seconds and 240 ms\" | %s -c 1 -d , \"%s\"' % (Q_EXECUTABLE,query)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(o),1)\n        self.assertEqual(len(e),0)\n\n        self.assertEqual(o[0],six.b('322,240,'))\n\n    def test_sha_function(self):\n        cmd = 'seq 1 4 | %s -c 1 -d , \"select c1,sha(c1,1,\\'utf-8\\') as sha1,sha(c1,224,\\'utf-8\\') as sha224,sha(c1,256,\\'utf-8\\') as sha256 from -\"' % Q_EXECUTABLE\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(o),4)\n        self.assertEqual(len(e),0)\n\n        self.assertEqual(o[0],six.b('1,356a192b7913b04c54574d18c28d46e6395428ab,e25388fde8290dc286a6164fa2d97e551b53498dcbf7bc378eb1f178,6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b'))\n        self.assertEqual(o[1],six.b('2,da4b9237bacccdf19c0760cab7aec4a8359010b0,58b2aaa0bfae7acc021b3260e941117b529b2e69de878fd7d45c61a9,d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35'))\n        self.assertEqual(o[2],six.b('3,77de68daecd823babbb58edb1c8e14d7106e83bb,4cfc3a1811fe40afa401b25ef7fa0379f1f7c1930a04f8755d678474,4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce'))\n        self.assertEqual(o[3],six.b('4,1b6453892473a467d07372d45eb05abc2031647a,271f93f45e9b4067327ed5c8cd30a034730aaace4382803c3e1d6c2f,4b227777d4dd1fc61c6f884f48641d02b4d121d3fd328cb08b5531fcacdabf8a'))\n\n\nclass MultiHeaderTests(AbstractQTestCase):\n    def test_output_header_when_multiple_input_headers_exist(self):\n        TMPFILE_COUNT = 5\n        tmpfiles = [self.create_file_with_data(sample_data_with_header) for x in range(TMPFILE_COUNT)]\n\n        tmpfilenames = \" UNION ALL \".join(map(lambda x:\"select * from %s\" % x.name, tmpfiles))\n\n        cmd = Q_EXECUTABLE + ' -d , \"select name,value1,value2 from (%s) order by name\" -H -O' % tmpfilenames\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), TMPFILE_COUNT*3+1)\n        self.assertEqual(o[0], six.b(\"name,value1,value2\"))\n\n        for i in range (TMPFILE_COUNT):\n            self.assertEqual(o[1+i],sample_data_rows[0])\n        for i in range (TMPFILE_COUNT):\n            self.assertEqual(o[TMPFILE_COUNT+1+i],sample_data_rows[1])\n        for i in range (TMPFILE_COUNT):\n            self.assertEqual(o[TMPFILE_COUNT*2+1+i],sample_data_rows[2])\n\n        for oi in o[1:]:\n            self.assertTrue(six.b('name') not in oi)\n\n        for i in range(TMPFILE_COUNT):\n            self.cleanup(tmpfiles[i])\n\n    def test_output_header_when_extra_header_column_names_are_different__concatenation_replacement(self):\n        tmpfile1 = self.create_file_with_data(sample_data_with_header)\n        tmpfile2 = self.create_file_with_data(generate_sample_data_with_header(six.b('othername,value1,value2')))\n\n        cmd = Q_EXECUTABLE + ' -d , \"select name,value1,value2 from (select * from %s union all select * from %s) order by name\" -H -O' % (tmpfile1.name,tmpfile2.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 7)\n        self.assertEqual(len(e), 0)\n        self.assertTrue(o, [\n            six.b('name,value1,value2'),\n            six.b('a,1,0'),\n            six.b('a,1,0'),\n            six.b('b,2,0'),\n            six.b('b,2,0'),\n            six.b('c,,0'),\n            six.b('c,,0')\n        ])\n\n        self.cleanup(tmpfile1)\n        self.cleanup(tmpfile2)\n\n    def test_output_header_when_extra_header_has_different_number_of_columns(self):\n        tmpfile1 = self.create_file_with_data(sample_data_with_header)\n        tmpfile2 = self.create_file_with_data(generate_sample_data_with_header(six.b('name,value1')))\n\n        cmd = Q_EXECUTABLE + ' -d , \"select name,value1,value2 from (select * from %s UNION ALL select * from %s) order by name\" -H -O' % (tmpfile1.name,tmpfile2.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 7)\n        self.assertEqual(len(e), 0)\n        self.assertTrue(o, [\n            six.b('name,value1,value2'),\n            six.b('a,1,0'),\n            six.b('a,1,0'),\n            six.b('b,2,0'),\n            six.b('b,2,0'),\n            six.b('c,,0'),\n            six.b('c,,0')\n        ])\n\n        self.cleanup(tmpfile1)\n        self.cleanup(tmpfile2)\n\n\nclass ParsingModeTests(AbstractQTestCase):\n\n    def test_strict_mode_column_count_mismatch_error(self):\n        tmpfile = self.create_file_with_data(uneven_ls_output)\n        cmd = Q_EXECUTABLE + ' -m strict \"select count(*) from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertNotEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n\n        self.assertTrue(six.b(\"Column Count is expected to identical\") in e[0])\n\n        self.cleanup(tmpfile)\n\n    def test_strict_mode_too_large_specific_column_count(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n        cmd = Q_EXECUTABLE + ' -d , -m strict -c 4 \"select count(*) from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertNotEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n\n        self.assertEqual(\n            e[0], six.b(\"Strict mode. Column count is expected to be 4 but is 3\"))\n\n        self.cleanup(tmpfile)\n\n    def test_strict_mode_too_small_specific_column_count(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n        cmd = Q_EXECUTABLE + ' -d , -m strict -c 2 \"select count(*) from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertNotEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n\n        self.assertEqual(\n            e[0], six.b(\"Strict mode. Column count is expected to be 2 but is 3\"))\n\n        self.cleanup(tmpfile)\n\n    def test_relaxed_mode_missing_columns_in_header(self):\n        tmpfile = self.create_file_with_data(\n            sample_data_with_missing_header_names)\n        cmd = Q_EXECUTABLE + ' -d , -m relaxed \"select count(*) from %s\" -H -A' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 7)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0],six.b('Table: %s' % tmpfile.name))\n        self.assertEqual(o[1],six.b('  Sources:'))\n        self.assertEqual(o[2],six.b('    source_type: file source: %s') % six.b(tmpfile.name))\n        self.assertEqual(o[3],six.b('  Fields:'))\n        self.assertEqual(o[4],six.b('    `name` - text'))\n        self.assertEqual(o[5],six.b('    `value1` - int'))\n        self.assertEqual(o[6],six.b('    `c3` - int'))\n\n        self.cleanup(tmpfile)\n\n    def test_strict_mode_missing_columns_in_header(self):\n        tmpfile = self.create_file_with_data(\n            sample_data_with_missing_header_names)\n        cmd = Q_EXECUTABLE + ' -d , -m strict \"select count(*) from %s\" -H -A' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertNotEqual(retcode, 0)\n        self.assertEqual(len(o), 0)\n        self.assertEqual(len(e), 1)\n\n        self.assertEqual(\n            e[0], six.b('Strict mode. Header row contains less columns than expected column count(2 vs 3)'))\n\n        self.cleanup(tmpfile)\n\n    def test_output_delimiter_with_missing_fields(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n        cmd = Q_EXECUTABLE + ' -d , \"select * from %s\" -D \";\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0], six.b('a;1;0'))\n        self.assertEqual(o[1], six.b('b;2;0'))\n        self.assertEqual(o[2], six.b('c;;0'))\n\n        self.cleanup(tmpfile)\n\n    def test_handling_of_null_integers(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n        cmd = Q_EXECUTABLE + ' -d , \"select avg(c2) from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0], six.b('1.5'))\n\n        self.cleanup(tmpfile)\n\n    def test_empty_integer_values_converted_to_null(self):\n        tmpfile = self.create_file_with_data(sample_data_no_header)\n        cmd = Q_EXECUTABLE + ' -d , \"select * from %s where c2 is null\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0], six.b('c,,0'))\n\n        self.cleanup(tmpfile)\n\n    def test_empty_string_values_not_converted_to_null(self):\n        tmpfile = self.create_file_with_data(\n            sample_data_with_empty_string_no_header)\n        cmd = Q_EXECUTABLE + ' -d , \"select * from %s where c2 == %s\"' % (\n            tmpfile.name, \"''\")\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0], six.b('c,,0'))\n\n        self.cleanup(tmpfile)\n\n    def test_relaxed_mode_detected_columns(self):\n        tmpfile = self.create_file_with_data(uneven_ls_output)\n        cmd = Q_EXECUTABLE + ' -m relaxed \"select count(*) from %s\" -A' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n\n        column_rows = o[o.index(six.b('  Fields:'))+1:]\n\n        self.assertEqual(len(column_rows), 11)\n\n        column_tuples = [x.strip().split(six.b(\" \")) for x in column_rows]\n        column_info = [(x[0], x[2]) for x in column_tuples]\n        column_names = [x[0] for x in column_tuples]\n        column_types = [x[2] for x in column_tuples]\n\n        self.assertEqual(column_names, [six.b('`c{}`'.format(x)) for x in range(1, 12)])\n        self.assertEqual(column_types, list(map(lambda x:six.b(x),[\n                          'text', 'int', 'text', 'text', 'int', 'text', 'int', 'int', 'text', 'text', 'text'])))\n\n        self.cleanup(tmpfile)\n\n    def test_relaxed_mode_detected_columns_with_specific_column_count(self):\n        tmpfile = self.create_file_with_data(uneven_ls_output)\n        cmd = Q_EXECUTABLE + ' -m relaxed \"select count(*) from %s\" -A -c 9' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n\n        column_rows = o[o.index(six.b('  Fields:'))+1:]\n\n        self.assertEqual(len(column_rows), 9)\n\n        column_tuples = [x.strip().split(six.b(\" \")) for x in column_rows]\n        column_info = [(x[0], x[2]) for x in column_tuples]\n        column_names = [x[0] for x in column_tuples]\n        column_types = [x[2] for x in column_tuples]\n\n        self.assertEqual(column_names, [six.b('`c{}`'.format(x)) for x in range(1, 10)])\n        self.assertEqual(\n            column_types, list(map(lambda x:six.b(x),['text', 'int', 'text', 'text', 'int', 'text', 'int', 'int', 'text'])))\n\n        self.cleanup(tmpfile)\n\n    def test_relaxed_mode_last_column_data_with_specific_column_count(self):\n        tmpfile = self.create_file_with_data(uneven_ls_output)\n        cmd = Q_EXECUTABLE + ' -m relaxed \"select c9 from %s\" -c 9' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 9)\n        self.assertEqual(len(e), 0)\n\n        expected_output = list(map(lambda x:six.b(x),[\"/selinux\", \"/mnt\", \"/srv\", \"/lost+found\", '\"/initrd.img.old -> /boot/initrd.img-3.8.0-19-generic\"',\n                           \"/cdrom\", \"/home\", '\"/vmlinuz -> boot/vmlinuz-3.8.0-19-generic\"', '\"/initrd.img -> boot/initrd.img-3.8.0-19-generic\"']))\n\n        self.assertEqual(o, expected_output)\n\n        self.cleanup(tmpfile)\n\n    def test_1_column_warning_in_relaxed_mode(self):\n        tmpfile = self.create_file_with_data(one_column_data)\n        cmd = Q_EXECUTABLE + ' -m relaxed \"select c1 from %s\" -d ,' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b('data without commas 1'))\n        self.assertEqual(o[1],six.b('data without commas 2'))\n\n        self.cleanup(tmpfile)\n\n    def test_1_column_warning_in_strict_mode(self):\n        tmpfile = self.create_file_with_data(one_column_data)\n        cmd = Q_EXECUTABLE + ' -m relaxed \"select c1 from %s\" -d , -m strict' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b('data without commas 1'))\n        self.assertEqual(o[1],six.b('data without commas 2'))\n\n        self.cleanup(tmpfile)\n\n\n    def test_1_column_warning_suppression_in_relaxed_mode_when_column_count_is_specific(self):\n        tmpfile = self.create_file_with_data(one_column_data)\n        cmd = Q_EXECUTABLE + ' -m relaxed \"select c1 from %s\" -d , -m relaxed -c 1' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b('data without commas 1'))\n        self.assertEqual(o[1],six.b('data without commas 2'))\n\n        self.cleanup(tmpfile)\n\n    def test_1_column_warning_suppression_in_strict_mode_when_column_count_is_specific(self):\n        tmpfile = self.create_file_with_data(one_column_data)\n        cmd = Q_EXECUTABLE + ' -m relaxed \"select c1 from %s\" -d , -m strict -c 1' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o),2)\n\n        self.assertEqual(o[0],six.b('data without commas 1'))\n        self.assertEqual(o[1],six.b('data without commas 2'))\n\n        self.cleanup(tmpfile)\n\n    def test_fluffy_mode__as_relaxed_mode(self):\n        tmpfile = self.create_file_with_data(uneven_ls_output)\n        cmd = Q_EXECUTABLE + ' -m relaxed \"select c9 from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 9)\n        self.assertEqual(len(e), 0)\n\n        expected_output = list(map(lambda x:six.b(x),[\"/selinux\", \"/mnt\", \"/srv\", \"/lost+found\",\n                           \"/initrd.img.old\", \"/cdrom\", \"/home\", \"/vmlinuz\", \"/initrd.img\"]))\n\n        self.assertEqual(o, expected_output)\n\n        self.cleanup(tmpfile)\n\n    def test_relaxed_mode_column_count_mismatch__was_previously_fluffy_mode_test(self):\n        data_row = six.b(\"column1 column2 column3 column4\")\n        data_list = [data_row] * 1000\n        data_list[950] = six.b(\"column1 column2 column3 column4 column5\")\n        tmpfile = self.create_file_with_data(six.b(\"\\n\").join(data_list))\n\n        cmd = Q_EXECUTABLE + ' -m relaxed \"select * from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n        self.assertEqual(len(o),1000)\n        self.assertEqual(len(e),0)\n        self.assertEqual(o[950],six.b('column1 column2 column3 \"column4 column5\"'))\n\n        self.cleanup(tmpfile)\n\n    def test_strict_mode_column_count_mismatch__less_columns(self):\n        data_row = six.b(\"column1 column2 column3 column4\")\n        data_list = [data_row] * 1000\n        data_list[750] = six.b(\"column1 column3 column4\")\n        tmpfile = self.create_file_with_data(six.b(\"\\n\").join(data_list))\n\n        cmd = Q_EXECUTABLE + ' -m strict \"select * from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertNotEqual(retcode,0)\n        self.assertEqual(len(o),0)\n        self.assertEqual(len(e),1)\n        self.assertTrue(e[0].startswith(six.b(\"Strict mode - Expected 4 columns instead of 3 columns\")))\n        self.assertTrue(six.b(' row 751.') in e[0])\n\n        self.cleanup(tmpfile)\n\n    def test_strict_mode_column_count_mismatch__more_columns(self):\n        data_row = six.b(\"column1 column2 column3 column4\")\n        data_list = [data_row] * 1000\n        data_list[750] = six.b(\"column1 column2 column3 column4 column5\")\n        tmpfile = self.create_file_with_data(six.b(\"\\n\").join(data_list))\n\n        cmd = Q_EXECUTABLE + ' -m strict \"select * from %s\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertNotEqual(retcode,0)\n        self.assertEqual(len(o),0)\n        self.assertEqual(len(e),1)\n        self.assertTrue(e[0].startswith(six.b(\"Strict mode - Expected 4 columns instead of 5 columns\")))\n        self.assertTrue(six.b(' row 751.') in e[0])\n\n        self.cleanup(tmpfile)\n\n\nclass FormattingTests(AbstractQTestCase):\n\n    def test_column_formatting(self):\n        # TODO Decide if this breaking change is reasonable\n        #cmd = 'seq 1 10 | ' + Q_EXECUTABLE + ' -f 1=%4.3f,2=%4.3f \"select sum(c1),avg(c1) from -\" -c 1'\n        cmd = 'seq 1 10 | ' + Q_EXECUTABLE + ' -f 1={:4.3f},2={:4.3f} \"select sum(c1),avg(c1) from -\" -c 1'\n\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 1)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0], six.b('55.000 5.500'))\n\n    def test_column_formatting_with_output_header(self):\n        perl_regex = \"'s/1\\n/column_name\\n1\\n/;'\"\n        # TODO Decide if this breaking change is reasonable\n        #cmd = 'seq 1 10 | perl -pe ' + perl_regex + ' | ' + Q_EXECUTABLE + ' -f 1=%4.3f,2=%4.3f \"select sum(column_name) mysum,avg(column_name) myavg from -\" -c 1 -H -O'\n        cmd = 'seq 1 10 | LANG=C perl -pe ' + perl_regex + ' | ' + Q_EXECUTABLE + ' -f 1={:4.3f},2={:4.3f} \"select sum(column_name) mysum,avg(column_name) myavg from -\" -c 1 -H -O'\n\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 2)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0], six.b('mysum myavg'))\n        self.assertEqual(o[1], six.b('55.000 5.500'))\n\n    def py3_test_successfuly_parse_universal_newlines_without_explicit_flag(self):\n        def list_as_byte_list(l):\n            return list(map(lambda x:six.b(x),l))\n\n        expected_output = list(map(lambda x:list_as_byte_list(x),[['lifelock', 'LifeLock', '', 'web', 'Tempe', 'AZ', '1-May-07', '6850000', 'USD', 'b'],\n                           ['lifelock', 'LifeLock', '', 'web', 'Tempe', 'AZ', '1-Oct-06', '6000000', 'USD', 'a'],\n                           ['lifelock', 'LifeLock', '', 'web', 'Tempe', 'AZ', '1-Jan-08', '25000000', 'USD', 'c'],\n                           ['mycityfaces', 'MyCityFaces', '7', 'web', 'Scottsdale', 'AZ', '1-Jan-08', '50000', 'USD', 'seed'],\n                           ['flypaper', 'Flypaper', '', 'web', 'Phoenix', 'AZ', '1-Feb-08', '3000000', 'USD', 'a'],\n                           ['infusionsoft', 'Infusionsoft', '105', 'software', 'Gilbert', 'AZ', '1-Oct-07', '9000000', 'USD', 'a']]))\n\n        data = six.b('permalink,company,numEmps,category,city,state,fundedDate,raisedAmt,raisedCurrency,round\\rlifelock,LifeLock,,web,Tempe,AZ,1-May-07,6850000,USD,b\\rlifelock,LifeLock,,web,Tempe,AZ,1-Oct-06,6000000,USD,a\\rlifelock,LifeLock,,web,Tempe,AZ,1-Jan-08,25000000,USD,c\\rmycityfaces,MyCityFaces,7,web,Scottsdale,AZ,1-Jan-08,50000,USD,seed\\rflypaper,Flypaper,,web,Phoenix,AZ,1-Feb-08,3000000,USD,a\\rinfusionsoft,Infusionsoft,105,software,Gilbert,AZ,1-Oct-07,9000000,USD,a')\n        tmp_data_file = self.create_file_with_data(data)\n\n        cmd = Q_EXECUTABLE + ' -d , -H \"select * from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 6)\n\n        actual_output = list(map(lambda row: row.split(six.b(\",\")),o))\n\n        self.assertEqual(actual_output,expected_output)\n\n        self.cleanup(tmp_data_file)\n\n    test_parsing_universal_newlines_without_explicit_flag = py3_test_successfuly_parse_universal_newlines_without_explicit_flag\n\n    def test_universal_newlines_parsing_flag(self):\n        def list_as_byte_list(l):\n            return list(map(lambda x:six.b(x),l))\n\n        expected_output = list(map(lambda x:list_as_byte_list(x),[['lifelock', 'LifeLock', '', 'web', 'Tempe', 'AZ', '1-May-07', '6850000', 'USD', 'b'],\n                           ['lifelock', 'LifeLock', '', 'web', 'Tempe', 'AZ', '1-Oct-06', '6000000', 'USD', 'a'],\n                           ['lifelock', 'LifeLock', '', 'web', 'Tempe', 'AZ', '1-Jan-08', '25000000', 'USD', 'c'],\n                           ['mycityfaces', 'MyCityFaces', '7', 'web', 'Scottsdale', 'AZ', '1-Jan-08', '50000', 'USD', 'seed'],\n                           ['flypaper', 'Flypaper', '', 'web', 'Phoenix', 'AZ', '1-Feb-08', '3000000', 'USD', 'a'],\n                           ['infusionsoft', 'Infusionsoft', '105', 'software', 'Gilbert', 'AZ', '1-Oct-07', '9000000', 'USD', 'a']]))\n\n        data = six.b('permalink,company,numEmps,category,city,state,fundedDate,raisedAmt,raisedCurrency,round\\rlifelock,LifeLock,,web,Tempe,AZ,1-May-07,6850000,USD,b\\rlifelock,LifeLock,,web,Tempe,AZ,1-Oct-06,6000000,USD,a\\rlifelock,LifeLock,,web,Tempe,AZ,1-Jan-08,25000000,USD,c\\rmycityfaces,MyCityFaces,7,web,Scottsdale,AZ,1-Jan-08,50000,USD,seed\\rflypaper,Flypaper,,web,Phoenix,AZ,1-Feb-08,3000000,USD,a\\rinfusionsoft,Infusionsoft,105,software,Gilbert,AZ,1-Oct-07,9000000,USD,a')\n        tmp_data_file = self.create_file_with_data(data)\n\n        cmd = Q_EXECUTABLE + ' -d , -H -U \"select permalink,company,numEmps,category,city,state,fundedDate,raisedAmt,raisedCurrency,round from %s\"' % tmp_data_file.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode,0)\n\n        if len(e) == 2 or len(e) == 1:\n            # In python 3.7, there's a deprecation warning for the 'U' file opening mode, which is ok for now\n            self.assertIn(len(e), [1,2])\n            self.assertTrue(b\"DeprecationWarning: 'U' mode is deprecated\" in e[0])\n        elif len(e) != 0:\n            # Nothing should be output to stderr in other versions\n            self.assertTrue(False,msg='Unidentified output in stderr')\n\n        self.assertEqual(len(o), 6)\n\n        actual_output = list(map(lambda row: row.split(six.b(\",\")),o))\n\n        self.assertEqual(actual_output,expected_output)\n\n        self.cleanup(tmp_data_file)\n\n\n\nclass SqlTests(AbstractQTestCase):\n\n    def test_find_example(self):\n        tmpfile = self.create_file_with_data(find_output)\n        cmd = Q_EXECUTABLE + ' \"select c5,c6,sum(c7)/1024.0/1024 as total from %s group by c5,c6 order by total desc\"' % tmpfile.name\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n        self.assertEqual(len(e), 0)\n\n        self.assertEqual(o[0], six.b('mapred mapred 0.9389581680297852'))\n        self.assertEqual(o[1], six.b('root root 0.02734375'))\n        self.assertEqual(o[2], six.b('harel harel 0.010888099670410156'))\n\n        self.cleanup(tmpfile)\n\n    def test_join_example(self):\n        cmd = Q_EXECUTABLE + ' \"select myfiles.c8,emails.c2 from {0}/exampledatafile myfiles join {0}/group-emails-example emails on (myfiles.c4 = emails.c1) where myfiles.c8 = \\'ppp\\'\"'.format(EXAMPLES)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 2)\n\n        self.assertEqual(o[0], six.b('ppp dip.1@otherdomain.com'))\n        self.assertEqual(o[1], six.b('ppp dip.2@otherdomain.com'))\n\n    def test_join_example_with_output_header(self):\n        cmd = Q_EXECUTABLE + ' -O \"select myfiles.c8 aaa,emails.c2 bbb from {0}/exampledatafile myfiles join {0}/group-emails-example emails on (myfiles.c4 = emails.c1) where myfiles.c8 = \\'ppp\\'\"'.format(EXAMPLES)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(o), 3)\n\n        self.assertEqual(o[0], six.b('aaa bbb'))\n        self.assertEqual(o[1], six.b('ppp dip.1@otherdomain.com'))\n        self.assertEqual(o[2], six.b('ppp dip.2@otherdomain.com'))\n\n    def test_self_join1(self):\n        tmpfile = self.create_file_with_data(six.b(\"\\n\").join([six.b(\"{} 9000\".format(i)) for i in range(0,10)]))\n        cmd = Q_EXECUTABLE + ' \"select * from %s a1 join %s a2 on (a1.c1 = a2.c1)\"' % (tmpfile.name,tmpfile.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 10)\n\n        self.cleanup(tmpfile)\n\n    def test_self_join_reuses_table(self):\n        tmpfile = self.create_file_with_data(six.b(\"\\n\").join([six.b(\"{} 9000\".format(i)) for i in range(0,10)]))\n        cmd = Q_EXECUTABLE + ' \"select * from %s a1 join %s a2 on (a1.c1 = a2.c1)\" -A' % (tmpfile.name,tmpfile.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 6)\n\n        self.assertEqual(o[0],six.b('Table: %s' % tmpfile.name))\n        self.assertEqual(o[1],six.b('  Sources:'))\n        self.assertEqual(o[2],six.b('    source_type: file source: %s') % six.b(tmpfile.name))\n        self.assertEqual(o[3],six.b('  Fields:'))\n        self.assertEqual(o[4],six.b('    `c1` - int'))\n        self.assertEqual(o[5],six.b('    `c2` - int'))\n\n        self.cleanup(tmpfile)\n\n    def test_self_join2(self):\n        tmpfile1 = self.create_file_with_data(six.b(\"\\n\").join([six.b(\"{} 9000\".format(i)) for i in range(0,10)]))\n        cmd = Q_EXECUTABLE + ' \"select * from %s a1 join %s a2 on (a1.c2 = a2.c2)\"' % (tmpfile1.name,tmpfile1.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 10*10)\n\n        self.cleanup(tmpfile1)\n\n        tmpfile2 = self.create_file_with_data(six.b(\"\\n\").join([six.b(\"{} 9000\".format(i)) for i in range(0,10)]))\n        cmd = Q_EXECUTABLE + ' \"select * from %s a1 join %s a2 on (a1.c2 = a2.c2) join %s a3 on (a1.c2 = a3.c2)\"' % (tmpfile2.name,tmpfile2.name,tmpfile2.name)\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 10*10*10)\n\n        self.cleanup(tmpfile2)\n\n    def test_disable_column_type_detection(self):\n        tmpfile = self.create_file_with_data(six.b('''regular_text,text_with_digits1,text_with_digits2,float_number\n\"regular text 1\",67,\"67\",12.3\n\"regular text 2\",067,\"067\",22.3\n\"regular text 3\",123,\"123\",33.4\n\"regular text 4\",-123,\"-123\",0122.2\n'''))\n\n        # Check original column type detection\n        cmd = Q_EXECUTABLE + ' -A -d , -H \"select * from %s\"' % (tmpfile.name)\n\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 8)\n\n        self.assertEqual(o[0],six.b('Table: %s' % tmpfile.name))\n        self.assertEqual(o[1], six.b('  Sources:'))\n        self.assertEqual(o[2], six.b('    source_type: file source: %s') % six.b(tmpfile.name))\n        self.assertEqual(o[3], six.b('  Fields:'))\n        self.assertEqual(o[4], six.b('    `regular_text` - text'))\n        self.assertEqual(o[5], six.b('    `text_with_digits1` - int'))\n        self.assertEqual(o[6], six.b('    `text_with_digits2` - int'))\n        self.assertEqual(o[7], six.b('    `float_number` - real'))\n\n        # Check column types detected when actual detection is disabled\n        cmd = Q_EXECUTABLE + ' -A -d , -H --as-text \"select * from %s\"' % (tmpfile.name)\n\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 8)\n\n        self.assertEqual(o[0],six.b('Table: %s' % tmpfile.name))\n        self.assertEqual(o[1],six.b('  Sources:'))\n        self.assertEqual(o[2],six.b('    source_type: file source: %s') % six.b(tmpfile.name))\n        self.assertEqual(o[3],six.b('  Fields:'))\n        self.assertEqual(o[4],six.b('    `regular_text` - text'))\n        self.assertEqual(o[5],six.b('    `text_with_digits1` - text'))\n        self.assertEqual(o[6],six.b('    `text_with_digits2` - text'))\n        self.assertEqual(o[7],six.b('    `float_number` - text'))\n\n        # Get actual data with regular detection\n        cmd = Q_EXECUTABLE + ' -d , -H \"select * from %s\"' % (tmpfile.name)\n\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 4)\n\n        self.assertEqual(o[0],six.b(\"regular text 1,67,67,12.3\"))\n        self.assertEqual(o[1],six.b(\"regular text 2,67,67,22.3\"))\n        self.assertEqual(o[2],six.b(\"regular text 3,123,123,33.4\"))\n        self.assertEqual(o[3],six.b(\"regular text 4,-123,-123,122.2\"))\n\n        # Get actual data without detection\n        cmd = Q_EXECUTABLE + ' -d , -H --as-text \"select * from %s\"' % (tmpfile.name)\n\n        retcode, o, e = run_command(cmd)\n\n        self.assertEqual(retcode, 0)\n        self.assertEqual(len(e), 0)\n        self.assertEqual(len(o), 4)\n\n        self.assertEqual(o[0],six.b(\"regular text 1,67,67,12.3\"))\n        self.assertEqual(o[1],six.b(\"regular text 2,067,067,22.3\"))\n        self.assertEqual(o[2],six.b(\"regular text 3,123,123,33.4\"))\n        self.assertEqual(o[3],six.b(\"regular text 4,-123,-123,0122.2\"))\n\n        self.cleanup(tmpfile)\n\n\nclass BasicModuleTests(AbstractQTestCase):\n\n    def test_engine_isolation(self):\n        tmpfile1 = self.create_file_with_data(six.b(\"a b c\\n1 2 3\\n4 5 6\"))\n        tmpfile2 = self.create_file_with_data(six.b(\"d e f\\n10 20 30\\n40 50 60\"))\n\n        # Run file 1 on engine 1\n        q1 = QTextAsData(QInputParams(skip_header=True,delimiter=' '))\n        r = q1.execute('select * from %s' % tmpfile1.name)\n        print(\"QueryQuery\",file=sys.stdout)\n\n        self.assertTrue(r.status == 'ok')\n        self.assertEqual(len(r.warnings),0)\n        self.assertEqual(len(r.data),2)\n        self.assertEqual(r.metadata.output_column_name_list,['a','b','c'])\n        self.assertEqual(r.data,[(1,2,3),(4,5,6)])\n        self.assertTrue(tmpfile1.name in r.metadata.table_structures)\n        self.assertTrue(tmpfile1.name in r.metadata.new_table_structures)\n        self.assertEqual(r.metadata.table_structures[tmpfile1.name].atomic_fns,[tmpfile1.name])\n        self.assertEqual(r.metadata.table_structures[tmpfile1.name].source_type,'file')\n        self.assertEqual(r.metadata.table_structures[tmpfile1.name].source,tmpfile1.name)\n\n        # run file 1 on engine 2\n        q2 = QTextAsData(QInputParams(skip_header=True,delimiter=' '))\n        r2 = q2.execute('select * from %s' % tmpfile1.name)\n        print(\"QueryQuery\",file=sys.stdout)\n\n        self.assertTrue(r2.status == 'ok')\n        self.assertEqual(len(r2.warnings),0)\n        self.assertEqual(len(r2.data),2)\n        self.assertEqual(r2.metadata.output_column_name_list,['a','b','c'])\n        self.assertEqual(r2.data,[(1,2,3),(4,5,6)])\n        self.assertTrue(tmpfile1.name in r2.metadata.table_structures)\n        self.assertTrue(tmpfile1.name in r2.metadata.new_table_structures)\n        self.assertEqual(r2.metadata.table_structures[tmpfile1.name].atomic_fns,[tmpfile1.name])\n        self.assertEqual(r2.metadata.table_structures[tmpfile1.name].source_type,'file')\n        self.assertEqual(r2.metadata.table_structures[tmpfile1.name].source,tmpfile1.name)\n\n        # run file 2 on engine 1\n        r3 = q1.execute('select * from %s' % tmpfile2.name)\n        print(\"QueryQuery\",file=sys.stdout)\n\n        print(r3)\n        self.assertTrue(r3.status == 'ok')\n        self.assertEqual(len(r3.warnings),0)\n        self.assertEqual(len(r3.data),2)\n        self.assertEqual(r3.metadata.output_column_name_list,['d','e','f'])\n        self.assertEqual(r3.data,[(10,20,30),(40,50,60)])\n        self.assertTrue(tmpfile2.name in r3.metadata.table_structures)\n        self.assertTrue(tmpfile2.name in r3.metadata.new_table_structures)\n        self.assertEqual(r3.metadata.table_structures[tmpfile2.name].atomic_fns,[tmpfile2.name])\n        self.assertEqual(r3.metadata.table_structures[tmpfile2.name].source,tmpfile2.name)\n        self.assertEqual(r3.metadata.table_structures[tmpfile2.name].source_type,'file')\n\n        q1.done()\n        q2.done()\n\n        self.cleanup(tmpfile1)\n        self.cleanup(tmpfile2)\n\n    def test_simple_query(self):\n        tmpfile = self.create_file_with_data(six.b(\"a b c\\n1 2 3\\n4 5 6\"))\n\n        q = QTextAsData(QInputParams(skip_header=True,delimiter=' '))\n        r = q.execute('select * from %s' % tmpfile.name)\n\n        self.assertTrue(r.status == 'ok')\n        self.assertEqual(len(r.warnings),0)\n        self.assertEqual(len(r.data),2)\n        self.assertEqual(r.metadata.output_column_name_list,['a','b','c'])\n        self.assertEqual(r.data,[(1,2,3),(4,5,6)])\n        self.assertTrue(tmpfile.name in r.metadata.table_structures)\n        self.assertTrue(tmpfile.name in r.metadata.new_table_structures)\n        self.assertEqual(r.metadata.table_structures[tmpfile.name].atomic_fns,[tmpfile.name])\n        self.assertEqual(r.metadata.table_structures[tmpfile.name].source_type,'file')\n        self.assertEqual(r.metadata.table_structures[tmpfile.name].source,tmpfile.name)\n\n        q.done()\n        self.cleanup(tmpfile)\n\n    def test_loaded_data_reuse(self):\n        tmpfile = self.create_file_with_data(six.b(\"a b c\\n1 2 3\\n4 5 6\"))\n\n        q = QTextAsData(QInputParams(skip_header=True,delimiter=' '))\n        r1 = q.execute('select * from %s' % tmpfile.name)\n\n        r2 = q.execute('select * from %s' % tmpfile.name)\n\n        self.assertTrue(r1.status == 'ok')\n        self.assertEqual(len(r1.warnings),0)\n        self.assertEqual(len(r1.data),2)\n        self.assertEqual(r1.metadata.output_column_name_list,['a','b','c'])\n        self.assertEqual(r1.data,[(1,2,3),(4,5,6)])\n        self.assertTrue(tmpfile.name in r1.metadata.table_structures)\n        self.assertTrue(tmpfile.name in r1.metadata.new_table_structures)\n        self.assertEqual(r1.metadata.table_structures[tmpfile.name].atomic_fns,[tmpfile.name])\n        self.assertEqual(r1.metadata.table_structures[tmpfile.name].source_type,'file')\n        self.assertEqual(r1.metadata.table_structures[tmpfile.name].source,tmpfile.name)\n\n        self.assertTrue(r2.status == 'ok')\n        self.assertTrue(tmpfile.name in r2.metadata.table_structures)\n        self.assertTrue(tmpfile.name not in r2.metadata.new_table_structures)\n        self.assertEqual(r2.data,r1.data)\n        self.assertEqual(r2.metadata.output_column_name_list,r2.metadata.output_column_name_list)\n        self.assertEqual(len(r2.warnings),0)\n\n        q.done()\n\n        self.cleanup(tmpfile)\n\n    def test_stdin_injection(self):\n        tmpfile = self.create_file_with_data(six.b(\"a b c\\n1 2 3\\n4 5 6\"))\n\n        data_streams_dict = {\n            '-': DataStream('stdin','-',codecs.open(tmpfile.name,'rb',encoding='utf-8'))\n        }\n        q = QTextAsData(QInputParams(skip_header=True,delimiter=' '),data_streams_dict=data_streams_dict)\n        r = q.execute('select * from -')\n\n        self.assertTrue(r.status == 'ok')\n        self.assertEqual(len(r.warnings),0)\n        self.assertEqual(len(r.data),2)\n        self.assertEqual(r.metadata.output_column_name_list,['a','b','c'])\n        self.assertEqual(r.data,[(1,2,3),(4,5,6)])\n        self.assertEqual(r.metadata.new_table_structures['-'],r.metadata.table_structures['-'])\n        self.assertEqual(r.metadata.table_structures['-'].column_names,['a','b','c'])\n        self.assertEqual(r.metadata.table_structures['-'].python_column_types,[int,int,int])\n        self.assertEqual(r.metadata.table_structures['-'].sqlite_column_types,['int','int','int'])\n        self.assertEqual(r.metadata.table_structures['-'].source_type,'data-stream')\n        self.assertEqual(r.metadata.table_structures['-'].source,'stdin')\n\n        q.done()\n        self.cleanup(tmpfile)\n\n    def test_named_stdin_injection(self):\n        tmpfile = self.create_file_with_data(six.b(\"a b c\\n1 2 3\\n4 5 6\"))\n\n        data_streams_dict = {\n            'my_stdin_data': DataStream('my_stdin_data','my_stdin_data',codecs.open(tmpfile.name,'rb',encoding='utf-8'))\n        }\n\n        q = QTextAsData(QInputParams(skip_header=True,delimiter=' '),data_streams_dict=data_streams_dict)\n        r = q.execute('select a from my_stdin_data')\n\n        self.assertTrue(r.status == 'ok')\n        self.assertEqual(len(r.warnings),0)\n        self.assertEqual(len(r.data),2)\n        self.assertEqual(r.metadata.output_column_name_list,['a'])\n        self.assertEqual(r.data,[(1,),(4,)])\n        self.assertTrue('my_stdin_data' in r.metadata.table_structures)\n        self.assertTrue('my_stdin_data' in r.metadata.new_table_structures)\n        self.assertEqual(r.metadata.table_structures['my_stdin_data'].qtable_name,'my_stdin_data')\n\n        q.done()\n        self.cleanup(tmpfile)\n\n    def test_data_stream_isolation(self):\n        tmpfile1 = self.create_file_with_data(six.b(\"a b c\\n1 2 3\\n4 5 6\"))\n        tmpfile2 = self.create_file_with_data(six.b(\"d e f\\n7 8 9\\n10 11 12\"))\n\n        data_streams_dict = {\n            'a-': DataStream('a-','a-',codecs.open(tmpfile1.name, 'rb', encoding='utf-8')),\n            'b-': DataStream('b-','b-',codecs.open(tmpfile2.name, 'rb', encoding='utf-8'))\n        }\n\n        q = QTextAsData(QInputParams(skip_header=True,delimiter=' '),data_streams_dict=data_streams_dict)\n        r1 = q.execute('select * from a-')\n\n        self.assertTrue(r1.status == 'ok')\n        self.assertEqual(len(r1.warnings),0)\n        self.assertEqual(len(r1.data),2)\n        self.assertEqual(r1.metadata.output_column_name_list,['a','b','c'])\n        self.assertEqual(r1.data,[(1,2,3),(4,5,6)])\n        self.assertTrue('a-' in r1.metadata.table_structures)\n        self.assertEqual(len(r1.metadata.table_structures),1)\n        self.assertEqual(r1.metadata.table_structures['a-'].source_type, 'data-stream')\n        self.assertEqual(r1.metadata.table_structures['a-'].source, 'a-')\n        self.assertEqual(r1.metadata.table_structures['a-'].column_names, ['a','b','c'])\n        self.assertEqual(r1.metadata.table_structures['a-'].python_column_types, [int,int,int])\n        self.assertEqual(r1.metadata.table_structures['a-'].sqlite_column_types, ['int','int','int'])\n\n        r2 = q.execute('select * from b-')\n\n        self.assertTrue(r2.status == 'ok')\n        self.assertEqual(len(r2.warnings),0)\n        self.assertEqual(len(r2.data),2)\n        self.assertEqual(r2.metadata.output_column_name_list,['d','e','f'])\n        self.assertEqual(r2.data,[(7,8,9),(10,11,12)])\n\n        self.assertEqual(len(r1.metadata.table_structures),2)\n        self.assertTrue('b-' in r1.metadata.table_structures)\n        self.assertEqual(r1.metadata.table_structures['b-'].source_type, 'data-stream')\n        self.assertEqual(r1.metadata.table_structures['b-'].source, 'b-')\n        self.assertEqual(r1.metadata.table_structures['b-'].column_names, ['d','e','f'])\n        self.assertEqual(r1.metadata.table_structures['b-'].python_column_types, [int,int,int])\n        self.assertEqual(r1.metadata.table_structures['b-'].sqlite_column_types, ['int','int','int'])\n\n        q.done()\n        self.cleanup(tmpfile1)\n        self.cleanup(tmpfile2)\n\n    def test_multiple_stdin_injection(self):\n        tmpfile1 = self.create_file_with_data(six.b(\"a b c\\n1 2 3\\n4 5 6\"))\n        tmpfile2 = self.create_file_with_data(six.b(\"d e f\\n7 8 9\\n10 11 12\"))\n\n        data_streams_dict = {\n            'my_stdin_data1': DataStream('my_stdin_data1','my_stdin_data1',codecs.open(tmpfile1.name,'rb',encoding='utf-8')),\n            'my_stdin_data2': DataStream('my_stdin_data2','my_stdin_data2',codecs.open(tmpfile2.name,'rb',encoding='utf-8'))\n        }\n        q = QTextAsData(QInputParams(skip_header=True,delimiter=' '),data_streams_dict=data_streams_dict)\n        r1 = q.execute('select * from my_stdin_data1')\n\n        self.assertTrue(r1.status == 'ok')\n        self.assertEqual(len(r1.warnings),0)\n        self.assertEqual(len(r1.data),2)\n        self.assertEqual(r1.metadata.output_column_name_list,['a','b','c'])\n        self.assertEqual(r1.data,[(1,2,3),(4,5,6)])\n        self.assertTrue('my_stdin_data1' in r1.metadata.table_structures)\n        self.assertTrue('my_stdin_data1' in r1.metadata.new_table_structures)\n        self.assertEqual(r1.metadata.table_structures['my_stdin_data1'].qtable_name,'my_stdin_data1')\n\n        r2 = q.execute('select * from my_stdin_data2')\n\n        self.assertTrue(r2.status == 'ok')\n        self.assertEqual(len(r2.warnings),0)\n        self.assertEqual(len(r2.data),2)\n        self.assertEqual(r2.metadata.output_column_name_list,['d','e','f'])\n        self.assertEqual(r2.data,[(7,8,9),(10,11,12)])\n        # There should be another data load, even though it's the same 'filename' as before\n        self.assertTrue('my_stdin_data2' in r2.metadata.table_structures)\n        self.assertTrue('my_stdin_data2' in r2.metadata.new_table_structures)\n        self.assertEqual(r2.metadata.table_structures['my_stdin_data2'].qtable_name,'my_stdin_data2')\n\n        r3 = q.execute('select aa.*,bb.* from my_stdin_data1 aa join my_stdin_data2 bb')\n\n        self.assertTrue(r3.status == 'ok')\n        self.assertEqual(len(r3.warnings),0)\n        self.assertEqual(len(r3.data),4)\n        self.assertEqual(r3.metadata.output_column_name_list,['a','b','c','d','e','f'])\n        self.assertEqual(r3.data,[(1,2,3,7,8,9),(1,2,3,10,11,12),(4,5,6,7,8,9),(4,5,6,10,11,12)])\n        self.assertTrue('my_stdin_data1' in r3.metadata.table_structures)\n        self.assertTrue('my_stdin_data1' not in r3.metadata.new_table_structures)\n\n        q.done()\n        self.cleanup(tmpfile1)\n        self.cleanup(tmpfile2)\n\n    def test_different_input_params_for_different_files(self):\n        tmpfile1 = self.create_file_with_data(six.b(\"a b c\\n1 2 3\\n4 5 6\"))\n        tmpfile2 = self.create_file_with_data(six.b(\"7\\t8\\t9\\n10\\t11\\t12\"))\n\n        q = QTextAsData(QInputParams(skip_header=True,delimiter=' '))\n\n        q.load_data(tmpfile1.name,QInputParams(skip_header=True,delimiter=' '))\n        q.load_data(tmpfile2.name,QInputParams(skip_header=False,delimiter='\\t'))\n\n        r = q.execute('select aa.*,bb.* from %s aa join %s bb' % (tmpfile1.name,tmpfile2.name))\n\n        self.assertTrue(r.status == 'ok')\n        self.assertEqual(len(r.warnings),0)\n        self.assertEqual(len(r.data),4)\n        self.assertEqual(r.metadata.output_column_name_list,['a','b','c','c1','c2','c3'])\n        self.assertEqual(r.data,[(1,2,3,7,8,9),(1,2,3,10,11,12),(4,5,6,7,8,9),(4,5,6,10,11,12)])\n        self.assertTrue(tmpfile1.name not in r.metadata.new_table_structures)\n        self.assertTrue(tmpfile2.name not in r.metadata.new_table_structures)\n\n        q.done()\n        self.cleanup(tmpfile1)\n        self.cleanup(tmpfile2)\n\n    def test_different_input_params_for_different_files_2(self):\n        tmpfile1 = self.create_file_with_data(six.b(\"a b c\\n1 2 3\\n4 5 6\"))\n        tmpfile2 = self.create_file_with_data(six.b(\"7\\t8\\t9\\n10\\t11\\t12\"))\n\n        q = QTextAsData()\n\n        q.load_data(tmpfile1.name,QInputParams(skip_header=True,delimiter=' '))\n        q.load_data(tmpfile2.name,QInputParams(skip_header=False,delimiter='\\t'))\n\n        r = q.execute('select aa.*,bb.* from %s aa join %s bb' % (tmpfile1.name,tmpfile2.name))\n\n        self.assertTrue(r.status == 'ok')\n        self.assertEqual(len(r.warnings),0)\n        self.assertEqual(len(r.data),4)\n        self.assertEqual(r.metadata.output_column_name_list,['a','b','c','c1','c2','c3'])\n        self.assertEqual(r.data,[(1,2,3,7,8,9),(1,2,3,10,11,12),(4,5,6,7,8,9),(4,5,6,10,11,12)])\n        self.assertTrue(tmpfile1.name not in r.metadata.new_table_structures)\n        self.assertTrue(tmpfile2.name not in r.metadata.new_table_structures)\n\n        q.done()\n        self.cleanup(tmpfile1)\n        self.cleanup(tmpfile2)\n\n    def test_input_params_override(self):\n        tmpfile = self.create_file_with_data(six.b(\"a b c\\n1 2 3\\n4 5 6\"))\n\n        default_input_params = QInputParams()\n\n        for k in default_input_params.__dict__.keys():\n            setattr(default_input_params,k,'GARBAGE')\n\n        q = QTextAsData(default_input_params)\n\n        r = q.execute('select * from %s' % tmpfile.name)\n\n        self.assertTrue(r.status == 'error')\n\n        overwriting_input_params = QInputParams(skip_header=True,delimiter=' ')\n\n        r2 = q.execute('select * from %s' % tmpfile.name,input_params=overwriting_input_params)\n\n        self.assertTrue(r2.status == 'ok')\n        self.assertEqual(len(r2.warnings),0)\n        self.assertEqual(len(r2.data),2)\n        self.assertEqual(r2.metadata.output_column_name_list,['a','b','c'])\n        self.assertEqual(r2.data,[(1,2,3),(4,5,6)])\n        self.assertTrue(tmpfile.name in r2.metadata.table_structures)\n        self.assertTrue(tmpfile.name in r2.metadata.new_table_structures)\n        self.assertEqual(r2.metadata.table_structures[tmpfile.name].atomic_fns,[tmpfile.name])\n        self.assertEqual(r2.metadata.table_structures[tmpfile.name].source,tmpfile.name)\n        self.assertEqual(r2.metadata.table_structures[tmpfile.name].source_type,'file')\n\n        q.done()\n        self.cleanup(tmpfile)\n\n    def test_input_params_merge(self):\n        input_params = QInputParams()\n\n        for k in input_params.__dict__.keys():\n            setattr(input_params,k,'GARBAGE')\n\n        merged_input_params = input_params.merged_with(QInputParams())\n\n        for k in merged_input_params.__dict__.keys():\n            self.assertTrue(getattr(merged_input_params,k) != 'GARBAGE')\n\n        for k in input_params.__dict__.keys():\n            self.assertTrue(getattr(merged_input_params,k) != 'GARBAGE')\n\n    def test_table_analysis_with_syntax_error(self):\n\n        q = QTextAsData()\n\n        q_output = q.analyze(\"bad syntax\")\n\n        q.done()\n        self.assertTrue(q_output.status == 'error')\n        self.assertTrue(q_output.error.msg.startswith('query error'))\n\n    def test_execute_response(self):\n        tmpfile = self.create_file_with_data(six.b(\"a b c\\n1 2 3\\n4 5 6\"))\n\n        q = QTextAsData()\n\n        q_output = q.execute(\"select a,c from %s\" % tmpfile.name,QInputParams(skip_header=True))\n\n        self.assertTrue(q_output.status == 'ok')\n        self.assertTrue(q_output.error is None)\n        self.assertEqual(len(q_output.warnings),0)\n        self.assertEqual(len(q_output.data),2)\n        self.assertEqual(q_output.data,[ (1,3),(4,6) ])\n        self.assertTrue(q_output.metadata is not None)\n\n        metadata = q_output.metadata\n\n        self.assertEqual(metadata.output_column_name_list, [ 'a','c'])\n        self.assertTrue(tmpfile.name in metadata.new_table_structures)\n        self.assertEqual(len(metadata.table_structures),1)\n\n        table_structure = metadata.new_table_structures[tmpfile.name]\n\n        self.assertEqual(table_structure.column_names,[ 'a','b','c'])\n        self.assertEqual(table_structure.python_column_types,[ int,int,int])\n        self.assertEqual(table_structure.sqlite_column_types,[ 'int','int','int'])\n        self.assertEqual(table_structure.qtable_name, tmpfile.name)\n        self.assertEqual(table_structure.atomic_fns,[tmpfile.name])\n        self.assertEqual(table_structure.source_type,'file')\n        self.assertEqual(table_structure.source,tmpfile.name)\n\n        q.done()\n        self.cleanup(tmpfile)\n\n    def test_analyze_response(self):\n        tmpfile = self.create_file_with_data(six.b(\"a b c\\n1 2 3\\n4 5 6\"))\n\n        q = QTextAsData()\n\n        q_output = q.analyze(\"select a,c from %s\" % tmpfile.name,QInputParams(skip_header=True))\n\n        self.assertTrue(q_output.status == 'ok')\n        self.assertTrue(q_output.error is None)\n        self.assertEqual(len(q_output.warnings),0)\n        self.assertEqual(len(q_output.data),2)\n        self.assertEqual(q_output.data,[ (1,3),(4,6) ])\n        self.assertTrue(q_output.metadata is not None)\n\n        metadata = q_output.metadata\n\n        self.assertEqual(metadata.output_column_name_list, [ 'a','c'])\n        self.assertEqual(len(metadata.table_structures),1)\n        self.assertTrue(tmpfile.name in metadata.new_table_structures)\n\n        table_structure = metadata.table_structures[tmpfile.name]\n\n        self.assertEqual(table_structure.column_names,[ 'a','b','c'])\n        self.assertEqual(table_structure.python_column_types,[ int,int,int])\n        self.assertEqual(table_structure.sqlite_column_types,[ 'int','int','int'])\n        self.assertEqual(table_structure.qtable_name, tmpfile.name)\n        self.assertEqual(table_structure.atomic_fns,[tmpfile.name])\n        self.assertEqual(table_structure.source_type,'file')\n        self.assertEqual(table_structure.source,tmpfile.name)\n\n        q.done()\n        self.cleanup(tmpfile)\n\n    def test_load_data_from_string_without_previous_data_load(self):\n        input_str = six.u('column1,column2,column3\\n') + six.u('\\n').join([six.u('value1,2.5,value3')] * 1000)\n\n\n        data_streams_dict = {\n            'my_data': DataStream('my_data_stream_id','my_data',six.StringIO(input_str))\n        }\n        q = QTextAsData(default_input_params=QInputParams(skip_header=True,delimiter=','),data_streams_dict=data_streams_dict)\n\n        q_output = q.execute('select column2,column3 from my_data')\n\n        self.assertTrue(q_output.status == 'ok')\n        self.assertTrue(q_output.error is None)\n        self.assertEqual(len(q_output.warnings),0)\n        self.assertTrue(len(q_output.data),1000)\n        self.assertEqual(len(set(q_output.data)),1)\n        self.assertEqual(list(set(q_output.data))[0],(2.5,'value3'))\n\n        metadata = q_output.metadata\n\n        self.assertTrue(metadata.output_column_name_list,['column2','column3'])\n        self.assertTrue('my_data' in metadata.new_table_structures)\n        self.assertEqual(len(metadata.table_structures),1)\n\n        table_structure = metadata.table_structures['my_data']\n\n        self.assertEqual(table_structure.column_names,['column1','column2','column3'])\n        self.assertEqual(table_structure.sqlite_column_types,['text','real','text'])\n        self.assertEqual(table_structure.python_column_types,[str,float,str])\n        self.assertEqual(table_structure.qtable_name, 'my_data')\n        self.assertEqual(table_structure.source_type, 'data-stream')\n        self.assertEqual(table_structure.source, 'my_data_stream_id')\n\n        q.done()\n\n    def test_load_data_from_string_with_previous_data_load(self):\n        input_str = six.u('column1,column2,column3\\n') + six.u('\\n').join([six.u('value1,2.5,value3')] * 1000)\n\n        data_streams_dict = {\n            'my_data': DataStream('a','my_data',six.StringIO(input_str))\n        }\n        q = QTextAsData(default_input_params=QInputParams(skip_header=True,delimiter=','),data_streams_dict=data_streams_dict)\n\n        dl = q.load_data('my_data',QInputParams(skip_header=True,delimiter=','))\n\n        q_output = q.execute('select column2,column3 from my_data')\n\n        self.assertTrue(q_output.status == 'ok')\n        self.assertTrue(q_output.error is None)\n        self.assertEqual(len(q_output.warnings),0)\n        self.assertTrue(len(q_output.data),1000)\n        self.assertEqual(len(set(q_output.data)),1)\n        self.assertEqual(list(set(q_output.data))[0],(2.5,'value3'))\n\n        metadata = q_output.metadata\n\n        self.assertTrue(metadata.output_column_name_list,['column2','column3'])\n        self.assertTrue('my_data' not in metadata.new_table_structures)\n        self.assertEqual(len(metadata.table_structures),1)\n\n        table_structure = metadata.table_structures['my_data']\n\n        self.assertEqual(table_structure.column_names,['column1','column2','column3'])\n        self.assertEqual(table_structure.sqlite_column_types,['text','real','text'])\n        self.assertEqual(table_structure.python_column_types,[str,float,str])\n        self.assertEqual(table_structure.qtable_name, 'my_data')\n\n        q.done()\n\n\n\nclass BenchmarkAttemptResults(object):\n    def __init__(self, attempt, lines, columns, duration,return_code):\n        self.attempt = attempt\n        self.lines = lines\n        self.columns = columns\n        self.duration = duration\n        self.return_code = return_code\n\n    def __str__(self):\n        return \"{}\".format(self.__dict__)\n    __repr__ = __str__\n\nclass BenchmarkResults(object):\n    def __init__(self, lines, columns, attempt_results, mean, stddev):\n        self.lines = lines\n        self.columns = columns\n        self.attempt_results = attempt_results\n        self.mean = mean\n        self.stddev = stddev\n\n    def __str__(self):\n        return \"{}\".format(self.__dict__)\n    __repr__ = __str__\n\n@pytest.mark.benchmark\nclass BenchmarkTests(AbstractQTestCase):\n\n    BENCHMARK_DIR = os.environ.get('Q_BENCHMARK_DATA_DIR')\n\n    def _ensure_benchmark_data_dir_exists(self):\n        try:\n            os.mkdir(BenchmarkTests.BENCHMARK_DIR)\n        except Exception as e:\n            pass\n\n    def _create_benchmark_file_if_needed(self):\n        self._ensure_benchmark_data_dir_exists()\n\n        if os.path.exists('{}/'.format(BenchmarkTests.BENCHMARK_DIR)):\n            return\n\n        g = GzipFile('unit-file.csv.gz')\n        d = g.read().decode('utf-8')\n        f = open('{}/benchmark-file.csv'.format(BenchmarkTests.BENCHMARK_DIR), 'w')\n        for i in range(100):\n            f.write(d)\n        f.close()\n\n    def _prepare_test_file(self, lines, columns):\n\n        filename = '{}/_benchmark_data__lines_{}_columns_{}.csv'.format(BenchmarkTests.BENCHMARK_DIR,lines, columns)\n\n        if os.path.exists(filename):\n            return filename\n\n        c = ['c{}'.format(x + 1) for x in range(columns)]\n\n        # write a header line\n        ff = open(filename,'w')\n        ff.write(\",\".join(c))\n        ff.write('\\n')\n        ff.close()\n\n        r, o, e = run_command('head -{} {}/benchmark-file.csv | ' + Q_EXECUTABLE + ' -d , \"select {} from -\" >> {}'.format(lines, BenchmarkTests.BENCHMARK_DIR, ','.join(c), filename))\n        self.assertEqual(r, 0)\n        # Create file cache as part of preparation\n        r, o, e = run_command(Q_EXECUTABLE + ' -C readwrite -d , \"select count(*) from %s\"' % filename)\n        self.asserEqual(r, 0)\n        return filename\n\n    def _decide_result(self,attempt_results):\n\n        failed = list(filter(lambda a: a.return_code != 0,attempt_results))\n\n        if len(failed) == 0:\n            mean = sum([x.duration for x in attempt_results]) / len(attempt_results)\n            sum_squared = sum([(x.duration - mean)**2 for x in attempt_results])\n            ddof = 0\n            pvar = sum_squared / (len(attempt_results) - ddof)\n            stddev = pvar ** 0.5\n        else:\n            mean = None\n            stddev = None\n\n        return BenchmarkResults(\n            attempt_results[0].lines,\n            attempt_results[0].columns,\n            attempt_results,\n            mean,\n            stddev\n        )\n\n    def _perform_test_performance_matrix(self,name,generate_cmd_function):\n        results = []\n\n        benchmark_results_folder = os.environ.get(\"Q_BENCHMARK_RESULTS_FOLDER\",'')\n        if benchmark_results_folder == \"\":\n            raise Exception(\"Q_BENCHMARK_RESULTS_FOLDER must be provided as an environment variable\")\n\n        self._create_benchmark_file_if_needed()\n        for columns in [1, 5, 10, 20, 50, 100]:\n            for lines in [1, 10, 100, 1000, 10000, 100000, 1000000]:\n                attempt_results = []\n                for attempt in range(10):\n                    filename = self._prepare_test_file(lines, columns)\n                    if DEBUG:\n                        print(\"Testing {}\".format(filename))\n                    t0 = time.time()\n                    r, o, e = run_command(generate_cmd_function(filename,lines,columns))\n                    duration = time.time() - t0\n                    attempt_result = BenchmarkAttemptResults(attempt, lines, columns, duration, r)\n                    attempt_results += [attempt_result]\n                    if DEBUG:\n                        print(\"Results: {}\".format(attempt_result.__dict__))\n                final_result = self._decide_result(attempt_results)\n                results += [final_result]\n\n        series_fields = [six.u('lines'),six.u('columns')]\n        value_fields = [six.u('mean'),six.u('stddev')]\n\n        all_fields = series_fields + value_fields\n\n        output_filename = '{}/{}.benchmark-results'.format(benchmark_results_folder,name)\n        output_file = open(output_filename,'w')\n        for columns,g in itertools.groupby(sorted(results,key=lambda x:x.columns),key=lambda x:x.columns):\n            x = six.u(\"\\t\").join(series_fields + [six.u('{}_{}').format(name, f) for f in value_fields])\n            print(x,file = output_file)\n            for result in g:\n                print(six.u(\"\\t\").join(map(str,[getattr(result,f) for f in all_fields])),file=output_file)\n        output_file.close()\n\n        print(\"results have been written to : {}\".format(output_filename))\n        if DEBUG:\n            print(\"RESULTS FOR {}\".format(name))\n            print(open(output_filename,'r').read())\n\n    def test_q_matrix(self):\n        Q_BENCHMARK_NAME = os.environ.get('Q_BENCHMARK_NAME')\n        if Q_BENCHMARK_NAME is None:\n            raise Exception('Q_BENCHMARK_NAME must be provided as an env var')\n\n        def generate_q_cmd(data_filename, line_count, column_count):\n            Q_BENCHMARK_ADDITIONAL_PARAMS = os.environ.get('Q_BENCHMARK_ADDITIONAL_PARAMS') or ''\n            additional_params = ''\n            additional_params = additional_params + ' ' + Q_BENCHMARK_ADDITIONAL_PARAMS\n            return '{} -d , {} \"select count(*) from {}\"'.format(Q_EXECUTABLE,additional_params, data_filename)\n        self._perform_test_performance_matrix(Q_BENCHMARK_NAME,generate_q_cmd)\n\n    def _get_textql_version(self):\n        r,o,e = run_command(\"textql --version\")\n        if r != 0:\n            raise Exception(\"Could not find textql\")\n        if len(e) != 0:\n            raise Exception(\"Errors while getting textql version\")\n        return o[0]\n\n    def _get_octosql_version(self):\n        r,o,e = run_command(\"octosql --version\")\n        if r != 0:\n            raise Exception(\"Could not find octosql\")\n        if len(e) != 0:\n            raise Exception(\"Errors while getting octosql version\")\n        version = re.findall('v[0-9]+\\\\.[0-9]+\\\\.[0-9]+',str(o[0],encoding='utf-8'))[0]\n        return version\n\n    def test_textql_matrix(self):\n        def generate_textql_cmd(data_filename,line_count,column_count):\n            return 'textql -dlm , -sql \"select count(*)\" {}'.format(data_filename)\n\n        name = 'textql_%s' % self._get_textql_version()\n        self._perform_test_performance_matrix(name,generate_textql_cmd)\n\n    def test_octosql_matrix(self):\n        config_fn = self.random_tmp_filename('octosql', 'config')\n        def generate_octosql_cmd(data_filename,line_count,column_count):\n            j = \"\"\"\ndataSources:\n  - name: bmdata\n    type: csv\n    config:\n      path: \"{}\"\n      headerRow: false\n      batchSize: 10000\n\"\"\".format(data_filename)[1:]\n            f = open(config_fn,'w')\n            f.write(j)\n            f.close()\n            return 'octosql -c {} -o batch-csv \"select count(*) from bmdata a\"'.format(config_fn)\n\n        name = 'octosql_%s' % self._get_octosql_version()\n        self._perform_test_performance_matrix(name,generate_octosql_cmd)\n\ndef suite():\n    tl = unittest.TestLoader()\n    basic_stuff = tl.loadTestsFromTestCase(BasicTests)\n    parsing_mode = tl.loadTestsFromTestCase(ParsingModeTests)\n    sql = tl.loadTestsFromTestCase(SqlTests)\n    formatting = tl.loadTestsFromTestCase(FormattingTests)\n    basic_module_stuff = tl.loadTestsFromTestCase(BasicModuleTests)\n    save_db_to_disk_tests = tl.loadTestsFromTestCase(SaveDbToDiskTests)\n    user_functions_tests = tl.loadTestsFromTestCase(UserFunctionTests)\n    multi_header_tests = tl.loadTestsFromTestCase(MultiHeaderTests)\n    return unittest.TestSuite([basic_module_stuff, basic_stuff, parsing_mode, sql, formatting,save_db_to_disk_tests,multi_header_tests,user_functions_tests])\n\nif __name__ == '__main__':\n    if len(sys.argv) > 1:\n        suite = unittest.TestSuite()\n        if '.' in sys.argv[1]:\n            c,m = sys.argv[1].split(\".\")\n            suite.addTest(globals()[c](m))\n        else:\n            tl = unittest.TestLoader()\n            tc = tl.loadTestsFromTestCase(globals()[sys.argv[1]])\n            suite = unittest.TestSuite([tc])\n    else:\n        suite = suite()\n\n    test_runner = unittest.TextTestRunner(verbosity=2)\n    result = test_runner.run(suite)\n    sys.exit(not result.wasSuccessful())\n"
  },
  {
    "path": "test-requirements.txt",
    "content": "pytest==6.2.2\nflake8==3.6.0\nsix==1.11.0\n"
  }
]