[
  {
    "path": ".bumpversion.cfg",
    "content": "[bumpversion]\ncurrent_version = 0.9.12\nfiles = SQLTools.py\ntag = True\ncommit = True\n\n"
  },
  {
    "path": ".gitignore",
    "content": ".DS_Store\n*.pyc\n*.py~\n*.sublime-workspace\n.idea/\n"
  },
  {
    "path": ".mention-bot",
    "content": "{\n  \"maxReviewers\": 2,\n  \"skipCollaboratorPR\": true\n}\n"
  },
  {
    "path": ".no-sublime-package",
    "content": ""
  },
  {
    "path": "Default (Linux).sublime-keymap",
    "content": "[\n    { \"keys\": [\"ctrl+alt+e\"], \"command\": \"st_select_connection\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+e\"], \"command\": \"st_execute\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+a\"], \"command\": \"st_execute_all\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+x\"], \"command\": \"st_explain_plan\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+h\"], \"command\": \"st_history\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+s\"], \"command\": \"st_show_records\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+d\"], \"command\": \"st_desc_table\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+f\"], \"command\": \"st_desc_function\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+b\"], \"command\": \"st_format\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+q\"], \"command\": \"st_save_query\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+r\"], \"command\": \"st_remove_saved_query\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+l\"], \"command\": \"st_list_queries\", \"args\": {\"mode\" : \"run\"}},\n    { \"keys\": [\"ctrl+e\", \"ctrl+o\"], \"command\": \"st_list_queries\", \"args\": {\"mode\" : \"open\"}},\n    { \"keys\": [\"ctrl+e\", \"ctrl+i\"], \"command\": \"st_list_queries\", \"args\": {\"mode\" : \"insert\"}}\n]\n"
  },
  {
    "path": "Default (OSX).sublime-keymap",
    "content": "[\n    { \"keys\": [\"ctrl+super+e\"], \"command\": \"st_select_connection\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+e\"], \"command\": \"st_execute\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+a\"], \"command\": \"st_execute_all\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+x\"], \"command\": \"st_explain_plan\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+h\"], \"command\": \"st_history\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+s\"], \"command\": \"st_show_records\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+d\"], \"command\": \"st_desc_table\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+f\"], \"command\": \"st_desc_function\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+b\"], \"command\": \"st_format\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+q\"], \"command\": \"st_save_query\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+r\"], \"command\": \"st_remove_saved_query\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+l\"], \"command\": \"st_list_queries\", \"args\": {\"mode\" : \"run\"}},\n    { \"keys\": [\"ctrl+e\", \"ctrl+o\"], \"command\": \"st_list_queries\", \"args\": {\"mode\" : \"open\"}},\n    { \"keys\": [\"ctrl+e\", \"ctrl+i\"], \"command\": \"st_list_queries\", \"args\": {\"mode\" : \"insert\"}}\n]\n"
  },
  {
    "path": "Default (Windows).sublime-keymap",
    "content": "[\n    { \"keys\": [\"ctrl+alt+e\"], \"command\": \"st_select_connection\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+e\"], \"command\": \"st_execute\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+a\"], \"command\": \"st_execute_all\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+x\"], \"command\": \"st_explain_plan\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+h\"], \"command\": \"st_history\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+s\"], \"command\": \"st_show_records\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+d\"], \"command\": \"st_desc_table\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+f\"], \"command\": \"st_desc_function\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+b\"], \"command\": \"st_format\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+q\"], \"command\": \"st_save_query\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+r\"], \"command\": \"st_remove_saved_query\" },\n    { \"keys\": [\"ctrl+e\", \"ctrl+l\"], \"command\": \"st_list_queries\", \"args\": {\"mode\" : \"run\"}},\n    { \"keys\": [\"ctrl+e\", \"ctrl+o\"], \"command\": \"st_list_queries\", \"args\": {\"mode\" : \"open\"}},\n    { \"keys\": [\"ctrl+e\", \"ctrl+i\"], \"command\": \"st_list_queries\", \"args\": {\"mode\" : \"insert\"}}\n]\n"
  },
  {
    "path": "Default.sublime-commands",
    "content": "[\n  {\n    \"caption\": \"ST: Select Connection\",\n    \"command\": \"st_select_connection\"\n  },\n  {\n    \"caption\": \"ST: Execute\",\n    \"command\": \"st_execute\"\n  },\n  {\n    \"caption\": \"ST: Execute All File\",\n    \"command\": \"st_execute_all\"\n  },\n  {\n    \"caption\": \"ST: Explain Plan\",\n    \"command\": \"st_explain_plan\"\n  },\n  {\n    \"caption\": \"ST: History\",\n    \"command\": \"st_history\"\n  },\n  {\n    \"caption\": \"ST: Show Table Records\",\n    \"command\": \"st_show_records\"\n  },\n  {\n    \"caption\": \"ST: Table Description\",\n    \"command\": \"st_desc_table\"\n  },\n  {\n    \"caption\": \"ST: Function Description\",\n    \"command\": \"st_desc_function\"\n  },\n  {\n    \"caption\": \"ST: Refresh Connection Data\",\n    \"command\": \"st_refresh_connection_data\"\n  },\n  {\n    \"caption\": \"ST: Save Query\",\n    \"command\": \"st_save_query\"\n  },\n  {\n    \"caption\": \"ST: Remove Saved Query\",\n    \"command\": \"st_remove_saved_query\"\n  },\n  {\n    \"caption\": \"ST: List and Run Saved Queries\",\n    \"command\": \"st_list_queries\",\n    \"args\"   : {\"mode\": \"run\"}\n  },\n  {\n    \"caption\": \"ST: List and Open Saved Queries\",\n    \"command\": \"st_list_queries\",\n    \"args\"   :  {\"mode\": \"open\"}\n  },\n  {\n    \"caption\": \"ST: List and Insert Saved Queries\",\n    \"command\": \"st_list_queries\",\n    \"args\"   :  {\"mode\": \"insert\"}\n  },\n  {\n    \"caption\": \"ST: Format SQL\",\n    \"command\": \"st_format\"\n  },\n  {\n    \"caption\": \"ST: Format SQL All File\",\n    \"command\": \"st_format_all\"\n  },\n  {\n    \"caption\": \"ST: About\",\n    \"command\": \"st_version\"\n  },\n  {\n    \"caption\": \"ST: Setup Connections\",\n    \"command\": \"edit_settings\", \"args\":\n    {\n      \"base_file\": \"${packages}/SQLTools/SQLToolsConnections.sublime-settings\",\n      \"default\": \"// List all your connections to DBs here\\n{\\n\\t\\\"connections\\\": {\\n\\t\\t$0\\n\\t},\\n\\t\\\"default\\\": null\\n}\"\n    }\n  },\n  {\n    \"caption\": \"ST: Settings\",\n    \"command\": \"edit_settings\", \"args\":\n    {\n      \"base_file\": \"${packages}/SQLTools/SQLTools.sublime-settings\",\n      \"default\": \"// Settings in here override those in \\\"SQLTools/SQLTools.sublime-settings\\\"\\n{\\n\\t$0\\n}\\n\"\n    }\n  }\n]\n"
  },
  {
    "path": "ISSUE_TEMPLATE.md",
    "content": "> This issue template helps us understand your SQLTools issues better. \n>\n> You don't need to stick to this template, but please try to guide us to reproduce the errors or understand your feature requests. \n> \n> Before submitting an issue, please consider these things first: \n> * Are you running the latest version? If not, try to upgrade.\n> * Did you check the [Setup Guide](https://code.mteixeira.dev/SublimeText-SQLTools/)?\n> * Did you check the logs in console (``Ctrl+` `` or select *View → Show Console*)?\n\n### Issue Type\n\nFeature Request |\nBug/Error |\nQuestion |\nOther\n\n### Description\n\n[Description of the bug / feature / question]\n\n### Version\n\n- *SQLTools Version*: vX.Y.Z\n- *OS*: (Windows, Mac, Linux)\n- *RDBMS*: (MySQL, PostgreSQL, Oracle, MSSQL, SQLite, Vertica, ...)\n\n> You can get this information by executing `ST: About` from Sublime `Command Palette`.\n\n### Steps to Reproduce (For bugfixes)\n\n1. [First Step]\n2. [Second Step]\n3. [and so on...]\n\n**Expected behavior:** [What you expected to happen]\n\n**Actual behavior:** [What actually happened]\n"
  },
  {
    "path": "LICENSE.md",
    "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    <program>  Copyright (C) <year>  <name of author>\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": "Main.sublime-menu",
    "content": "[\n    {\n        \"caption\": \"Preferences\",\n        \"mnemonic\": \"n\",\n        \"id\": \"preferences\",\n        \"children\":\n        [\n            {\n                \"caption\": \"Package Settings\",\n                \"mnemonic\": \"P\",\n                \"id\": \"package-settings\",\n                \"children\":\n                [\n                    {\n                        \"caption\": \"SQLTools\",\n                        \"children\":\n                        [\n                            {\n                                \"caption\": \"Connections\",\n                                \"command\": \"edit_settings\", \"args\":\n                                {\n                                    \"base_file\": \"${packages}/SQLTools/SQLToolsConnections.sublime-settings\",\n                                    \"default\": \"// List all your connections to DBs here\\n{\\n\\t\\\"connections\\\": {\\n\\t\\t$0\\n\\t},\\n\\t\\\"default\\\": null\\n}\"\n                                }\n                            },\n                            {\n                                \"caption\": \"Settings\",\n                                \"command\": \"edit_settings\", \"args\":\n                                {\n                                    \"base_file\": \"${packages}/SQLTools/SQLTools.sublime-settings\",\n                                    \"default\": \"// Settings in here override those in \\\"SQLTools/SQLTools.sublime-settings\\\"\\n{\\n\\t$0\\n}\\n\"\n                                }\n                            },\n                            {\n                                \"caption\": \"Key Bindings\",\n                                \"command\": \"edit_settings\", \"args\":\n                                {\n                                    \"base_file\": \"${packages}/SQLTools/Default ($platform).sublime-keymap\",\n                                    \"default\": \"[\\n\\t$0\\n]\\n\"\n                                }\n                            }\n                        ]\n                    }\n                ]\n            }\n        ]\n    }\n]\n"
  },
  {
    "path": "README.md",
    "content": "![SQLTools](https://github.com/mtxr/SQLTools/raw/images/icon.png?raw=true) SQLTools\n===============\n\n> Looking for maintainers! I'm currently using VSCode as my editor, so I'm not actively maintaining this project anymore.\n>\n> If you are interested in maintaining this project, contact me.\n>\n> If you are interested in checking VSCode version, see [https://github.com/mtxr/vscode-sqltools](https://github.com/mtxr/vscode-sqltools).\n\n\n[![Join the chat at https://gitter.im/SQLTools/Lobby](https://badges.gitter.im/SQLTools/Lobby.svg)](https://gitter.im/SQLTools/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n\nYour swiss knife SQL for Sublime Text.\n\nWrite your SQL with smart completions and handy table and function definitions, execute SQL and explain queries, format your queries and save them in history.\n\nProject website: [https://code.mteixeira.dev/SublimeText-SQLTools/](https://code.mteixeira.dev/SublimeText-SQLTools/)\n\n> If you are looking for VSCode version go to [https://github.com/mtxr/vscode-sqltools](https://github.com/mtxr/vscode-sqltools).\n\n## Donate\n\nSQLTools was developed with ♥ to save us time during our programming journey. But It also takes me time and efforts to develop SQLTools.\n\nSQLTools will save you (for sure) a lot of time and help you to increase your productivity so, I hope you can donate and help SQLTools to become more awesome than ever.\n\n<a href=\"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=RSMB6DGK238V8\" title=\"Donate to this project using Paypal\"><img src=\"https://img.shields.io/badge/paypal-donate-yellow.svg\" alt=\"PayPal donate button\" /></a>\n\n## Features\n\n* Works with PostgreSQL, MySQL, Oracle, MSSQL, SQLite, Vertica, Firebird and Snowflake\n* Smart completions (except SQLite)\n* Run SQL Queries &nbsp; <kbd>CTRL+e</kbd>, <kbd>CTRL+e</kbd>\n![Auto complete and run SQL queries](https://github.com/mtxr/SQLTools/raw/images/execute_auto_complete.gif?raw=true)\n* View table description &nbsp; <kbd>CTRL+e</kbd>, <kbd>CTRL+d</kbd>\n![View table schemas](https://github.com/mtxr/SQLTools/raw/images/table_description.gif?raw=true)\n* Show table records &nbsp; <kbd>CTRL+e</kbd>, <kbd>CTRL+s</kbd>\n![Show table records](https://github.com/mtxr/SQLTools/raw/images/table_records.gif?raw=true)\n* Show explain plan for queries &nbsp; <kbd>CTRL+e</kbd>, <kbd>CTRL+x</kbd>\n* Formatting SQL Queries &nbsp; <kbd>CTRL+e</kbd>, <kbd>CTRL+b</kbd>\n![Formatting SQL Queries](https://github.com/mtxr/SQLTools/raw/images/format_sql.gif?raw=true)\n* View Queries history &nbsp; <kbd>CTRL+e</kbd>, <kbd>CTRL+h</kbd>\n* Save queries &nbsp; <kbd>CTRL+e</kbd>, <kbd>CTRL+q</kbd>\n* List and Run saved queries &nbsp; <kbd>CTRL+e</kbd>, <kbd>CTRL+l</kbd>\n* Remove saved queries &nbsp; <kbd>CTRL+e</kbd>, <kbd>CTRL+r</kbd>\n* Threading support to prevent lockups\n* Query timeout (kill thread if query takes too long)\n\n## Installing\n\n### Using Sublime Package Control\n\nIf you are using [Sublime Package Control](https://packagecontrol.io/packages/SQLTools), you can easily install SQLTools via the `Package Control: Install Package` menu item.\n\n1. Press <kbd>CTRL+SHIFT+p</kbd>\n2. Type *`Install Package`*\n3. Find *`SQLTools`*\n4. Wait & Done!\n\n### Download Manually\n\nI strongly recommend you to use Package Control. It helps you to keep the package updated with the last version.\n\n1. Download the latest released zip file [here](https://github.com/mtxr/SublimeText-SQLTools/releases/latest)\n2. Unzip the files and rename the folder to `SQLTools`\n3. Find your `Packages` directory using the menu item  `Preferences -> Browse Packages...`\n4. Copy the folder into your Sublime Text `Packages` directory\n\n### Using SQLTools with Mac OS X\n\nSublime Text has it's environment variable `PATH` set from launchctl, not by your shell. Binaries installed by packages such as homebrew, for instance `psql` DB CLI for `PostgreSQL`, cannot be found by Sublime Text and results in error in Sublime Text console by `SQLTools`. Installing the package `Fix Mac Path` or setting the full path to your DB CLI binary in `SQLTools.sublime-settings` resolves this issue. Package can be downloaded via [PackageControl](https://packagecontrol.io/packages/Fix%20Mac%20Path) or [github](https://github.com/int3h/SublimeFixMacPath).\n\n## Contributors\n\nThis project exists thanks to all the people who [contribute](https://github.com/mtxr/SublimeText-SQLTools/graphs/contributors).\n\n\n## Configuration \n\nDocumentation: [https://code.mteixeira.dev/SublimeText-SQLTools/](https://code.mteixeira.dev/SublimeText-SQLTools/)\n\n\n\n\n"
  },
  {
    "path": "SQLTools.py",
    "content": "__version__ = \"v0.9.12\"\n\nimport sys\nimport os\nimport re\nimport logging\nfrom collections import OrderedDict\n\nimport sublime\nfrom sublime_plugin import WindowCommand, EventListener, TextCommand\nfrom Default.paragraph import expand_to_paragraph\n\nfrom .SQLToolsAPI import Utils\nfrom .SQLToolsAPI.Storage import Storage, Settings\nfrom .SQLToolsAPI.Connection import Connection\nfrom .SQLToolsAPI.History import History\nfrom .SQLToolsAPI.Completion import Completion\n\nMESSAGE_RUNNING_CMD = 'Executing SQL command...'\nSYNTAX_PLAIN_TEXT = 'Packages/Text/Plain text.tmLanguage'\nSYNTAX_SQL = 'Packages/SQL/SQL.tmLanguage'\nSQLTOOLS_SETTINGS_FILE = 'SQLTools.sublime-settings'\nSQLTOOLS_CONNECTIONS_FILE = 'SQLToolsConnections.sublime-settings'\nSQLTOOLS_QUERIES_FILE = 'SQLToolsSavedQueries.sublime-settings'\n\nUSER_FOLDER                  = None\nDEFAULT_FOLDER               = None\nSETTINGS_FILENAME            = None\nSETTINGS_FILENAME_DEFAULT    = None\nCONNECTIONS_FILENAME         = None\nCONNECTIONS_FILENAME_DEFAULT = None\nQUERIES_FILENAME             = None\nQUERIES_FILENAME_DEFAULT     = None\nsettingsStore                = None\nqueriesStore                 = None\nconnectionsStore             = None\nhistoryStore                 = None\n\n# create pluggin logger\nDEFAULT_LOG_LEVEL = logging.WARNING\nplugin_logger = logging.getLogger(__package__)\n# some plugins are not playing by the rules and configure the root loger\nplugin_logger.propagate = False\nif not plugin_logger.handlers:\n    plugin_logger_handler = logging.StreamHandler()\n    plugin_logger_formatter = logging.Formatter(\"[{name}] {levelname}: {message}\", style='{')\n    plugin_logger_handler.setFormatter(plugin_logger_formatter)\n    plugin_logger.addHandler(plugin_logger_handler)\nplugin_logger.setLevel(DEFAULT_LOG_LEVEL)\nlogger = logging.getLogger(__name__)\n\n\ndef getSublimeUserFolder():\n    return os.path.join(sublime.packages_path(), 'User')\n\n\ndef startPlugin():\n    global USER_FOLDER, DEFAULT_FOLDER\n    global SETTINGS_FILENAME, SETTINGS_FILENAME_DEFAULT\n    global CONNECTIONS_FILENAME, CONNECTIONS_FILENAME_DEFAULT\n    global QUERIES_FILENAME, QUERIES_FILENAME_DEFAULT\n    global settingsStore, queriesStore, connectionsStore, historyStore\n\n    USER_FOLDER = getSublimeUserFolder()\n    DEFAULT_FOLDER = os.path.dirname(__file__)\n\n    SETTINGS_FILENAME            = os.path.join(USER_FOLDER, SQLTOOLS_SETTINGS_FILE)\n    SETTINGS_FILENAME_DEFAULT    = os.path.join(DEFAULT_FOLDER, SQLTOOLS_SETTINGS_FILE)\n    CONNECTIONS_FILENAME         = os.path.join(USER_FOLDER, SQLTOOLS_CONNECTIONS_FILE)\n    CONNECTIONS_FILENAME_DEFAULT = os.path.join(DEFAULT_FOLDER, SQLTOOLS_CONNECTIONS_FILE)\n    QUERIES_FILENAME             = os.path.join(USER_FOLDER, SQLTOOLS_QUERIES_FILE)\n    QUERIES_FILENAME_DEFAULT     = os.path.join(DEFAULT_FOLDER, SQLTOOLS_QUERIES_FILE)\n\n    try:\n        settingsStore = Settings(SETTINGS_FILENAME, default=SETTINGS_FILENAME_DEFAULT)\n    except Exception as e:\n        msg = '{0}: Failed to parse {1} file'.format(__package__, SQLTOOLS_SETTINGS_FILE)\n        logging.exception(msg)\n        Window().status_message(msg)\n\n    try:\n        connectionsStore = Settings(CONNECTIONS_FILENAME, default=CONNECTIONS_FILENAME_DEFAULT)\n    except Exception as e:\n        msg = '{0}: Failed to parse {1} file'.format(__package__, SQLTOOLS_CONNECTIONS_FILE)\n        logging.exception(msg)\n        Window().status_message(msg)\n\n    queriesStore = Storage(QUERIES_FILENAME, default=QUERIES_FILENAME_DEFAULT)\n    historyStore = History(settingsStore.get('history_size', 100))\n\n    if settingsStore.get('debug', False):\n        plugin_logger.setLevel(logging.DEBUG)\n    else:\n        plugin_logger.setLevel(DEFAULT_LOG_LEVEL)\n\n    Connection.setTimeout(settingsStore.get('thread_timeout', 15))\n    Connection.setHistoryManager(historyStore)\n\n    logger.info('plugin (re)loaded')\n    logger.info('version %s', __version__)\n\n\ndef readConnections():\n    mergedConnections = {}\n\n    # fixes #39 and #45\n    if not connectionsStore:\n        startPlugin()\n\n    # global connections\n    globalConnectionsDict = connectionsStore.get('connections', {})\n    # project-specific connections\n    projectConnectionsDict = {}\n    projectData = Window().project_data()\n    if projectData:\n        projectConnectionsDict = projectData.get('connections', {})\n\n    # merge connections\n    mergedConnections = globalConnectionsDict.copy()\n    mergedConnections.update(projectConnectionsDict)\n\n    ordered = OrderedDict(sorted(mergedConnections.items()))\n\n    return ordered\n\n\ndef getDefaultConnectionName():\n    default = connectionsStore.get('default', False)\n    if not default:\n        return\n    return default\n\n\ndef createOutput(panel=None, syntax=None, prependText=None):\n    onInitialOutput = None\n    if not panel:\n        panel, onInitialOutput = getOutputPlace(syntax)\n    if prependText:\n        panel.run_command('append', {'characters': str(prependText)})\n\n    initial = True\n\n    def append(outputContent):\n        nonlocal initial\n        if initial:\n            initial = False\n            if onInitialOutput:\n                onInitialOutput()\n\n        # append content\n        panel.set_read_only(False)\n        panel.run_command('append', {'characters': outputContent})\n        panel.set_read_only(True)\n\n    return append\n\n\ndef toNewTab(content, name=\"\", suffix=\"SQLTools Saved Query\"):\n    resultContainer = Window().new_file()\n    resultContainer.set_name(\n        ((name + \" - \") if name != \"\" else \"\") + suffix)\n    resultContainer.set_syntax_file(SYNTAX_SQL)\n    resultContainer.run_command('append', {'characters': content})\n\n\ndef insertContent(content):\n    view = View()\n    # getting the settings local to this view/tab\n    viewSettings = view.settings()\n    # saving the original settings for \"auto_indent\", or True if none set\n    autoIndent = viewSettings.get('auto_indent', True)\n    # turn off automatic indenting otherwise the tabbing of the original\n    # string is not respected after a newline is encountered\n    viewSettings.set('auto_indent', False)\n    view.run_command('insert', {'characters': content})\n    # restore \"auto_indent\" setting\n    viewSettings.set('auto_indent', autoIndent)\n\n\ndef getOutputPlace(syntax=None, name=\"SQLTools Result\"):\n    showResultOnWindow = settingsStore.get('show_result_on_window', False)\n    if not showResultOnWindow:\n        resultContainer = Window().find_output_panel(name)\n        if resultContainer is None:\n            resultContainer = Window().create_output_panel(name)\n    else:\n        resultContainer = None\n        views = Window().views()\n        for view in views:\n            if view.name() == name:\n                resultContainer = view\n                break\n        if not resultContainer:\n            resultContainer = Window().new_file()\n            resultContainer.set_name(name)\n\n    resultContainer.set_scratch(True)  # avoids prompting to save\n    resultContainer.set_read_only(True)\n    resultContainer.settings().set(\"word_wrap\", \"false\")\n\n    def onInitialOutputCallback():\n        if settingsStore.get('clear_output', False):\n            resultContainer.set_read_only(False)\n            resultContainer.run_command('select_all')\n            resultContainer.run_command('left_delete')\n            resultContainer.set_read_only(True)\n\n        # set custom syntax highlight, only if one was passed explicitly,\n        # otherwise use Plain Text syntax\n        if syntax:\n            # if custom and SQL related, use that, otherwise defaults to SQL\n            if 'sql' in syntax.lower():\n                resultContainer.set_syntax_file(syntax)\n            else:\n                resultContainer.set_syntax_file(SYNTAX_SQL)\n        else:\n            resultContainer.set_syntax_file(SYNTAX_PLAIN_TEXT)\n\n        # hide previously set command running message (if any)\n        Window().status_message('')\n\n        if not showResultOnWindow:\n            # if case this is an output pannel, show it\n            Window().run_command(\"show_panel\", {\"panel\": \"output.\" + name})\n\n        if settingsStore.get('focus_on_result', False):\n            Window().focus_view(resultContainer)\n\n    return resultContainer, onInitialOutputCallback\n\n\ndef getSelectionText():\n    text = []\n\n    selectionRegions = getSelectionRegions()\n\n    if not selectionRegions:\n        return text\n\n    for region in selectionRegions:\n        text.append(View().substr(region))\n\n    return text\n\n\ndef getSelectionRegions():\n    expandedRegions = []\n\n    if not View().sel():\n        return None\n\n    # If we would need to expand the empty selection, then which type:\n    #   'file', 'view' = use text of current view\n    #   'paragraph' =  paragraph(s) (text between newlines)\n    #   'line' = current line(s)\n    expandTo = settingsStore.get('expand_to', 'file')\n    if not expandTo:\n        expandTo = 'file'\n\n    # keep compatibility with previous settings\n    expandToParagraph = settingsStore.get('expand_to_paragraph')\n    if expandToParagraph is True:\n        expandTo = 'paragraph'\n\n    expandTo = str(expandTo).strip()\n    if expandTo not in ['file', 'view', 'paragraph', 'line']:\n        expandTo = 'file'\n\n    for region in View().sel():\n        # if user did not select anything - expand selection,\n        # otherwise use the currently selected region\n        if region.empty():\n            if expandTo in ['file', 'view']:\n                region = sublime.Region(0, View().size())\n                # no point in further iterating over selections, just use entire file\n                return [region]\n            elif expandTo == 'paragraph':\n                region = expand_to_paragraph(View(), region.b)\n            else:\n                # expand to line\n                region = View().line(region)\n\n        # even if we could not expand, avoid adding empty regions\n        if not region.empty():\n            expandedRegions.append(region)\n\n    return expandedRegions\n\n\ndef getCurrentSyntax():\n    view = View()\n    currentSyntax = None\n    if view:\n        currentSyntax = view.settings().get('syntax')\n    return currentSyntax\n\n\nclass ST(EventListener):\n    connectionDict   = None\n    conn             = None\n    tables           = []\n    columns          = []\n    functions        = []\n    completion       = None\n\n    @staticmethod\n    def bootstrap():\n        ST.connectionDict = readConnections()\n        ST.setDefaultConnection()\n\n    @staticmethod\n    def setDefaultConnection():\n        default = getDefaultConnectionName()\n        if not default:\n            return\n        if default not in ST.connectionDict:\n            logger.error('connection \"%s\" set as default, but it does not exists', default)\n            return\n        logger.info('default connection is set to \"%s\"', default)\n        ST.setConnection(default)\n\n    @staticmethod\n    def setConnection(connectionName, callback=None):\n        if not connectionName:\n            return\n\n        if connectionName not in ST.connectionDict:\n            return\n\n        settings = settingsStore.all()\n        config = ST.connectionDict.get(connectionName)\n\n        promptKeys = [key for key, value in config.items() if value is None]\n        promptDict = {}\n        logger.info('[setConnection] prompt keys {}'.format(promptKeys))\n\n        def mergeConfig(config, promptedKeys=None):\n            merged = config.copy()\n            if promptedKeys:\n                merged.update(promptedKeys)\n            return merged\n\n        def createConnection(connectionName, config, settings, callback=None):\n            # if DB cli binary could not be found in path a FileNotFoundError is thrown\n            try:\n                ST.conn = Connection(connectionName, config, settings=settings)\n            except FileNotFoundError as e:\n                # use only first line of the Exception in status message\n                Window().status_message(__package__ + \": \" + str(e).splitlines()[0])\n                raise e\n            ST.loadConnectionData(callback)\n\n        if not promptKeys:\n            createConnection(connectionName, config, settings, callback)\n            return\n\n\n        def setMissingKey(key, value):\n            nonlocal promptDict\n            if value is None:\n                return\n            promptDict[key] = value\n            if promptKeys:\n                promptNext()\n            else:\n                merged = mergeConfig(config, promptDict)\n                createConnection(connectionName, merged, settings, callback)\n\n        def promptNext():\n            nonlocal promptKeys\n            if not promptKeys:\n                merged = mergeConfig(config, promptDict)\n                createConnection(connectionName, merged, settings, callback)\n            key = promptKeys.pop();\n            Window().show_input_panel(\n                    'Connection ' + key,\n                    '',\n                    lambda userInput: setMissingKey(key, userInput),\n                    None,\n                    None)\n\n        promptNext()\n\n    @staticmethod\n    def loadConnectionData(callback=None):\n        # clear the list of identifiers (in case connection is changed)\n        ST.tables = []\n        ST.columns = []\n        ST.functions = []\n        ST.completion = None\n        objectsLoaded = 0\n\n        if not ST.conn:\n            return\n\n        def afterAllDataHasLoaded():\n            ST.completion = Completion(ST.tables, ST.columns, ST.functions, settings=settingsStore)\n            logger.info('completions loaded')\n            if (callback):\n                callback()\n\n        def tablesCallback(tables):\n            ST.tables = tables\n            nonlocal objectsLoaded\n            objectsLoaded += 1\n            logger.info('loaded tables : \"{0}\"'.format(tables))\n            if objectsLoaded == 3:\n                afterAllDataHasLoaded()\n\n        def columnsCallback(columns):\n            ST.columns = columns\n            nonlocal objectsLoaded\n            objectsLoaded += 1\n            logger.info('loaded columns : \"{0}\"'.format(columns))\n            if objectsLoaded == 3:\n                afterAllDataHasLoaded()\n\n        def functionsCallback(functions):\n            ST.functions = functions\n            nonlocal objectsLoaded\n            objectsLoaded += 1\n            logger.info('loaded functions: \"{0}\"'.format(functions))\n            if objectsLoaded == 3:\n                logger.info('all objects loaded')\n                afterAllDataHasLoaded()\n\n        ST.conn.getTables(tablesCallback)\n        ST.conn.getColumns(columnsCallback)\n        ST.conn.getFunctions(functionsCallback)\n\n    @staticmethod\n    def selectConnectionQuickPanel(callback=None):\n        ST.connectionDict = readConnections()\n        if len(ST.connectionDict) == 0:\n            sublime.message_dialog('You need to setup your connections first.')\n            return\n\n        def connectionMenuList(connDictionary):\n            menuItemsList = []\n            template = '{dbtype}://{user}{host}{port}{db}'\n            for name, config in ST.connectionDict.items():\n                dbtype = config.get('type', '')\n                user = '{}@'.format(config.get('username', '')) if 'username' in config else ''\n                # user = config.get('username', '')\n                host=config.get('host', '')\n                port = ':{}'.format(config.get('port', '')) if 'port' in config else ''\n                db = '/{}'.format(config.get('database', '')) if 'database' in config else ''\n                connectionInfo = template.format(\n                    dbtype=dbtype,\n                    user=user,\n                    host=host,\n                    port=port,\n                    db=db)\n                menuItemsList.append([name, connectionInfo])\n                menuItemsList.sort()\n            return menuItemsList\n\n        def onConnectionSelected(index, callback):\n            menuItemsList = connectionMenuList(ST.connectionDict)\n            if index < 0 or index >= len(menuItemsList):\n                return\n            connectionName = menuItemsList[index][0]\n            ST.setConnection(connectionName, callback)\n            logger.info('Connection \"{0}\" selected'.format(connectionName))\n\n        menu = connectionMenuList(ST.connectionDict)\n        # show pannel with callback above\n        Window().show_quick_panel(menu, lambda index: onConnectionSelected(index, callback))\n\n    @staticmethod\n    def showTablesQuickPanel(callback):\n        if len(ST.tables) == 0:\n            sublime.message_dialog('Your database has no tables.')\n            return\n\n        ST.showQuickPanelWithSelection(ST.tables, callback)\n\n    @staticmethod\n    def showFunctionsQuickPanel(callback):\n        if len(ST.functions) == 0:\n            sublime.message_dialog('Your database has no functions.')\n            return\n\n        ST.showQuickPanelWithSelection(ST.functions, callback)\n\n    @staticmethod\n    def showQuickPanelWithSelection(arrayOfValues, callback):\n        w = Window();\n        view = w.active_view()\n        selection = view.sel()[0]\n\n        initialText = ''\n        # ignore obvious non-identifier selections\n        if selection.size() <= 128:\n            (row_begin,_) = view.rowcol(selection.begin())\n            (row_end,_) = view.rowcol(selection.end())\n            # only consider selections within same line\n            if row_begin == row_end:\n                initialText = view.substr(selection)\n\n        w.show_quick_panel(arrayOfValues, callback)\n        w.run_command('insert', {'characters': initialText})\n        w.run_command(\"select_all\")\n\n    @staticmethod\n    def on_query_completions(view, prefix, locations):\n        # skip completions, if no connection\n        if ST.conn is None:\n            return None\n\n        if ST.completion is None:\n            return None\n\n        if ST.completion.isDisabled():\n            return None\n\n        if not len(locations):\n            return None\n\n        ignoreSelectors = ST.completion.getIgnoreSelectors()\n        if ignoreSelectors:\n            for selector in ignoreSelectors:\n                if view.match_selector(locations[0], selector):\n                    return None\n\n        activeSelectors = ST.completion.getActiveSelectors()\n        if activeSelectors:\n            for selector in activeSelectors:\n                if view.match_selector(locations[0], selector):\n                    break\n            else:\n                return None\n\n        # sublimePrefix = prefix\n        # sublimeCompletions = view.extract_completions(sublimePrefix, locations[0])\n\n        # preferably get prefix ourselves instead of using default sublime \"prefix\".\n        # Sublime will return only last portion of this preceding text. Given:\n        # SELECT table.col|\n        # sublime will return: \"col\", and we need: \"table.col\"\n        # to know more precisely which completions are more appropriate\n\n        # get a Region that starts at the beginning of current line\n        # and ends at current cursor position\n        currentPoint = locations[0]\n        lineStartPoint = view.line(currentPoint).begin()\n        lineStartToLocation = sublime.Region(lineStartPoint, currentPoint)\n        try:\n            lineStr = view.substr(lineStartToLocation)\n            prefix = re.split('[^`\\\"\\w.\\$]+', lineStr).pop()\n        except Exception as e:\n            logger.debug(e)\n\n        # use current paragraph as sql text to parse\n        sqlRegion = expand_to_paragraph(view, currentPoint)\n        sql = view.substr(sqlRegion)\n        sqlToCursorRegion = sublime.Region(sqlRegion.begin(), currentPoint)\n        sqlToCursor = view.substr(sqlToCursorRegion)\n\n        # get completions\n        autoCompleteList, inhibit = ST.completion.getAutoCompleteList(prefix, sql, sqlToCursor)\n\n        # safe check here, so even if we return empty completions and inhibit is true\n        # we return empty completions to show default sublime completions\n        if autoCompleteList is None or len(autoCompleteList) == 0:\n            return None\n\n        if inhibit:\n            return (autoCompleteList, sublime.INHIBIT_WORD_COMPLETIONS)\n\n        return autoCompleteList\n\n\n# #\n# # Commands\n# #\n\n\n# Usage for old keybindings defined by users\nclass StShowConnectionMenu(WindowCommand):\n    @staticmethod\n    def run():\n        Window().run_command('st_select_connection')\n\n\nclass StSelectConnection(WindowCommand):\n    @staticmethod\n    def run():\n        ST.selectConnectionQuickPanel()\n\n\nclass StShowRecords(WindowCommand):\n    @staticmethod\n    def run():\n        if not ST.conn:\n            ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_show_records'))\n            return\n\n        def onTableSelected(index):\n            if index < 0:\n                return None\n            Window().status_message(MESSAGE_RUNNING_CMD)\n            tableName = ST.tables[index]\n            prependText = 'Table \"{tableName}\"\\n'.format(tableName=tableName)\n            return ST.conn.getTableRecords(\n                tableName,\n                createOutput(prependText=prependText))\n\n        ST.showTablesQuickPanel(callback=onTableSelected)\n\n\nclass StDescTable(WindowCommand):\n    @staticmethod\n    def run():\n        currentSyntax = getCurrentSyntax()\n\n        if not ST.conn:\n            ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_desc_table'))\n            return\n\n        def onTableSelected(index):\n            if index < 0:\n                return None\n            Window().status_message(MESSAGE_RUNNING_CMD)\n            return ST.conn.getTableDescription(ST.tables[index], createOutput(syntax=currentSyntax))\n\n        ST.showTablesQuickPanel(callback=onTableSelected)\n\n\nclass StDescFunction(WindowCommand):\n    @staticmethod\n    def run():\n        currentSyntax = getCurrentSyntax()\n\n        if not ST.conn:\n            ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_desc_function'))\n            return\n\n        def onFunctionSelected(index):\n            if index < 0:\n                return None\n            Window().status_message(MESSAGE_RUNNING_CMD)\n            functionName = ST.functions[index].split('(', 1)[0]\n            return ST.conn.getFunctionDescription(functionName, createOutput(syntax=currentSyntax))\n\n        # get everything until first occurrence of \"(\", e.g. get \"function_name\"\n        # from \"function_name(int)\"\n        ST.showFunctionsQuickPanel(callback=onFunctionSelected)\n\n\nclass StRefreshConnectionData(WindowCommand):\n    @staticmethod\n    def run():\n        if not ST.conn:\n            return\n        ST.loadConnectionData()\n\n\nclass StExplainPlan(WindowCommand):\n    @staticmethod\n    def run():\n        if not ST.conn:\n            ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_explain_plan'))\n            return\n\n        Window().status_message(MESSAGE_RUNNING_CMD)\n        ST.conn.explainPlan(getSelectionText(), createOutput())\n\n\nclass StExecute(WindowCommand):\n    @staticmethod\n    def run():\n        if not ST.conn:\n            ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_execute'))\n            return\n\n        Window().status_message(MESSAGE_RUNNING_CMD)\n        ST.conn.execute(getSelectionText(), createOutput())\n\n\nclass StExecuteAll(WindowCommand):\n    @staticmethod\n    def run():\n        if not ST.conn:\n            ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_execute_all'))\n            return\n\n        Window().status_message(MESSAGE_RUNNING_CMD)\n        allText = View().substr(sublime.Region(0, View().size()))\n        ST.conn.execute(allText, createOutput())\n\n\nclass StFormat(TextCommand):\n    @staticmethod\n    def run(edit):\n        selectionRegions = getSelectionRegions()\n\n        if not selectionRegions:\n            return\n\n        for region in selectionRegions:\n            textToFormat = View().substr(region)\n            View().replace(edit, region, Utils.formatSql(textToFormat, settingsStore.get('format', {})))\n\n\nclass StFormatAll(TextCommand):\n    @staticmethod\n    def run(edit):\n        region = sublime.Region(0, View().size())\n        textToFormat = View().substr(region)\n        View().replace(edit, region, Utils.formatSql(textToFormat, settingsStore.get('format', {})))\n\n\nclass StVersion(WindowCommand):\n    @staticmethod\n    def run():\n        sublime.message_dialog('Using {0} {1}'.format(__package__, __version__))\n\n\nclass StHistory(WindowCommand):\n    @staticmethod\n    def run():\n        if not ST.conn:\n            ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_history'))\n            return\n\n        if len(historyStore.all()) == 0:\n            sublime.message_dialog('History is empty.')\n            return\n\n        def cb(index):\n            if index < 0:\n                return None\n            return ST.conn.execute(historyStore.get(index), createOutput())\n\n        Window().show_quick_panel(historyStore.all(), cb)\n\n\nclass StSaveQuery(WindowCommand):\n    @staticmethod\n    def run():\n        query = getSelectionText()\n\n        def cb(alias):\n            queriesStore.add(alias, query)\n        Window().show_input_panel('Query alias', '', cb, None, None)\n\n\nclass StListQueries(WindowCommand):\n    @staticmethod\n    def run(mode=\"run\"):\n        if mode == \"run\" and not ST.conn:\n            ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_list_queries',\n                                                                               {'mode': mode}))\n            return\n\n        queriesList = queriesStore.all()\n        if len(queriesList) == 0:\n            sublime.message_dialog('No saved queries.')\n            return\n\n        options = []\n        for alias, query in queriesList.items():\n            options.append([str(alias), str(query)])\n        options.sort()\n\n        def cb(index):\n            if index < 0:\n                return None\n\n            alias, query = options[index]\n            if mode == \"run\":\n                ST.conn.execute(query, createOutput())\n            elif mode == \"insert\":\n                insertContent(query)\n            else:\n                toNewTab(query, alias)\n\n            return\n\n        try:\n            Window().show_quick_panel(options, cb)\n        except Exception:\n            pass\n\n\nclass StRemoveSavedQuery(WindowCommand):\n    @staticmethod\n    def run():\n        if not ST.conn:\n            ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_remove_saved_query'))\n            return\n\n        queriesList = queriesStore.all()\n        if len(queriesList) == 0:\n            sublime.message_dialog('No saved queries.')\n            return\n\n        options = []\n        for alias, query in queriesList.items():\n            options.append([str(alias), str(query)])\n        options.sort()\n\n        def cb(index):\n            if index < 0:\n                return None\n\n            return queriesStore.delete(options[index][0])\n        try:\n            Window().show_quick_panel(options, cb)\n        except Exception:\n            pass\n\n\ndef Window():\n    return sublime.active_window()\n\n\ndef View():\n    return Window().active_view()\n\n\ndef reload():\n    try:\n        # python 3.0 to 3.3\n        import imp\n        imp.reload(sys.modules[__package__ + \".SQLToolsAPI\"])\n        imp.reload(sys.modules[__package__ + \".SQLToolsAPI.Utils\"])\n        imp.reload(sys.modules[__package__ + \".SQLToolsAPI.Completion\"])\n        imp.reload(sys.modules[__package__ + \".SQLToolsAPI.Storage\"])\n        imp.reload(sys.modules[__package__ + \".SQLToolsAPI.History\"])\n        imp.reload(sys.modules[__package__ + \".SQLToolsAPI.Command\"])\n        imp.reload(sys.modules[__package__ + \".SQLToolsAPI.Connection\"])\n    except Exception as e:\n        raise (e)\n\n    try:\n        ST.bootstrap()\n    except Exception:\n        pass\n\n\ndef plugin_loaded():\n\n    try:\n        from package_control import events\n\n        if events.install(__name__):\n            logger.info('Installed %s!' % events.install(__name__))\n        elif events.post_upgrade(__name__):\n            logger.info('Upgraded to %s!' % events.post_upgrade(__name__))\n            sublime.message_dialog(('{0} was upgraded.' +\n                                    'If you have any problem,' +\n                                    'just restart your Sublime Text.'\n                                    ).format(__name__)\n                                   )\n\n    except Exception:\n        pass\n\n    startPlugin()\n    reload()\n\n\ndef plugin_unloaded():\n    if plugin_logger.handlers:\n        plugin_logger.handlers.pop()\n"
  },
  {
    "path": "SQLTools.sublime-settings",
    "content": "// NOTE: it is strongly advised to override ONLY those settings\n// that you wish to change in your Users/SQLTools.sublime-settings.\n// Don't copy-paste the entire config.\n{\n    /**\n     * If DB cli binary is not in PATH, set the full path in \"cli\" section.\n     * Note: forward slashes (\"/\") should be used in path. Example:\n     *  \"mysql\"   : \"c:/Program Files/MySQL/MySQL Server 5.7/bin/mysql.exe\"\n     */\n    \"cli\": {\n        \"mysql\"   : \"mysql\",\n        \"pgsql\"   : \"psql\",\n        \"mssql\"   : \"sqlcmd\",\n        \"oracle\"  : \"sqlplus\",\n        \"sqlite\"  : \"sqlite3\",\n        \"vertica\" : \"vsql\",\n        \"firebird\": \"isql\",\n        \"sqsh\"    : \"sqsh\",\n        \"snowsql\" : \"snowsql\"\n    },\n\n    // If there is no SQL selected, use \"expanded\" region.\n    // Possible options:\n    //  \"file\"      - entire file contents\n    //  \"paragraph\" - text between newlines relative to cursor(s)\n    //  \"line\"      - current line of cursor(s)\n    \"expand_to\": \"file\",\n\n    // puts results either in output panel or new window\n    \"show_result_on_window\": false,\n\n    // focus on result panel\n    \"focus_on_result\": false,\n\n    // clears the output of previous query\n    \"clear_output\": true,\n\n    // query timeout in seconds\n    \"thread_timeout\": 15,\n\n    // stream the output line by line\n    \"use_streams\": false,\n\n    // number of queries to save in the history\n    \"history_size\": 100,\n\n    \"show_records\": {\n        \"limit\": 50\n    },\n\n    // unless false, appends LIMIT clause to SELECT statements (not compatible with all DB's)\n    \"safe_limit\": false,\n\n    \"debug\": false,\n\n    /**\n     * Print the queries that were executed to the output.\n     * Possible values for show_query: \"top\", \"bottom\", true (\"top\"), or false (disable)\n     * When using regular output, this will determine where query details is displayed.\n     * In stream output mode, any option that isn't false will print query details at\n     * the bottom of result.\n     */\n    \"show_query\": false,\n\n    /**\n     * Possible values for autocompletion: \"basic\", \"smart\", true (\"smart\"),\n     *                                      or false (disable)\n     * Completion keywords case is controlled by format.keyword_case (see below)\n     */\n    \"autocompletion\": \"smart\",\n\n    // Settings used for formatting the queries and autocompletions\n    //\n    // \"keyword_case\"   , \"upper\", \"lower\", \"capitalize\" and null (leaves case intact)\n    // \"identifier_case\", \"upper\", \"lower\", \"capitalize\" and null (leaves case intact)\n    // \"strip_comments\" , formatting removes comments\n    // \"indent_tabs\"    , use tabs instead of spaces\n    // \"indent_width\"   , indentation width\n    // \"reindent\"       , reindent code\n    \"format\": {\n        \"keyword_case\"    : \"upper\",\n        \"identifier_case\" : null,\n        \"strip_comments\"  : false,\n        \"indent_tabs\"     : false,\n        \"indent_width\"    : 4,\n        \"reindent\"        : true\n    },\n\n    /**\n     * The list of syntax selectors for which the autocompletion will be active.\n     * An empty list means autocompletion always active.\n     */\n    \"autocomplete_selectors_active\": [\n        \"source.sql\",\n        \"source.pgsql\",\n        \"source.plpgsql.postgres\",\n        \"source.plsql.oracle\",\n        \"source.tsql\"\n    ],\n\n    /**\n     * The list of syntax selectors for which the autocompletion will be disabled.\n     */\n    \"autocomplete_selectors_ignore\": [\n        \"string.quoted.single.sql\",\n        \"string.quoted.single.pgsql\",\n        \"string.quoted.single.postgres\",\n        \"string.quoted.single.oracle\",\n        \"string.group.quote.oracle\"\n    ],\n\n    /**\n     * Command line interface options for each RDBMS.\n     * In this file, the section `cli` above has the names you can use here.\n     * E.g.: \"mysql\", \"pgsql\", \"oracle\"\n     *\n     * Names in the curly brackets (e.g. `{host}`) in sections `args`, `args_optional`,\n     * `env`, `env_optional` are replaced by the values specified in the connection.\n     */\n    \"cli_options\": {\n        \"pgsql\": {\n            \"options\": [\"--no-password\"],\n            \"before\": [],\n            \"after\": [],\n            \"args\": \"-d {database}\",\n            \"args_optional\": [\n                \"-h {host}\",\n                \"-p {port}\",\n                \"-U {username}\"\n            ],\n            \"env_optional\": {\n                \"PGPASSWORD\": \"{password}\"\n            },\n            \"queries\": {\n                \"execute\": {\n                    \"options\": []\n                },\n                \"show records\": {\n                    \"query\": \"select * from {0} limit {1};\",\n                    \"options\": []\n                },\n                \"desc table\": {\n                    \"query\": \"\\\\d+ {0}\",\n                    \"options\": []\n                },\n                \"desc function\": {\n                    \"query\": \"\\\\sf {0}\",\n                    \"options\": []\n                },\n                \"explain plan\": {\n                    \"query\": \"explain analyze {0};\",\n                    \"options\": []\n                },\n                \"desc\": {\n                    \"query\": \"select quote_ident(table_schema) || '.' || quote_ident(table_name) as tblname from information_schema.tables where table_schema not in ('pg_catalog', 'information_schema') order by table_schema = current_schema() desc, table_schema, table_name;\",\n                    \"options\": [\"--tuples-only\", \"--no-psqlrc\"]\n                },\n                \"columns\": {\n                    \"query\": \"select distinct quote_ident(table_name) || '.' || quote_ident(column_name) from information_schema.columns where table_schema not in ('pg_catalog', 'information_schema');\",\n                    \"options\": [\"--tuples-only\", \"--no-psqlrc\"]\n                },\n                \"functions\": {\n                    \"query\": \"select quote_ident(n.nspname) || '.' || quote_ident(f.proname) || '(' || pg_get_function_identity_arguments(f.oid) || ')' as funname from pg_catalog.pg_proc as f inner join pg_catalog.pg_namespace as n on n.oid = f.pronamespace where n.nspname not in ('pg_catalog', 'information_schema');\",\n                    \"options\": [\"--tuples-only\", \"--no-psqlrc\"]\n                }\n            }\n        },\n\n        \"mysql\": {\n            \"options\": [\"--no-auto-rehash\", \"--compress\"],\n            \"before\": [],\n            \"after\": [],\n            \"args\": \"-D\\\"{database}\\\"\",\n            \"args_optional\": [\n                \"--login-path=\\\"{login-path}\\\"\",\n                \"--defaults-extra-file=\\\"{defaults-extra-file}\\\"\",\n                \"--default-character-set=\\\"{default-character-set}\\\"\",\n                \"-h\\\"{host}\\\"\",\n                \"-P{port}\",\n                \"-u\\\"{username}\\\"\"\n            ],\n            \"env_optional\": {\n                \"MYSQL_PWD\": \"{password}\"\n            },\n            \"queries\": {\n                \"execute\": {\n                    \"options\": [\"--table\"]\n                },\n                \"show records\": {\n                    \"query\": \"select * from {0} limit {1};\",\n                    \"options\": [\"--table\"]\n                },\n                \"desc table\": {\n                    \"query\": \"desc {0};\",\n                    \"options\": [\"--table\"]\n                },\n                \"desc function\": {\n                    \"query\": \"select routine_definition from information_schema.routines where concat(case when routine_schema REGEXP '[^0-9a-zA-Z$_]' then concat('`',routine_schema,'`') else routine_schema end, '.', case when routine_name REGEXP '[^0-9a-zA-Z$_]' then concat('`',routine_name,'`') else routine_name end) = '{0}';\",\n                    \"options\": [\"--silent\", \"--raw\"]\n                },\n                \"explain plan\": {\n                    \"query\": \"explain {0};\",\n                    \"options\": [\"--table\"]\n                },\n                \"desc\" : {\n                    \"query\": \"select concat(case when table_schema REGEXP '[^0-9a-zA-Z$_]' then concat('`',table_schema,'`') else table_schema end, '.', case when table_name REGEXP '[^0-9a-zA-Z$_]' then concat('`',table_name,'`') else table_name end) as obj from information_schema.tables where table_schema = database() order by table_name;\",\n                    \"options\": [\"--silent\", \"--raw\", \"--skip-column-names\"]\n                },\n                \"columns\": {\n                    \"query\": \"select concat(case when table_name REGEXP '[^0-9a-zA-Z$_]' then concat('`',table_name,'`') else table_name end, '.', case when column_name REGEXP '[^0-9a-zA-Z$_]' then concat('`',column_name,'`') else column_name end) as obj from information_schema.columns where table_schema = database() order by table_name, ordinal_position;\",\n                    \"options\": [\"--silent\", \"--raw\", \"--skip-column-names\"]\n                },\n                \"functions\": {\n                    \"query\": \"select concat(case when routine_schema REGEXP '[^0-9a-zA-Z$_]' then concat('`',routine_schema,'`') else routine_schema end, '.', case when routine_name REGEXP '[^0-9a-zA-Z$_]' then concat('`',routine_name,'`') else routine_name end, '()') as obj from information_schema.routines where routine_schema = database();\",\n                    \"options\": [\"--silent\", \"--raw\", \"--skip-column-names\"]\n                }\n            }\n        },\n\n        \"mssql\": {\n            \"options\": [],\n            \"before\": [],\n            \"after\": [\"go\", \"quit\"],\n            \"args\": \"-d \\\"{database}\\\"\",\n            \"args_optional\": [\"-S \\\"{host},{port}\\\"\", \"-S \\\"{host}\\\\{instance}\\\"\", \"-U \\\"{username}\\\"\", \"-P \\\"{password}\\\"\"],\n            \"queries\": {\n                \"execute\": {\n                    \"options\": [\"-k\"]\n                },\n                \"show records\": {\n                    \"query\": \"select top {1} * from {0};\",\n                    \"options\": []\n                },\n                \"desc table\": {\n                    \"query\": \"exec sp_help N'{0}';\",\n                    \"options\": [\"-y30\", \"-Y30\"]\n                },\n                \"desc function\": {\n                    \"query\": \"exec sp_helptext N'{0}';\",\n                    \"options\": [\"-h-1\"]\n                },\n                \"explain plan\": {\n                    \"query\": \"{0};\",\n                    \"options\": [\"-k\"],\n                    \"before\": [\n                        \"SET STATISTICS PROFILE ON\",\n                        \"SET STATISTICS IO ON\",\n                        \"SET STATISTICS TIME ON\"\n                    ]\n                },\n                \"desc\": {\n                    \"query\": \"set nocount on; select concat(table_schema, '.', table_name) as obj from information_schema.tables order by table_schema, table_name;\",\n                    \"options\": [\"-h-1\", \"-r1\"]\n                },\n                \"columns\": {\n                    \"query\": \"set nocount on; select distinct concat(table_name, '.', column_name) as obj from information_schema.columns;\",\n                    \"options\": [\"-h-1\", \"-r1\"]\n                },\n                \"functions\": {\n                    \"query\": \"set nocount on; select concat(routine_schema, '.', routine_name) as obj from information_schema.routines order by routine_schema, routine_name;\",\n                    \"options\": [\"-h-1\", \"-r1\"]\n                }\n            }\n        },\n\n        \"oracle\": {\n            \"options\": [\"-S\"],\n            \"before\": [\n                \"SET LINESIZE   32767\",\n                \"SET WRAP       OFF\",\n                \"SET PAGESIZE   0\",\n                \"SET EMBEDDED   ON\",\n                \"SET TRIMOUT    ON\",\n                \"SET TRIMSPOOL  ON\",\n                \"SET TAB        OFF\",\n                \"SET SERVEROUT  ON\",\n                \"SET NULL       '@'\",\n                \"SET COLSEP     '|'\",\n                \"SET SQLBLANKLINES ON\"\n            ],\n            \"after\": [],\n            \"env_optional\": {\n                \"NLS_LANG\": \"{nls_lang}\"\n            },\n            \"args\": \"{username}/{password}@\\\"(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST={host})(PORT={port})))(CONNECT_DATA=(SERVICE_NAME={service})))\\\"\",\n            \"queries\": {\n                \"execute\": {\n                    \"options\": [],\n                    \"before\": [\n                        // \"SET TIMING     ON\",\n                        \"SET FEEDBACK   ON\"\n                    ]\n                },\n                \"show records\": {\n                    \"query\": \"select * from {0} where rownum <= {1};\",\n                    \"options\": [],\n                    \"before\": [\n                        \"SET FEEDBACK   ON\"\n                    ]\n                },\n                \"desc table\": {\n                    \"query\": \"desc {0};\",\n                    \"options\": [],\n                    \"before\": [\n                        \"SET LINESIZE   80\",  // override for readability\n                        \"SET WRAP       ON\",  // override for readability\n                        \"SET FEEDBACK   ON\"\n                    ]\n                },\n                \"desc function\": {\n                    \"query\": \"select text from all_source where type in ('FUNCTION', 'PROCEDURE', 'PACKAGE', 'PACKAGE BODY') and name = nvl(substr(ltrim('{0}', sys_context('USERENV', 'CURRENT_SCHEMA') || '.' ), 0, instr(ltrim('{0}', sys_context('USERENV', 'CURRENT_SCHEMA') || '.' ), '.')-1), ltrim('{0}', sys_context('USERENV', 'CURRENT_SCHEMA') || '.' )) and owner = sys_context('USERENV', 'CURRENT_SCHEMA') order by type, line;\",\n                    \"options\": [],\n                    \"before\": [\n                        \"SET SERVEROUT  OFF\",  // override\n                        \"SET NULL       ''\",   // override\n                        \"SET HEADING    OFF\",\n                        \"SET FEEDBACK   OFF\"\n                    ]\n                },\n                \"explain plan\": {\n                    \"query\": \"explain plan for {0};\\nselect plan_table_output from table(dbms_xplan.display());\",\n                    \"options\": [],\n                    \"before\": [\n                        \"SET FEEDBACK   ON\"\n                    ]\n                },\n                \"desc\" : {\n                    \"query\": \"select owner || '.' || case when upper(name) = name then name else chr(34) || name || chr(34) end as obj from (select owner, table_name as name from all_tables union all select owner, view_name as name from all_views) o where owner not in ('ANONYMOUS','APPQOSSYS','CTXSYS','DBSNMP','EXFSYS', 'LBACSYS', 'MDSYS','MGMT_VIEW','OLAPSYS','OWBSYS','ORDPLUGINS', 'ORDSYS','OUTLN', 'SI_INFORMTN_SCHEMA','SYS','SYSMAN','SYSTEM', 'TSMSYS','WK_TEST','WKSYS', 'WKPROXY','WMSYS','XDB','APEX_040000', 'APEX_PUBLIC_USER','DIP', 'FLOWS_30000','FLOWS_FILES','MDDATA', 'ORACLE_OCM','SPATIAL_CSW_ADMIN_USR', 'SPATIAL_WFS_ADMIN_USR', 'XS$NULL','PUBLIC');\",\n                    \"options\": [],\n                    \"before\": [\n                        \"SET SERVEROUT  OFF\",  // override\n                        \"SET NULL       ''\",   // override\n                        \"SET HEADING    OFF\",\n                        \"SET FEEDBACK   OFF\"\n                    ]\n                },\n                \"columns\": {\n                    \"query\": \"select case when upper(table_name) = table_name then table_name else chr(34) || table_name || chr(34) end || '.' || case when upper(column_name) = column_name then column_name else chr(34) || column_name || chr(34) end as obj from (select c.table_name, c.column_name, t.owner from all_tab_columns c inner join all_tables t on c.owner = t.owner and c.table_name = t.table_name union all select c.table_name, c.column_name, t.owner from all_tab_columns c inner join all_views t on c.owner = t.owner and c.table_name = t.view_name) o where owner not in ('ANONYMOUS','APPQOSSYS','CTXSYS','DBSNMP','EXFSYS', 'LBACSYS', 'MDSYS','MGMT_VIEW','OLAPSYS','OWBSYS','ORDPLUGINS', 'ORDSYS','OUTLN', 'SI_INFORMTN_SCHEMA','SYS','SYSMAN','SYSTEM', 'TSMSYS','WK_TEST','WKSYS', 'WKPROXY','WMSYS','XDB','APEX_040000', 'APEX_PUBLIC_USER','DIP', 'FLOWS_30000','FLOWS_FILES','MDDATA', 'ORACLE_OCM','SPATIAL_CSW_ADMIN_USR', 'SPATIAL_WFS_ADMIN_USR', 'XS$NULL','PUBLIC');\",\n                    \"options\": [],\n                    \"before\": [\n                        \"SET SERVEROUT  OFF\",  // override\n                        \"SET NULL       ''\",   // override\n                        \"SET HEADING    OFF\",\n                        \"SET FEEDBACK   OFF\"\n                    ]\n                },\n                \"functions\": {\n                    \"query\": \"select case when object_type = 'PACKAGE' then object_name||'.'||procedure_name else owner || '.' || object_name end || '()' as obj from all_procedures where object_type in ('FUNCTION','PROCEDURE','PACKAGE') and not (object_type = 'PACKAGE' and procedure_name is null) and owner = sys_context('USERENV', 'CURRENT_SCHEMA');\",\n                    \"options\": [],\n                    \"before\": [\n                        \"SET SERVEROUT  OFF\",  // override\n                        \"SET NULL       ''\",   // override\n                        \"SET HEADING    OFF\",\n                        \"SET FEEDBACK   OFF\"\n                    ]\n                }\n            }\n        },\n\n        \"sqlite\": {\n            \"options\": [],\n            \"before\": [],\n            \"after\": [],\n            \"args\": \"\\\"{database}\\\"\",\n            \"queries\": {\n                \"execute\": {\n                    \"options\": [\"-column\", \"-header\", \"-bail\"]\n                },\n                \"show records\": {\n                    \"query\": \"select * from \\\"{0}\\\" limit {1};\",\n                    \"options\": [\"-column\", \"-header\"]\n                },\n                \"explain plan\": {\n                    \"query\": \"EXPLAIN QUERY PLAN {0};\",\n                    \"options\": [\"-column\", \"-header\", \"-bail\"]\n                },\n                \"desc table\": {\n                    \"query\": \".schema \\\"{0}\\\"\",\n                    \"options\": [\"-column\", \"-header\"]\n                },\n                \"desc\" : {\n                    \"query\": \"SELECT name FROM sqlite_master WHERE type='table';\",\n                    \"options\": [\"-noheader\"],\n                    \"before\": [\n                        \".headers off\"\n                    ]\n                }\n            }\n        },\n\n        \"vertica\": {\n            \"options\": [],\n            \"before\" : [],\n            \"after\": [],\n            \"args\": \"-h \\\"{host}\\\" -p {port} -U \\\"{username}\\\" -w \\\"{password}\\\" -d \\\"{database}\\\"\",\n            \"queries\": {\n                \"execute\": {\n                    \"options\": []\n                },\n                \"show records\": {\n                    \"query\": \"select * from {0} limit {1};\",\n                    \"options\": []\n                },\n                \"desc table\": {\n                    \"query\": \"\\\\d {0}\",\n                    \"options\": []\n                },\n                \"explain plan\": {\n                    \"query\": \"explain {0};\",\n                    \"options\": []\n                },\n                \"desc\" : {\n                    \"query\": \"select quote_ident(table_schema) || '.' || quote_ident(table_name) as obj from v_catalog.tables where is_system_table = false;\",\n                    \"options\": [\"--tuples-only\", \"--no-vsqlrc\"]\n                },\n                \"columns\": {\n                    \"query\": \"select quote_ident(table_name) || '.' || quote_ident(column_name) as obj from v_catalog.columns where is_system_table = false order by table_name, ordinal_position;\",\n                    \"options\": [\"--tuples-only\", \"--no-vsqlrc\"]\n                }\n            }\n        },\n\n        \"firebird\": {\n            \"options\": [],\n            \"before\": [],\n            \"after\": [],\n            \"args\": \"-pagelength 10000 -u \\\"{username}\\\" -p \\\"{password}\\\" \\\"{host}/{port}:{database}\\\"\",\n            \"queries\": {\n                \"execute\": {\n                    \"options\": [],\n                    \"before\": [\n                        \"set bail on;\",\n                        \"set count on;\"\n                    ]\n                },\n                \"show records\": {\n                    \"query\": \"select first {1} * from {0};\",\n                    \"options\": [],\n                    \"before\": [\n                        \"set bail off;\",\n                        \"set count on;\"\n                    ]\n                },\n                \"desc table\": {\n                    \"query\": \"show table {0}; \\n show view {0};\",\n                    \"before\": [\n                        \"set bail off;\"\n                    ]\n                },\n                \"desc function\": {\n                    \"query\": \"show procedure {0};\",\n                    \"before\": [\n                        \"set bail off;\"\n                    ]\n                },\n                \"explain plan\": {\n                    \"query\": \"{0};\",\n                    \"before\": [\n                        \"set bail on;\",\n                        \"set count on;\",\n                        \"set plan on;\",\n                        \"set stats on;\"\n                    ]\n                },\n                \"desc\" : {\n                    \"query\": \"select case when upper(rdb$relation_name) = rdb$relation_name then trim(rdb$relation_name) else '\\\"' || trim(rdb$relation_name) || '\\\"' end as obj from rdb$relations where (rdb$system_flag is null or rdb$system_flag = 0);\",\n                    \"before\": [\n                        \"set bail off;\",\n                        \"set heading off;\",\n                        \"set count off;\",\n                        \"set stats off;\"\n                    ]\n                },\n                \"columns\": {\n                    \"query\": \"select case when upper(f.rdb$relation_name) = f.rdb$relation_name then trim(f.rdb$relation_name) else '\\\"' || trim(f.rdb$relation_name) || '\\\"' end || '.' || case when upper(f.rdb$field_name) = f.rdb$field_name then trim(f.rdb$field_name) else '\\\"' || trim(f.rdb$field_name) || '\\\"' end as obj from rdb$relation_fields f join rdb$relations r on f.rdb$relation_name = r.rdb$relation_name where (r.rdb$system_flag is null or r.rdb$system_flag = 0) order by f.rdb$relation_name, f.rdb$field_position;\",\n                    \"before\": [\n                        \"set bail off;\",\n                        \"set heading off;\",\n                        \"set count off;\",\n                        \"set stats off;\"\n                    ]\n                },\n                \"functions\": {\n                    \"query\": \"select case when upper(rdb$procedure_name) = rdb$procedure_name then trim(rdb$procedure_name) else '\\\"' || trim(rdb$procedure_name) || '\\\"' end || '()' as obj from rdb$procedures where (rdb$system_flag is null or rdb$system_flag = 0);\",\n                    \"before\": [\n                        \"set bail off;\",\n                        \"set heading off;\",\n                        \"set count off;\",\n                        \"set stats off;\"\n                    ]\n                }\n            }\n        },\n\n        \"sqsh\": {\n            \"options\": [],\n            \"before\": [],\n            \"after\": [],\n            \"args\": \"-S {host}:{port} -U\\\"{username}\\\" -P\\\"{password}\\\" -D{database}\",\n            \"queries\": {\n                \"execute\": {\n                    \"options\": [],\n                    \"before\": [\"\\\\set semicolon_cmd=\\\"\\\\go -mpretty -l\\\"\"]\n                },\n                \"desc\": {\n                    \"query\": \"select concat(table_schema, '.', table_name) from information_schema.tables order by table_name;\",\n                    \"options\": [],\n                    \"before\" :[\"\\\\set semicolon_cmd=\\\"\\\\go -mpretty -l -h -f\\\"\"]\n                },\n                \"columns\": {\n                    \"query\": \"select concat(table_name, '.', column_name) from information_schema.columns order by table_name, ordinal_position;\",\n                    \"options\": [],\n                    \"before\" :[\"\\\\set semicolon_cmd=\\\"\\\\go -mpretty -l -h -f\\\"\"]\n                },\n                \"desc table\": {\n                    \"query\": \"exec sp_columns \\\"{0}\\\";\",\n                    \"options\": [],\n                    \"before\": [\"\\\\set semicolon_cmd=\\\"\\\\go -mpretty -l -h -f\\\"\"]\n                },\n                \"show records\": {\n                    \"query\": \"select top {1} * from \\\"{0}\\\";\",\n                    \"options\": [],\n                    \"before\": [\"\\\\set semicolon_cmd=\\\"\\\\go -mpretty -l\\\"\"]\n                }\n            }\n        },\n\n        \"snowsql\": {\n            \"options\": [],\n            \"env_optional\": {\n                \"SNOWSQL_PWD\": \"{password}\"\n            },\n            \"args\": \"-u {user} -a {account} -d {database} --authenticator {auth} -K\",\n            \"queries\": {\n                \"execute\": {\n                    \"options\": [],\n                },\n                \"show records\": {\n                    \"query\": \"SELECT * FROM {0} LIMIT {1};\"\n                },\n                \"desc table\": {\n                    \"query\": \"DESC TABLE {0};\",\n                    \"options\": [\"-o\", \"output_format=plain\", \n                                \"-o\", \"timing=False\"]\n                },\n                \"desc\": {\n                    \"query\": \"SELECT TABLE_SCHEMA || '.' || TABLE_NAME AS tbl FROM INFORMATION_SCHEMA.TABLES ORDER BY tbl;\",\n                    \"options\": [\"-o\", \"output_format=plain\", \n                                \"-o\", \"header=False\", \n                                \"-o\", \"timing=False\"]\n                },\n                \"columns\": {\n                    \"query\": \"SELECT TABLE_NAME || '.' || COLUMN_NAME AS col FROM INFORMATION_SCHEMA.COLUMNS ORDER BY col;\",\n                    \"options\": [\"-o\", \"output_format=plain\", \n                                \"-o\", \"header=False\", \n                                \"-o\", \"timing=False\"]\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "SQLToolsAPI/Command.py",
    "content": "import os\nimport signal\nimport subprocess\nimport time\nimport logging\n\nfrom threading import Thread, Timer\n\nlogger = logging.getLogger(__name__)\n\nclass Command(object):\n    timeout = 15\n\n    def __init__(self, args, env, callback, query=None, encoding='utf-8',\n                 options=None, timeout=15, silenceErrors=False, stream=False):\n        if options is None:\n            options = {}\n\n        self.args = args\n        self.env = env\n        self.callback = callback\n        self.query = query\n        self.encoding = encoding\n        self.options = options\n        self.timeout = timeout\n        self.silenceErrors = silenceErrors\n        self.stream = stream\n        self.process = None\n\n        if 'show_query' not in self.options:\n            self.options['show_query'] = False\n        elif self.options['show_query'] not in ['top', 'bottom']:\n            self.options['show_query'] = 'top' if (isinstance(self.options['show_query'], bool) and\n                                                   self.options['show_query']) else False\n\n    def run(self):\n        if not self.query:\n            return\n\n        self.args = map(str, self.args)\n        si = None\n        if os.name == 'nt':\n            si = subprocess.STARTUPINFO()\n            si.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n\n        # select appropriate file handle for stderr\n        # usually we want to redirect stderr to stdout, so erros are shown\n        # in the output in the right place (where they actually occurred)\n        # only if silenceErrors=True, we separate stderr from stdout and discard it\n        stderrHandle = subprocess.STDOUT\n        if self.silenceErrors:\n            stderrHandle = subprocess.PIPE\n\n        # set the environment\n        modifiedEnvironment = os.environ.copy()\n        if (self.env):\n            modifiedEnvironment.update(self.env)\n\n        queryTimerStart = time.time()\n\n        self.process = subprocess.Popen(self.args,\n                                        stdout=subprocess.PIPE,\n                                        stderr=stderrHandle,\n                                        stdin=subprocess.PIPE,\n                                        env=modifiedEnvironment,\n                                        startupinfo=si)\n\n        if self.stream:\n            self.process.stdin.write(self.query.encode(self.encoding))\n            self.process.stdin.close()\n            hasWritten = False\n\n            for line in self.process.stdout:\n                self.callback(line.decode(self.encoding, 'replace').replace('\\r', ''))\n                hasWritten = True\n\n            queryTimerEnd = time.time()\n            # we are done with the output, terminate the process\n            if self.process:\n                self.process.terminate()\n            else:\n                if hasWritten:\n                    self.callback('\\n')\n\n            if self.options['show_query']:\n                formattedQueryInfo = self._formatShowQuery(self.query, queryTimerStart, queryTimerEnd)\n                self.callback(formattedQueryInfo + '\\n')\n\n            return\n\n        # regular mode is handled with more reliable Popen.communicate\n        # which also terminates the process afterwards\n        results, errors = self.process.communicate(input=self.query.encode(self.encoding))\n\n        queryTimerEnd = time.time()\n\n        resultString = ''\n\n        if results:\n            resultString += results.decode(self.encoding,\n                                           'replace').replace('\\r', '')\n\n        if errors and not self.silenceErrors:\n            resultString += errors.decode(self.encoding,\n                                          'replace').replace('\\r', '')\n\n        if self.process is None and resultString != '':\n            resultString += '\\n'\n\n        if self.options['show_query']:\n            formattedQueryInfo = self._formatShowQuery(self.query, queryTimerStart, queryTimerEnd)\n            queryPlacement = self.options['show_query']\n            if queryPlacement == 'top':\n                resultString = \"{0}\\n{1}\".format(formattedQueryInfo, resultString)\n            elif queryPlacement == 'bottom':\n                resultString = \"{0}{1}\\n\".format(resultString, formattedQueryInfo)\n\n        self.callback(resultString)\n\n    @staticmethod\n    def _formatShowQuery(query, queryTimeStart, queryTimeEnd):\n        resultInfo = \"/*\\n-- Executed querie(s) at {0} took {1:.3f} s --\".format(\n            str(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(queryTimeStart))),\n            (queryTimeEnd - queryTimeStart))\n        resultLine = \"-\" * (len(resultInfo) - 3)\n        resultString = \"{0}\\n{1}\\n{2}\\n{3}\\n*/\".format(\n            resultInfo, resultLine, query, resultLine)\n        return resultString\n\n    @staticmethod\n    def createAndRun(args, env, callback, query=None, encoding='utf-8',\n                     options=None, timeout=15, silenceErrors=False, stream=False):\n        if options is None:\n            options = {}\n        command = Command(args=args,\n                          env=env,\n                          callback=callback,\n                          query=query,\n                          encoding=encoding,\n                          options=options,\n                          timeout=timeout,\n                          silenceErrors=silenceErrors,\n                          stream=stream)\n        command.run()\n\n\nclass ThreadCommand(Command, Thread):\n    def __init__(self, args, env, callback, query=None, encoding='utf-8',\n                 options=None, timeout=Command.timeout, silenceErrors=False, stream=False):\n        if options is None:\n            options = {}\n\n        Command.__init__(self,\n                         args=args,\n                         env=env,\n                         callback=callback,\n                         query=query,\n                         encoding=encoding,\n                         options=options,\n                         timeout=timeout,\n                         silenceErrors=silenceErrors,\n                         stream=stream)\n        Thread.__init__(self)\n\n    def stop(self):\n        if not self.process:\n            return\n\n        # if poll returns None - proc still running, otherwise returns process return code\n        if self.process.poll() is not None:\n            return\n\n        try:\n            # Windows does not provide SIGKILL, go with SIGTERM\n            sig = getattr(signal, 'SIGKILL', signal.SIGTERM)\n            os.kill(self.process.pid, sig)\n            self.process = None\n\n            logger.info(\"command execution exceeded timeout (%s s), process killed\", self.timeout)\n            self.callback((\"Command execution time exceeded 'thread_timeout' ({0} s).\\n\"\n                           \"Process killed!\\n\\n\"\n                          ).format(self.timeout))\n        except Exception:\n            logger.info(\"command execution exceeded timeout (%s s), process could not be killed\", self.timeout)\n            self.callback((\"Command execution time exceeded 'thread_timeout' ({0} s).\\n\"\n                           \"Process could not be killed!\\n\\n\"\n                          ).format(self.timeout))\n            pass\n\n    @staticmethod\n    def createAndRun(args, env, callback, query=None, encoding='utf-8',\n                     options=None, timeout=Command.timeout, silenceErrors=False, stream=False):\n        # Don't allow empty dicts or lists as defaults in method signature,\n        # cfr http://nedbatchelder.com/blog/200806/pylint.html\n        if options is None:\n            options = {}\n        command = ThreadCommand(args=args,\n                                env=env,\n                                callback=callback,\n                                query=query,\n                                encoding=encoding,\n                                options=options,\n                                timeout=timeout,\n                                silenceErrors=silenceErrors,\n                                stream=stream)\n        command.start()\n        killTimeout = Timer(command.timeout, command.stop)\n        killTimeout.start()\n"
  },
  {
    "path": "SQLToolsAPI/Completion.py",
    "content": "import re\nimport logging\nfrom collections import namedtuple\n\nfrom .ParseUtils import extractTables\n\nJOIN_COND_PATTERN = r\"\\s+?JOIN\\s+?[\\w\\.`\\\"]+\\s+?(?:AS\\s+)?(\\w+)\\s+?ON\\s+?(?:[\\w\\.]+)?$\"\nJOIN_COND_REGEX = re.compile(JOIN_COND_PATTERN, re.IGNORECASE)\n\nkeywords_list = [\n    'SELECT', 'UPDATE', 'DELETE', 'INSERT', 'INTO', 'FROM',\n    'WHERE', 'GROUP BY', 'ORDER BY', 'HAVING', 'JOIN',\n    'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'USING',\n    'LIMIT', 'DISTINCT', 'SET'\n]\n\nlogger = logging.getLogger(__name__)\n\n\n# this function is generously used in completions code to get rid\n# of all sorts of leading and trailing quotes in RDBMS identifiers\ndef _stripQuotes(ident):\n    return ident.strip('\"\\'`')\n\n\n# used for formatting output\ndef _stripQuotesOnDemand(ident, doStrip=True):\n    if doStrip:\n        return _stripQuotes(ident)\n    return ident\n\n\ndef _startsWithQuote(ident):\n    # ident is matched against any of the possible ident quotes\n    quotes = ('`', '\"')\n    return ident.startswith(quotes)\n\n\ndef _stripPrefix(text, prefix):\n    if text.startswith(prefix):\n        return text[len(prefix):]\n    return text\n\n\n# escape $ sign when formatting output\ndef _escapeDollarSign(ident):\n    return ident.replace(\"$\", \"\\$\")\n\n\nclass CompletionItem(namedtuple('CompletionItem', ['type', 'ident'])):\n    \"\"\"Represents a potential or actual completion item.\n      * type - type of item (Table, Function, Column)\n      * ident - identifier (table.column, schema.table, alias)\n    \"\"\"\n    __slots__ = ()\n\n    @property\n    def parent(self):\n        \"\"\"Parent of identifier, e.g. \"table\" from \"table.column\" \"\"\"\n        if self.ident.count('.') == 0:\n            return None\n        else:\n            return self.ident.partition('.')[0]\n\n    @property\n    def name(self):\n        \"\"\"Name of identifier, e.g. \"column\" from \"table.column\" \"\"\"\n        return self.ident.split('.').pop()\n\n    # for functions - strip open bracket \"(\" and everything after that\n    # e.g: mydb.myAdd(int, int) --> mydb.myadd\n    def _matchIdent(self):\n        if self.type == 'Function':\n            return self.ident.partition('(')[0].lower()\n        return self.ident.lower()\n\n    # Helper method for string matching\n    # When exactly is true:\n    #   matches search string to target exactly, but empty search string matches anything\n    # When exactly is false:\n    #   if only one char given in search string match this single char with start\n    #   of target string, otherwise match search string anywhere in target string\n    @staticmethod\n    def _stringMatched(target, search, exactly):\n        if exactly:\n            return target == search or search == ''\n        else:\n            if (len(search) == 1):\n                return target.startswith(search)\n            return search in target\n\n    # Method to match completion item against search string (prefix).\n    # Lower score means a better match.\n    # If completion item matches prefix with parent identifier, e.g.:\n    #     table_name.column ~ table_name.co, then score = 1\n    # If completion item matches prefix without parent identifier, e.g.:\n    #     table_name.column ~ co, then score = 2\n    # If completion item matches, but prefix has no parent, e.g.:\n    #     table ~ tab, then score = 3\n    def prefixMatchScore(self, search, exactly=False):\n        target = self._matchIdent()\n        search = search.lower()\n\n        # match parent exactly and partially match name\n        if '.' in target and '.' in search:\n            searchList = search.split('.')\n            searchObject = _stripQuotes(searchList.pop())\n            searchParent = _stripQuotes(searchList.pop())\n            targetList = target.split('.')\n            targetObject = _stripQuotes(targetList.pop())\n            targetParent = _stripQuotes(targetList.pop())\n            if (searchParent == targetParent):\n                if self._stringMatched(targetObject, searchObject, exactly):\n                    return 1   # highest score\n            return 0\n\n        # second part matches ?\n        if '.' in target:\n            targetObjectNoQuote = _stripQuotes(target.split('.').pop())\n            searchNoQuote = _stripQuotes(search)\n            if self._stringMatched(targetObjectNoQuote, searchNoQuote, exactly):\n                return 2\n        else:\n            targetNoQuote = _stripQuotes(target)\n            searchNoQuote = _stripQuotes(search)\n            if self._stringMatched(targetNoQuote, searchNoQuote, exactly):\n                return 3\n            else:\n                return 0\n        return 0\n\n    def prefixMatchListScore(self, searchList, exactly=False):\n        for item in searchList:\n            score = self.prefixMatchScore(item, exactly)\n            if score:\n                return score\n        return 0\n\n    # format completion item according to sublime text completions format\n    def format(self, stripQuotes=False):\n        typeDisplay = ''\n        if self.type == 'Table':\n            typeDisplay = self.type\n        elif self.type == 'Keyword':\n            typeDisplay = self.type\n        elif self.type == 'Alias':\n            typeDisplay = self.type\n        elif self.type == 'Function':\n            typeDisplay = 'Func'\n        elif self.type == 'Column':\n            typeDisplay = 'Col'\n\n        if not typeDisplay:\n            return (self.ident, _stripQuotesOnDemand(self.ident, stripQuotes))\n\n        part = self.ident.split('.')\n        if len(part) > 1:\n            return (\"{0}\\t({1} {2})\".format(part[1], part[0], typeDisplay),\n                    _stripQuotesOnDemand(_escapeDollarSign(part[1]), stripQuotes))\n\n        return (\"{0}\\t({1})\".format(self.ident, typeDisplay),\n                _stripQuotesOnDemand(_escapeDollarSign(self.ident), stripQuotes))\n\n\nclass Completion:\n    def __init__(self, allTables, allColumns, allFunctions, settings=None):\n        self.allTables = [CompletionItem('Table', table) for table in allTables]\n        self.allColumns = [CompletionItem('Column', column) for column in allColumns]\n        self.allFunctions = [CompletionItem('Function', func) for func in allFunctions]\n\n        # we don't save the settings (we don't need them after init)\n        if settings is None:\n            settings = {}\n\n        # check old setting name ('selectors') first for compatibility\n        activeSelectors = settings.get('selectors', None)\n        if not activeSelectors:\n            activeSelectors = settings.get(\n                'autocomplete_selectors_active',\n                ['source.sql'])\n        self.activeSelectors = activeSelectors\n\n        self.ignoreSelectors = settings.get(\n            'autocomplete_selectors_ignore',\n            ['string.quoted.single.sql'])\n\n        # determine type of completions\n        self.completionType = settings.get('autocompletion', 'smart')\n        if not self.completionType:\n            self.completionType = None  # autocompletion disabled\n        else:\n            self.completionType = str(self.completionType).strip()\n            if self.completionType not in ['basic', 'smart']:\n                self.completionType = 'smart'\n\n        # determine desired keywords case from settings\n        formatSettings = settings.get('format', {})\n        keywordCase = formatSettings.get('keyword_case', 'upper')\n        uppercaseKeywords = keywordCase.lower().startswith('upper')\n\n        self.allKeywords = []\n        for keyword in keywords_list:\n            if uppercaseKeywords:\n                keyword = keyword.upper()\n            else:\n                keyword = keyword.lower()\n\n            self.allKeywords.append(CompletionItem('Keyword', keyword))\n\n    def getActiveSelectors(self):\n        return self.activeSelectors\n\n    def getIgnoreSelectors(self):\n        return self.ignoreSelectors\n\n    def isDisabled(self):\n        return self.completionType is None\n\n    def getAutoCompleteList(self, prefix, sql, sqlToCursor):\n        if self.isDisabled():\n            return None\n\n        autocompleteList = []\n        inhibit = False\n        if self.completionType == 'smart':\n            autocompleteList, inhibit = self._getAutoCompleteListSmart(prefix, sql, sqlToCursor)\n        else:\n            autocompleteList = self._getAutoCompleteListBasic(prefix)\n\n        if not autocompleteList:\n            return None, False\n\n        # return completions with or without quotes?\n        # determined based on ident after last dot\n        startsWithQuote = _startsWithQuote(prefix.split(\".\").pop())\n        autocompleteList = [item.format(startsWithQuote) for item in autocompleteList]\n\n        return autocompleteList, inhibit\n\n    def _getAutoCompleteListBasic(self, prefix):\n        prefix = prefix.lower()\n        autocompleteList = []\n\n        # columns, tables and functions that match the prefix\n        for item in self.allColumns:\n            score = item.prefixMatchScore(prefix)\n            if score:\n                autocompleteList.append(item)\n\n        for item in self.allTables:\n            score = item.prefixMatchScore(prefix)\n            if score:\n                autocompleteList.append(item)\n\n        for item in self.allFunctions:\n            score = item.prefixMatchScore(prefix)\n            if score:\n                autocompleteList.append(item)\n\n        if len(autocompleteList) == 0:\n            return None\n\n        return autocompleteList\n\n    def _getAutoCompleteListSmart(self, prefix, sql, sqlToCursor):\n        \"\"\"\n        Generally, we recognize 3 different variations in prefix:\n          * ident|           // no dots (.) in prefix\n            In this case we show completions for all available identifiers (tables, columns,\n            functions) that have \"ident\" text in them. Identifiers relevant to current\n            statement shown first.\n          * parent.ident|   // single dot in prefix\n            In this case, if \"parent\" matches on of parsed table aliases we show column\n            completions for them, as well as we do prefix search for all other identifiers.\n            If something is matched, we return results as well as set a flag to suppress\n            Sublime completions.\n            If we don't find any objects using prefix search or we know that \"parent\" is\n            a query alias, we don't return anything and allow Sublime to do it's job by\n            showing most relevant completions.\n          * database.table.col|   // multiple dots in prefix\n            In this case we only show columns for \"table\" column, as there is nothing else\n            that could be referenced that way.\n        Since it's too complicated to handle the specifics of identifiers case sensitivity\n        as well as all nuances of quoting of those identifiers for each RDBMS, we always\n        match against lower-cased and stripped quotes of both prefix and our internal saved\n        identifiers (tables, columns, functions). E.g. \"MyTable\".\"myCol\" --> mytable.mycol\n        \"\"\"\n\n        # TODO: add completions of function out fields\n        prefix = prefix.lower()\n        prefixDots = prefix.count('.')\n\n        # continue with empty identifiers list, even if we failed to parse identifiers\n        identifiers = []\n        try:\n            identifiers = extractTables(sql)\n        except Exception as e:\n            logger.debug('Failed to extact the list identifiers from SQL:\\n {}'.format(sql),\n                         exc_info=True)\n\n        # joinAlias is set only if user is editing join condition with alias. E.g.\n        # SELECT a.* from tbl_a a inner join tbl_b b ON |\n        joinAlias = None\n        if prefixDots <= 1:\n            try:\n                joinCondMatch = JOIN_COND_REGEX.search(sqlToCursor, re.IGNORECASE)\n                if joinCondMatch:\n                    joinAlias = joinCondMatch.group(1)\n            except Exception as e:\n                logger.debug('Failed search of join condition, SQL:\\n {}'.format(sqlToCursor),\n                             exc_info=True)\n\n        autocompleteList = []\n        inhibit = False\n        if prefixDots == 0:\n            autocompleteList, inhibit = self._noDotsCompletions(prefix, identifiers, joinAlias)\n        elif prefixDots == 1:\n            autocompleteList, inhibit = self._singleDotCompletions(prefix, identifiers, joinAlias)\n        else:\n            autocompleteList, inhibit = self._multiDotCompletions(prefix, identifiers)\n\n        if not autocompleteList:\n            return None, False\n\n        return autocompleteList, inhibit\n\n    def _noDotsCompletions(self, prefix, identifiers, joinAlias=None):\n        \"\"\"\n        Method handles most generic completions when prefix does not contain any dots.\n        In this case completions can be anything: cols, tables, functions that have this name.\n        Still we try to predict users needs and output aliases, tables, columns and function\n        that are used in currently parsed statement first, then show everything else that\n        could be related.\n        Order: statement aliases -> statement cols -> statement tables -> statement functions,\n        then:  other cols -> other tables -> other functions that match the prefix in their names\n        \"\"\"\n\n        # use set, as we are interested only in unique identifiers\n        sqlAliases = set()\n        sqlTables = []\n        sqlColumns = []\n        sqlFunctions = []\n        otherTables = []\n        otherColumns = []\n        otherFunctions = []\n        otherKeywords = []\n        otherJoinConditions = []\n\n        # utilitary temp lists\n        identTables = set()\n        identColumns = set()\n        identFunctions = set()\n\n        for ident in identifiers:\n            if ident.has_alias():\n                aliasItem = CompletionItem('Alias', ident.alias)\n                score = aliasItem.prefixMatchScore(prefix)\n                if score and aliasItem.ident != prefix:\n                    sqlAliases.add(aliasItem)\n\n            if ident.is_function:\n                identFunctions.add(ident.full_name)\n            elif ident.is_table_alias:\n                identTables.add(ident.full_name)\n                identColumns.add(ident.name + '.' + prefix)\n\n        for table in self.allTables:\n            score = table.prefixMatchScore(prefix, exactly=False)\n            if score:\n                if table.prefixMatchListScore(identTables, exactly=True) > 0:\n                    sqlTables.append(table)\n                else:\n                    otherTables.append(table)\n\n        for col in self.allColumns:\n            score = col.prefixMatchScore(prefix, exactly=False)\n            if score:\n                if col.prefixMatchListScore(identColumns, exactly=False) > 0:\n                    sqlColumns.append(col)\n                else:\n                    otherColumns.append(col)\n\n        for fun in self.allFunctions:\n            score = fun.prefixMatchScore(prefix, exactly=False)\n            if score:\n                if fun.prefixMatchListScore(identFunctions, exactly=True) > 0:\n                    sqlColumns.append(fun)\n                else:\n                    otherColumns.append(fun)\n\n        # keywords\n        for item in self.allKeywords:\n            score = item.prefixMatchScore(prefix)\n            if score:\n                otherKeywords.append(item)\n\n        # join conditions\n        if joinAlias:\n            joinConditions = self._joinConditionCompletions(identifiers, joinAlias)\n\n            for condition in joinConditions:\n                if condition.ident.lower().startswith(prefix):\n                    otherJoinConditions.append(condition)\n\n        # collect the results in prefered order\n        autocompleteList = []\n\n        # first of all list join conditions (if applicable)\n        autocompleteList.extend(otherJoinConditions)\n\n        # then aliases and identifiers related to currently parsed statement\n        autocompleteList.extend(sqlAliases)\n\n        # then cols, tables, functions related to current statement\n        autocompleteList.extend(sqlColumns)\n        autocompleteList.extend(sqlTables)\n        autocompleteList.extend(sqlFunctions)\n\n        # then other matching cols, tables, functions\n        autocompleteList.extend(otherKeywords)\n        autocompleteList.extend(otherColumns)\n        autocompleteList.extend(otherTables)\n        autocompleteList.extend(otherFunctions)\n\n        return autocompleteList, False\n\n    def _singleDotCompletions(self, prefix, identifiers, joinAlias=None):\n        \"\"\"\n        More intelligent completions can be shown if we have single dot in prefix in certain cases.\n        \"\"\"\n        prefixList = prefix.split(\".\")\n        prefixObject = prefixList.pop()\n        prefixParent = prefixList.pop()\n\n        # get join conditions\n        joinConditions = []\n        if joinAlias:\n            joinConditions = self._joinConditionCompletions(identifiers, joinAlias)\n\n        sqlTableAliases = set()  # set of CompletionItem\n        sqlQueryAliases = set()  # set of strings\n\n        # we use set, as we are interested only in unique identifiers\n        for ident in identifiers:\n            if ident.has_alias() and ident.alias.lower() == prefixParent:\n                if ident.is_query_alias:\n                    sqlQueryAliases.add(ident.alias)\n\n                if ident.is_table_alias:\n                    tables = [\n                        table\n                        for table in self.allTables\n                        if table.prefixMatchScore(ident.full_name, exactly=True) > 0\n                    ]\n                    sqlTableAliases.update(tables)\n\n        autocompleteList = []\n\n        for condition in joinConditions:\n            aliasPrefix = prefixParent + '.'\n            if condition.ident.lower().startswith(aliasPrefix):\n                autocompleteList.append(CompletionItem(condition.type,\n                                                       _stripPrefix(condition.ident, aliasPrefix)))\n\n        # first of all expand table aliases to real table names and try\n        # to match their columns with prefix of these expanded identifiers\n        # e.g. select x.co| from tab x   //  \"x.co\" will expland to \"tab.co\"\n        for table_item in sqlTableAliases:\n            prefix_to_match = table_item.name + '.' + prefixObject\n            for item in self.allColumns:\n                score = item.prefixMatchScore(prefix_to_match)\n                if score:\n                    autocompleteList.append(item)\n\n        # try to match all our other objects (tables, columns, functions) with prefix\n        for item in self.allColumns:\n            score = item.prefixMatchScore(prefix)\n            if score:\n                autocompleteList.append(item)\n\n        for item in self.allTables:\n            score = item.prefixMatchScore(prefix)\n            if score:\n                autocompleteList.append(item)\n\n        for item in self.allFunctions:\n            score = item.prefixMatchScore(prefix)\n            if score:\n                autocompleteList.append(item)\n\n        inhibit = len(autocompleteList) > 0\n        # in case prefix parent is a query alias we simply don't know what those\n        # columns might be so, set inhibit = False to allow sublime default completions\n        if prefixParent in sqlQueryAliases:\n            inhibit = False\n\n        return autocompleteList, inhibit\n\n    # match only columns if prefix contains multiple dots (db.table.col)\n    def _multiDotCompletions(self, prefix, identifiers):\n        autocompleteList = []\n        for item in self.allColumns:\n            score = item.prefixMatchScore(prefix)\n            if score:\n                autocompleteList.append(item)\n\n        if len(autocompleteList) > 0:\n            return autocompleteList, True\n\n        return None, False\n\n    def _joinConditionCompletions(self, identifiers, joinAlias=None):\n        if not joinAlias:\n            return None\n\n        # use set, as we are interested only in unique identifiers\n        sqlTableAliases = set()\n        joinAliasColumns = set()\n        sqlOtherColumns = set()\n\n        for ident in identifiers:\n            if ident.has_alias() and not ident.is_function:\n                sqlTableAliases.add(CompletionItem('Alias', ident.alias))\n\n                prefixForColumnMatch = ident.name + '.'\n                columns = [\n                    (ident.alias, col)\n                    for col in self.allColumns\n                    if (col.prefixMatchScore(prefixForColumnMatch, exactly=True) > 0 and\n                        _stripQuotes(col.name).lower().endswith('id'))\n                ]\n\n                if ident.alias == joinAlias:\n                    joinAliasColumns.update(columns)\n                else:\n                    sqlOtherColumns.update(columns)\n\n        joinCandidatesCompletions = []\n        for joinAlias, joinColumn in joinAliasColumns:\n            # str.endswith can be matched against a tuple\n            columnsToMatch = None\n            if _stripQuotes(joinColumn.name).lower() == 'id':\n                columnsToMatch = (\n                    _stripQuotes(joinColumn.parent).lower() + _stripQuotes(joinColumn.name).lower(),\n                    _stripQuotes(joinColumn.parent).lower() + '_' + _stripQuotes(joinColumn.name).lower()\n                )\n            else:\n                columnsToMatch = (\n                    _stripQuotes(joinColumn.name).lower(),\n                    _stripQuotes(joinColumn.parent).lower() + _stripQuotes(joinColumn.name).lower(),\n                    _stripQuotes(joinColumn.parent).lower() + '_' + _stripQuotes(joinColumn.name).lower()\n                )\n\n            for otherAlias, otherColumn in sqlOtherColumns:\n                if _stripQuotes(otherColumn.name).lower().endswith(columnsToMatch):\n                    sideA = joinAlias + '.' + joinColumn.name\n                    sideB = otherAlias + '.' + otherColumn.name\n\n                    joinCandidatesCompletions.append(CompletionItem('Condition', sideA + ' = ' + sideB))\n                    joinCandidatesCompletions.append(CompletionItem('Condition', sideB + ' = ' + sideA))\n\n        return joinCandidatesCompletions\n"
  },
  {
    "path": "SQLToolsAPI/Connection.py",
    "content": "import shutil\nimport shlex\nimport codecs\nimport logging\nimport sqlparse\n\nfrom . import Utils as U\nfrom . import Command as C\n\nlogger = logging.getLogger(__name__)\n\n\ndef _encoding_exists(enc):\n    try:\n        codecs.lookup(enc)\n    except LookupError:\n        return False\n    return True\n\n\nclass Connection(object):\n    DB_CLI_NOT_FOUND_MESSAGE = \"\"\"DB CLI '{0}' could not be found.\nPlease set the path to DB CLI '{0}' binary in your SQLTools settings before continuing.\nExample of \"cli\" section in SQLTools.sublime-settings:\n    /* ...  (note the use of forward slashes) */\n    \"cli\" : {{\n        \"mysql\"   : \"c:/Program Files/MySQL/MySQL Server 5.7/bin/mysql.exe\",\n        \"pgsql\"   : \"c:/Program Files/PostgreSQL/9.6/bin/psql.exe\"\n    }}\nYou might need to restart the editor for settings to be refreshed.\"\"\"\n\n    name = None\n    options = None\n    settings = None\n    type = None\n    host = None\n    port = None\n    database = None\n    username = None\n    password = None\n    encoding = None\n    safe_limit = None\n    show_query = None\n    rowsLimit = None\n    history = None\n    timeout = None\n\n    def __init__(self, name, options, settings=None, commandClass='ThreadCommand'):\n        self.Command = getattr(C, commandClass)\n\n        self.name = name\n        self.options = {k: v for k, v in options.items() if v is not None}\n\n        if settings is None:\n            settings = {}\n        self.settings = settings\n\n        self.type       = self.options.get('type', None)\n        self.host       = self.options.get('host', None)\n        self.port       = self.options.get('port', None)\n        self.database   = self.options.get('database', None)\n        self.username   = self.options.get('username', None)\n        self.password   = self.options.get('password', None)\n        self.encoding   = self.options.get('encoding', 'utf-8')\n        self.encoding   = self.encoding or 'utf-8'  # defaults to utf-8\n        if not _encoding_exists(self.encoding):\n            self.encoding = 'utf-8'\n\n        self.safe_limit = settings.get('safe_limit', None)\n        self.show_query = settings.get('show_query', False)\n        self.rowsLimit  = settings.get('show_records', {}).get('limit', 50)\n        self.useStreams = settings.get('use_streams', False)\n        self.cli        = settings.get('cli')[self.options['type']]\n\n        cli_path = shutil.which(self.cli)\n        if cli_path is None:\n            logger.info(self.DB_CLI_NOT_FOUND_MESSAGE.format(self.cli))\n            raise FileNotFoundError(self.DB_CLI_NOT_FOUND_MESSAGE.format(self.cli))\n\n    def __str__(self):\n        return self.name\n\n    def info(self):\n        return 'DB: {0}, Connection: {1}@{2}:{3}'.format(\n            self.database, self.username, self.host, self.port)\n\n    def runInternalNamedQueryCommand(self, queryName, callback):\n        query = self.getNamedQuery(queryName)\n        if not query:\n            emptyList = []\n            callback(emptyList)\n            return\n\n        queryToRun = self.buildNamedQuery(queryName, query)\n        args = self.buildArgs(queryName)\n        env = self.buildEnv()\n\n        def cb(result):\n            callback(U.getResultAsList(result))\n\n        self.Command.createAndRun(args=args,\n                                  env=env,\n                                  callback=cb,\n                                  query=queryToRun,\n                                  encoding=self.encoding,\n                                  timeout=60,\n                                  silenceErrors=True,\n                                  stream=False)\n\n    def getTables(self, callback):\n        self.runInternalNamedQueryCommand('desc', callback)\n\n    def getColumns(self, callback):\n        self.runInternalNamedQueryCommand('columns', callback)\n\n    def getFunctions(self, callback):\n        self.runInternalNamedQueryCommand('functions', callback)\n\n    def runFormattedNamedQueryCommand(self, queryName, formatValues, callback):\n        query = self.getNamedQuery(queryName)\n        if not query:\n            return\n\n        # added for compatibility with older format string\n        query = query.replace(\"%s\", \"{0}\", 1)\n        query = query.replace(\"%s\", \"{1}\", 1)\n\n        if isinstance(formatValues, tuple):\n            query = query.format(*formatValues)  # unpack the tuple\n        else:\n            query = query.format(formatValues)\n\n        queryToRun = self.buildNamedQuery(queryName, query)\n        args = self.buildArgs(queryName)\n        env = self.buildEnv()\n        self.Command.createAndRun(args=args,\n                                  env=env,\n                                  callback=callback,\n                                  query=queryToRun,\n                                  encoding=self.encoding,\n                                  timeout=self.timeout,\n                                  silenceErrors=False,\n                                  stream=False)\n\n    def getTableRecords(self, tableName, callback):\n        # in case we expect multiple values pack them into tuple\n        formatValues = (tableName, self.rowsLimit)\n        self.runFormattedNamedQueryCommand('show records', formatValues, callback)\n\n    def getTableDescription(self, tableName, callback):\n        self.runFormattedNamedQueryCommand('desc table', tableName, callback)\n\n    def getFunctionDescription(self, functionName, callback):\n        self.runFormattedNamedQueryCommand('desc function', functionName, callback)\n\n    def explainPlan(self, queries, callback):\n        queryName = 'explain plan'\n        explainQuery = self.getNamedQuery(queryName)\n        if not explainQuery:\n            return\n\n        strippedQueries = [\n            explainQuery.format(query.strip().strip(\";\"))\n            for rawQuery in queries\n            for query in filter(None, sqlparse.split(rawQuery))\n        ]\n        queryToRun = self.buildNamedQuery(queryName, strippedQueries)\n        args = self.buildArgs(queryName)\n        env = self.buildEnv()\n        self.Command.createAndRun(args=args,\n                                  env=env,\n                                  callback=callback,\n                                  query=queryToRun,\n                                  encoding=self.encoding,\n                                  timeout=self.timeout,\n                                  silenceErrors=False,\n                                  stream=self.useStreams)\n\n    def execute(self, queries, callback, stream=None):\n        queryName = 'execute'\n\n        # if not explicitly overriden, use the value from settings\n        if stream is None:\n            stream = self.useStreams\n\n        if isinstance(queries, str):\n            queries = [queries]\n\n        # add original (umodified) queries to the history\n        if self.history:\n            self.history.add('\\n'.join(queries))\n\n        processedQueriesList = []\n        for rawQuery in queries:\n            for query in sqlparse.split(rawQuery):\n                if self.safe_limit:\n                    parsedTokens = sqlparse.parse(query.strip().replace(\"'\", \"\\\"\"))\n                    if ((parsedTokens[0][0].ttype in sqlparse.tokens.Keyword and\n                            parsedTokens[0][0].value == 'select')):\n                        applySafeLimit = True\n                        for parse in parsedTokens:\n                            for token in parse.tokens:\n                                if token.ttype in sqlparse.tokens.Keyword and token.value == 'limit':\n                                    applySafeLimit = False\n                        if applySafeLimit:\n                            if (query.strip()[-1:] == ';'):\n                                query = query.strip()[:-1]\n                            query += \" LIMIT {0};\".format(self.safe_limit)\n                processedQueriesList.append(query)\n\n        queryToRun = self.buildNamedQuery(queryName, processedQueriesList)\n        args = self.buildArgs(queryName)\n        env = self.buildEnv()\n\n        logger.debug(\"Query: %s\", str(queryToRun))\n\n        self.Command.createAndRun(args=args,\n                                  env=env,\n                                  callback=callback,\n                                  query=queryToRun,\n                                  encoding=self.encoding,\n                                  options={'show_query': self.show_query},\n                                  timeout=self.timeout,\n                                  silenceErrors=False,\n                                  stream=stream)\n\n    def getNamedQuery(self, queryName):\n        if not queryName:\n            return None\n\n        cliOptions = self.getOptionsForSgdbCli()\n        return cliOptions.get('queries', {}).get(queryName, {}).get('query')\n\n    def buildNamedQuery(self, queryName, queries):\n        if not queryName:\n            return None\n\n        if not queries:\n            return None\n\n        cliOptions = self.getOptionsForSgdbCli()\n        beforeCli = cliOptions.get('before')\n        afterCli = cliOptions.get('after')\n        beforeQuery = cliOptions.get('queries', {}).get(queryName, {}).get('before')\n        afterQuery = cliOptions.get('queries', {}).get(queryName, {}).get('after')\n\n        # sometimes we preprocess the raw queries from user, in that case we already have a list\n        if type(queries) is not list:\n            queries = [queries]\n\n        builtQueries = []\n        if beforeCli is not None:\n            builtQueries.extend(beforeCli)\n        if beforeQuery is not None:\n            builtQueries.extend(beforeQuery)\n        if queries is not None:\n            builtQueries.extend(queries)\n        if afterQuery is not None:\n            builtQueries.extend(afterQuery)\n        if afterCli is not None:\n            builtQueries.extend(afterCli)\n\n        # remove empty list items\n        builtQueries = list(filter(None, builtQueries))\n\n        return '\\n'.join(builtQueries)\n\n    def buildArgs(self, queryName=None):\n        cliOptions = self.getOptionsForSgdbCli()\n        args = [self.cli]\n\n        # append otional args (if any) - could be a single value or a list\n        optionalArgs = cliOptions.get('args_optional')\n        if optionalArgs:  # only if we have optional args\n            if isinstance(optionalArgs, list):\n                for item in optionalArgs:\n                    formattedItem = self.formatOptionalArgument(item, self.options)\n                    if formattedItem:\n                        args = args + shlex.split(formattedItem)\n            else:\n                formattedItem = self.formatOptionalArgument(optionalArgs, self.options)\n                if formattedItem:\n                    args = args + shlex.split(formattedItem)\n\n        # append generic options\n        options = cliOptions.get('options', None)\n        if options:\n            args = args + options\n\n        # append query specific options (if present)\n        if queryName:\n            queryOptions = cliOptions.get('queries', {}).get(queryName, {}).get('options')\n            if queryOptions:\n                if len(queryOptions) > 0:\n                    args = args + queryOptions\n\n        # append main args - could be a single value or a list\n        mainArgs = cliOptions['args']\n        if isinstance(mainArgs, list):\n            mainArgs = ' '.join(mainArgs)\n\n        mainArgs = mainArgs.format(**self.options)\n        args = args + shlex.split(mainArgs)\n\n        logger.debug('CLI args (%s): %s', str(queryName), ' '.join(args))\n        return args\n\n    def buildEnv(self):\n        cliOptions = self.getOptionsForSgdbCli()\n        env = dict()\n\n        # append **optional** environment variables dict (if any)\n        optionalEnv = cliOptions.get('env_optional')\n        if optionalEnv:  # only if we have optional args\n            if isinstance(optionalEnv, dict):\n                for var, value in optionalEnv.items():\n                    formattedValue = self.formatOptionalArgument(value, self.options)\n                    if formattedValue:\n                        env.update({var: formattedValue})\n\n        # append environment variables dict (if any)\n        staticEnv = cliOptions.get('env')\n        if staticEnv:  # only if we have optional args\n            if isinstance(staticEnv, dict):\n                for var, value in staticEnv.items():\n                    formattedValue = value.format(**self.options)\n                    if formattedValue:\n                        env.update({var: formattedValue})\n\n        logger.debug('CLI environment: %s', str(env))\n        return env\n\n    def getOptionsForSgdbCli(self):\n        return self.settings.get('cli_options', {}).get(self.type)\n\n    @staticmethod\n    def formatOptionalArgument(argument, formatOptions):\n        try:\n            formattedArg = argument.format(**formatOptions)\n        except (KeyError, IndexError):\n            return None\n\n        if argument == formattedArg:  # string not changed after format\n            return None\n        return formattedArg\n\n    @staticmethod\n    def setTimeout(timeout):\n        Connection.timeout = timeout\n        logger.info('Connection timeout set to {0} seconds'.format(timeout))\n\n    @staticmethod\n    def setHistoryManager(manager):\n        Connection.history = manager\n        size = manager.getMaxSize()\n        logger.info('Connection history size is {0}'.format(size))\n"
  },
  {
    "path": "SQLToolsAPI/History.py",
    "content": "__version__ = \"v0.1.0\"\n\n\nclass SizeException(Exception):\n    pass\n\n\nclass NotFoundException(Exception):\n    pass\n\n\nclass History:\n\n    def __init__(self, maxSize=100):\n        self.items = []\n        self.maxSize = maxSize\n\n    def add(self, query):\n        if self.getSize() >= self.getMaxSize():\n            self.items.pop(0)\n        self.items.insert(0, query)\n\n    def get(self, index):\n        if index < 0 or index > (len(self.items) - 1):\n            raise NotFoundException(\"No query selected\")\n\n        return self.items[index]\n\n    def setMaxSize(self, size=100):\n        if size < 1:\n            raise SizeException(\"Size can't be lower than 1\")\n\n        self.maxSize = size\n        return self.maxSize\n\n    def getMaxSize(self):\n        return self.maxSize\n\n    def getSize(self):\n        return len(self.items)\n\n    def all(self):\n        return self.items\n\n    def clear(self):\n        self.items = []\n        return self.items\n"
  },
  {
    "path": "SQLToolsAPI/ParseUtils.py",
    "content": "import os\nimport sys\nimport itertools\nfrom collections import namedtuple\n\ndirpath = os.path.join(os.path.dirname(__file__), 'lib')\nif dirpath not in sys.path:\n    sys.path.append(dirpath)\n\nimport sqlparse\n\nfrom sqlparse.sql import IdentifierList, Identifier, Function\nfrom sqlparse.tokens import Keyword, DML\n\n\nclass Reference(namedtuple('Reference', ['schema', 'name', 'alias', 'is_function'])):\n    __slots__ = ()\n\n    def has_alias(self):\n        return self.alias is not None\n\n    @property\n    def is_query_alias(self):\n        return self.name is None and self.alias is not None\n\n    @property\n    def is_table_alias(self):\n        return self.name is not None and self.alias is not None and not self.is_function\n\n    @property\n    def full_name(self):\n        if self.schema is None:\n            return self.name\n        else:\n            return self.schema + '.' + self.name\n\n\ndef _is_subselect(parsed):\n    if not parsed.is_group:\n        return False\n    for item in parsed.tokens:\n        if item.ttype is DML and item.value.upper() in ('SELECT', 'INSERT',\n                                                        'UPDATE', 'CREATE', 'DELETE'):\n            return True\n    return False\n\n\ndef _identifier_is_function(identifier):\n    return any(isinstance(t, Function) for t in identifier.tokens)\n\n\ndef _extract_from_part(parsed):\n    tbl_prefix_seen = False\n    for item in parsed.tokens:\n        if item.is_group:\n            for x in _extract_from_part(item):\n                yield x\n        if tbl_prefix_seen:\n            if _is_subselect(item):\n                for x in _extract_from_part(item):\n                    yield x\n            # An incomplete nested select won't be recognized correctly as a\n            # sub-select. eg: 'SELECT * FROM (SELECT id FROM user'. This causes\n            # the second FROM to trigger this elif condition resulting in a\n            # StopIteration. So we need to ignore the keyword if the keyword\n            # FROM.\n            # Also 'SELECT * FROM abc JOIN def' will trigger this elif\n            # condition. So we need to ignore the keyword JOIN and its variants\n            # INNER JOIN, FULL OUTER JOIN, etc.\n            elif item.ttype is Keyword and (\n                    not item.value.upper() == 'FROM') and (\n                    not item.value.upper().endswith('JOIN')):\n                tbl_prefix_seen = False\n            else:\n                yield item\n        elif item.ttype is Keyword or item.ttype is Keyword.DML:\n            item_val = item.value.upper()\n            if (item_val in ('COPY', 'FROM', 'INTO', 'UPDATE', 'TABLE') or\n                    item_val.endswith('JOIN')):\n                tbl_prefix_seen = True\n        # 'SELECT a, FROM abc' will detect FROM as part of the column list.\n        # So this check here is necessary.\n        elif isinstance(item, IdentifierList):\n            for identifier in item.get_identifiers():\n                if (identifier.ttype is Keyword and\n                        identifier.value.upper() == 'FROM'):\n                    tbl_prefix_seen = True\n                    break\n\n\ndef _extract_table_identifiers(token_stream):\n    for item in token_stream:\n        if isinstance(item, IdentifierList):\n            for ident in item.get_identifiers():\n                try:\n                    alias = ident.get_alias()\n                    schema_name = ident.get_parent_name()\n                    real_name = ident.get_real_name()\n                except AttributeError:\n                    continue\n                if real_name:\n                    yield Reference(schema_name, real_name,\n                                    alias, _identifier_is_function(ident))\n        elif isinstance(item, Identifier):\n            yield Reference(item.get_parent_name(), item.get_real_name(),\n                            item.get_alias(), _identifier_is_function(item))\n        elif isinstance(item, Function):\n            yield Reference(item.get_parent_name(), item.get_real_name(),\n                            item.get_alias(), _identifier_is_function(item))\n\n\ndef extractTables(sql):\n    # let's handle multiple statements in one sql string\n    extracted_tables = []\n    statements = list(sqlparse.parse(sql))\n    for statement in statements:\n        stream = _extract_from_part(statement)\n        extracted_tables.append(list(_extract_table_identifiers(stream)))\n    return list(itertools.chain(*extracted_tables))\n"
  },
  {
    "path": "SQLToolsAPI/README.md",
    "content": "## SQLTools API for plugins - v0.2.5\n\nDocs will be ready soon\n"
  },
  {
    "path": "SQLToolsAPI/Storage.py",
    "content": "import os\nimport shutil\nfrom . import Utils as U\n\n__version__ = \"v0.1.0\"\n\n\nclass Storage:\n    def __init__(self, filename, default=None):\n        self.storageFile = filename\n        self.defaultFile = default\n        self.items = {}\n\n        # copy entire file, to keep comments\n        # if not os.path.isfile(filename) and default and os.path.isfile(default):\n        #     shutil.copyfile(default, filename)\n\n        self.all()\n\n    def all(self):\n        userFile = self.getFilename()\n\n        if os.path.exists(userFile):\n            self.items = U.parseJson(self.getFilename())\n        else:\n            self.items = {}\n\n        return U.merge(self.items, self.defaults())\n\n    def write(self):\n        return U.saveJson(self.items if isinstance(self.items, dict) else {}, self.getFilename())\n\n    def add(self, key, value):\n        if len(key) <= 0:\n            return\n\n        self.all()\n\n        if isinstance(value, str):\n            value = [value]\n\n        self.items[key] = '\\n'.join(value)\n        self.write()\n\n    def delete(self, key):\n        if len(key) <= 0:\n            return\n\n        self.all()\n        self.items.pop(key)\n        self.write()\n\n    def get(self, key, default=None):\n        if len(key) <= 0:\n            return\n\n        items = self.all()\n        return items[key] if key in items else default\n\n    def getFilename(self):\n        return self.storageFile\n\n    def defaults(self):\n        if self.defaultFile and os.path.isfile(self.defaultFile):\n            return U.parseJson(self.defaultFile)\n        return {}\n\n\nclass Settings(Storage):\n    pass\n"
  },
  {
    "path": "SQLToolsAPI/Utils.py",
    "content": "__version__ = \"v0.2.0\"\n\nimport json\nimport os\nimport re\nimport sys\n\ndirpath = os.path.join(os.path.dirname(__file__), 'lib')\nif dirpath not in sys.path:\n    sys.path.append(dirpath)\n\nimport sqlparse\n\n# Regular expression for comments\ncomment_re = re.compile(\n    '(^)?[^\\S\\n]*/(?:\\*(.*?)\\*/[^\\S\\n]*|/[^\\n]*)($)?',\n    re.DOTALL | re.MULTILINE\n)\n\n\ndef parseJson(filename):\n    \"\"\" Parse a JSON file\n        First remove comments and then use the json module package\n        Comments look like :\n            // ...\n        or\n            /*\n            ...\n            */\n    \"\"\"\n\n    with open(filename, mode='r', encoding='utf-8') as f:\n        content = ''.join(f.readlines())\n\n        # Looking for comments\n        match = comment_re.search(content)\n        while match:\n            # single line comment\n            content = content[:match.start()] + content[match.end():]\n            match = comment_re.search(content)\n\n        # remove trailing commas\n        content = re.sub(r',([ \\t\\r\\n]+)}', r'\\1}', content)\n        content = re.sub(r',([ \\t\\r\\n]+)\\]', r'\\1]', content)\n\n        # Return json file\n        return json.loads(content, encoding='utf-8')\n\n\ndef saveJson(content, filename):\n    with open(filename, mode='w', encoding='utf-8') as outfile:\n        json.dump(content, outfile,\n                  sort_keys=True, indent=2, separators=(',', ': '))\n\n\ndef getResultAsList(results):\n    resultList = []\n    for result in results.splitlines():\n        lineResult = ''\n        for element in result.strip('|').split('|'):\n            lineResult += element.strip()\n        if lineResult:\n            resultList.append(lineResult)\n    return resultList\n\n\ndef formatSql(raw, settings):\n    try:\n        result = sqlparse.format(raw, **settings)\n\n        return result\n    except Exception:\n        return None\n\n\ndef merge(source, destination):\n    \"\"\"\n    run me with nosetests --with-doctest file.py\n\n    >>> a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }\n    >>> b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }\n    >>> merge(b, a) == { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }\n    True\n    \"\"\"\n    for key, value in source.items():\n        if isinstance(value, dict):\n            # get node or create one\n            node = destination.setdefault(key, {})\n            merge(value, node)\n        else:\n            destination[key] = value\n\n    return destination\n"
  },
  {
    "path": "SQLToolsAPI/__init__.py",
    "content": "__version__ = \"v0.3.0\"\n\n\n__all__ = [\n    'Utils',\n    'Completion',\n    'Command',\n    'Connection',\n    'History',\n    'Storage',\n    'Settings'\n]\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\n\"\"\"Parse SQL statements.\"\"\"\n\n# Setup namespace\nfrom sqlparse import sql\nfrom sqlparse import cli\nfrom sqlparse import engine\nfrom sqlparse import tokens\nfrom sqlparse import filters\nfrom sqlparse import formatter\n\nfrom sqlparse.compat import text_type\n\n__version__ = '0.2.3'\n__all__ = ['engine', 'filters', 'formatter', 'sql', 'tokens', 'cli']\n\n\ndef parse(sql, encoding=None):\n    \"\"\"Parse sql and return a list of statements.\n\n    :param sql: A string containing one or more SQL statements.\n    :param encoding: The encoding of the statement (optional).\n    :returns: A tuple of :class:`~sqlparse.sql.Statement` instances.\n    \"\"\"\n    return tuple(parsestream(sql, encoding))\n\n\ndef parsestream(stream, encoding=None):\n    \"\"\"Parses sql statements from file-like object.\n\n    :param stream: A file-like object.\n    :param encoding: The encoding of the stream contents (optional).\n    :returns: A generator of :class:`~sqlparse.sql.Statement` instances.\n    \"\"\"\n    stack = engine.FilterStack()\n    stack.enable_grouping()\n    return stack.run(stream, encoding)\n\n\ndef format(sql, encoding=None, **options):\n    \"\"\"Format *sql* according to *options*.\n\n    Available options are documented in :ref:`formatting`.\n\n    In addition to the formatting options this function accepts the\n    keyword \"encoding\" which determines the encoding of the statement.\n\n    :returns: The formatted SQL statement as string.\n    \"\"\"\n    stack = engine.FilterStack()\n    options = formatter.validate_options(options)\n    stack = formatter.build_filter_stack(stack, options)\n    stack.postprocess.append(filters.SerializerUnicode())\n    return u''.join(stack.run(sql, encoding))\n\n\ndef split(sql, encoding=None):\n    \"\"\"Split *sql* into single statements.\n\n    :param sql: A string containing one or more SQL statements.\n    :param encoding: The encoding of the statement (optional).\n    :returns: A list of strings.\n    \"\"\"\n    stack = engine.FilterStack()\n    return [text_type(stmt).strip() for stmt in stack.run(sql, encoding)]\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/__main__.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\n\"\"\"Entrypoint module for `python -m sqlparse`.\n\nWhy does this file exist, and why __main__? For more info, read:\n- https://www.python.org/dev/peps/pep-0338/\n- https://docs.python.org/2/using/cmdline.html#cmdoption-m\n- https://docs.python.org/3/using/cmdline.html#cmdoption-m\n\"\"\"\n\nimport sys\n\nfrom sqlparse.cli import main\n\nif __name__ == '__main__':\n    sys.exit(main())\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/cli.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\n\"\"\"Module that contains the command line app.\n\nWhy does this file exist, and why not put this in __main__?\n  You might be tempted to import things from __main__ later, but that will\n  cause problems: the code will get executed twice:\n  - When you run `python -m sqlparse` python will execute\n    ``__main__.py`` as a script. That means there won't be any\n    ``sqlparse.__main__`` in ``sys.modules``.\n  - When you import __main__ it will get executed again (as a module) because\n    there's no ``sqlparse.__main__`` in ``sys.modules``.\n  Also see (1) from http://click.pocoo.org/5/setuptools/#setuptools-integration\n\"\"\"\n\nimport argparse\nimport sys\nfrom io import TextIOWrapper\nfrom codecs import open, getreader\n\nimport sqlparse\nfrom sqlparse.compat import PY2\nfrom sqlparse.exceptions import SQLParseError\n\n\n# TODO: Add CLI Tests\n# TODO: Simplify formatter by using argparse `type` arguments\ndef create_parser():\n    _CASE_CHOICES = ['upper', 'lower', 'capitalize']\n\n    parser = argparse.ArgumentParser(\n        prog='sqlformat',\n        description='Format FILE according to OPTIONS. Use \"-\" as FILE '\n                    'to read from stdin.',\n        usage='%(prog)s  [OPTIONS] FILE, ...',\n    )\n\n    parser.add_argument('filename')\n\n    parser.add_argument(\n        '-o', '--outfile',\n        dest='outfile',\n        metavar='FILE',\n        help='write output to FILE (defaults to stdout)')\n\n    parser.add_argument(\n        '--version',\n        action='version',\n        version=sqlparse.__version__)\n\n    group = parser.add_argument_group('Formatting Options')\n\n    group.add_argument(\n        '-k', '--keywords',\n        metavar='CHOICE',\n        dest='keyword_case',\n        choices=_CASE_CHOICES,\n        help='change case of keywords, CHOICE is one of {0}'.format(\n            ', '.join('\"{0}\"'.format(x) for x in _CASE_CHOICES)))\n\n    group.add_argument(\n        '-i', '--identifiers',\n        metavar='CHOICE',\n        dest='identifier_case',\n        choices=_CASE_CHOICES,\n        help='change case of identifiers, CHOICE is one of {0}'.format(\n            ', '.join('\"{0}\"'.format(x) for x in _CASE_CHOICES)))\n\n    group.add_argument(\n        '-l', '--language',\n        metavar='LANG',\n        dest='output_format',\n        choices=['python', 'php'],\n        help='output a snippet in programming language LANG, '\n             'choices are \"python\", \"php\"')\n\n    group.add_argument(\n        '--strip-comments',\n        dest='strip_comments',\n        action='store_true',\n        default=False,\n        help='remove comments')\n\n    group.add_argument(\n        '-r', '--reindent',\n        dest='reindent',\n        action='store_true',\n        default=False,\n        help='reindent statements')\n\n    group.add_argument(\n        '--indent_width',\n        dest='indent_width',\n        default=2,\n        type=int,\n        help='indentation width (defaults to 2 spaces)')\n\n    group.add_argument(\n        '-a', '--reindent_aligned',\n        action='store_true',\n        default=False,\n        help='reindent statements to aligned format')\n\n    group.add_argument(\n        '-s', '--use_space_around_operators',\n        action='store_true',\n        default=False,\n        help='place spaces around mathematical operators')\n\n    group.add_argument(\n        '--wrap_after',\n        dest='wrap_after',\n        default=0,\n        type=int,\n        help='Column after which lists should be wrapped')\n\n    group.add_argument(\n        '--comma_first',\n        dest='comma_first',\n        default=False,\n        type=bool,\n        help='Insert linebreak before comma (default False)')\n\n    group.add_argument(\n        '--encoding',\n        dest='encoding',\n        default='utf-8',\n        help='Specify the input encoding (default utf-8)')\n\n    return parser\n\n\ndef _error(msg):\n    \"\"\"Print msg and optionally exit with return code exit_.\"\"\"\n    sys.stderr.write(u'[ERROR] {0}\\n'.format(msg))\n    return 1\n\n\ndef main(args=None):\n    parser = create_parser()\n    args = parser.parse_args(args)\n\n    if args.filename == '-':  # read from stdin\n        if PY2:\n            data = getreader(args.encoding)(sys.stdin).read()\n        else:\n            data = TextIOWrapper(\n                sys.stdin.buffer, encoding=args.encoding).read()\n    else:\n        try:\n            data = ''.join(open(args.filename, 'r', args.encoding).readlines())\n        except IOError as e:\n            return _error(\n                u'Failed to read {0}: {1}'.format(args.filename, e))\n\n    if args.outfile:\n        try:\n            stream = open(args.outfile, 'w', args.encoding)\n        except IOError as e:\n            return _error(u'Failed to open {0}: {1}'.format(args.outfile, e))\n    else:\n        stream = sys.stdout\n\n    formatter_opts = vars(args)\n    try:\n        formatter_opts = sqlparse.formatter.validate_options(formatter_opts)\n    except SQLParseError as e:\n        return _error(u'Invalid options: {0}'.format(e))\n\n    s = sqlparse.format(data, **formatter_opts)\n    stream.write(s)\n    stream.flush()\n    return 0\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/compat.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\n\"\"\"Python 2/3 compatibility.\n\nThis module only exists to avoid a dependency on six\nfor very trivial stuff. We only need to take care of\nstring types, buffers and metaclasses.\n\nParts of the code is copied directly from six:\nhttps://bitbucket.org/gutworth/six\n\"\"\"\n\nimport sys\nfrom io import TextIOBase\n\nPY2 = sys.version_info[0] == 2\nPY3 = sys.version_info[0] == 3\n\n\nif PY3:\n    def unicode_compatible(cls):\n        return cls\n\n    bytes_type = bytes\n    text_type = str\n    string_types = (str,)\n    from io import StringIO\n    file_types = (StringIO, TextIOBase)\n\n\nelif PY2:\n    def unicode_compatible(cls):\n        cls.__unicode__ = cls.__str__\n        cls.__str__ = lambda x: x.__unicode__().encode('utf-8')\n        return cls\n\n    bytes_type = str\n    text_type = unicode\n    string_types = (str, unicode,)\n    from StringIO import StringIO\n    file_types = (file, StringIO, TextIOBase)\n    from StringIO import StringIO\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/engine/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\nfrom sqlparse.engine import grouping\nfrom sqlparse.engine.filter_stack import FilterStack\nfrom sqlparse.engine.statement_splitter import StatementSplitter\n\n__all__ = [\n    'grouping',\n    'FilterStack',\n    'StatementSplitter',\n]\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/engine/filter_stack.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\n\"\"\"filter\"\"\"\n\nfrom sqlparse import lexer\nfrom sqlparse.engine import grouping\nfrom sqlparse.engine.statement_splitter import StatementSplitter\n\n\nclass FilterStack(object):\n    def __init__(self):\n        self.preprocess = []\n        self.stmtprocess = []\n        self.postprocess = []\n        self._grouping = False\n\n    def enable_grouping(self):\n        self._grouping = True\n\n    def run(self, sql, encoding=None):\n        stream = lexer.tokenize(sql, encoding)\n        # Process token stream\n        for filter_ in self.preprocess:\n            stream = filter_.process(stream)\n\n        stream = StatementSplitter().process(stream)\n\n        # Output: Stream processed Statements\n        for stmt in stream:\n            if self._grouping:\n                stmt = grouping.group(stmt)\n\n            for filter_ in self.stmtprocess:\n                filter_.process(stmt)\n\n            for filter_ in self.postprocess:\n                stmt = filter_.process(stmt)\n\n            yield stmt\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/engine/grouping.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\nfrom sqlparse import sql\nfrom sqlparse import tokens as T\nfrom sqlparse.utils import recurse, imt\n\nT_NUMERICAL = (T.Number, T.Number.Integer, T.Number.Float)\nT_STRING = (T.String, T.String.Single, T.String.Symbol)\nT_NAME = (T.Name, T.Name.Placeholder)\n\n\ndef _group_matching(tlist, cls):\n    \"\"\"Groups Tokens that have beginning and end.\"\"\"\n    opens = []\n    tidx_offset = 0\n    for idx, token in enumerate(list(tlist)):\n        tidx = idx - tidx_offset\n\n        if token.is_whitespace:\n            # ~50% of tokens will be whitespace. Will checking early\n            # for them avoid 3 comparisons, but then add 1 more comparison\n            # for the other ~50% of tokens...\n            continue\n\n        if token.is_group and not isinstance(token, cls):\n            # Check inside previously grouped (ie. parenthesis) if group\n            # of differnt type is inside (ie, case). though ideally  should\n            # should check for all open/close tokens at once to avoid recursion\n            _group_matching(token, cls)\n            continue\n\n        if token.match(*cls.M_OPEN):\n            opens.append(tidx)\n\n        elif token.match(*cls.M_CLOSE):\n            try:\n                open_idx = opens.pop()\n            except IndexError:\n                # this indicates invalid sql and unbalanced tokens.\n                # instead of break, continue in case other \"valid\" groups exist\n                continue\n            close_idx = tidx\n            tlist.group_tokens(cls, open_idx, close_idx)\n            tidx_offset += close_idx - open_idx\n\n\ndef group_brackets(tlist):\n    _group_matching(tlist, sql.SquareBrackets)\n\n\ndef group_parenthesis(tlist):\n    _group_matching(tlist, sql.Parenthesis)\n\n\ndef group_case(tlist):\n    _group_matching(tlist, sql.Case)\n\n\ndef group_if(tlist):\n    _group_matching(tlist, sql.If)\n\n\ndef group_for(tlist):\n    _group_matching(tlist, sql.For)\n\n\ndef group_begin(tlist):\n    _group_matching(tlist, sql.Begin)\n\n\ndef group_typecasts(tlist):\n    def match(token):\n        return token.match(T.Punctuation, '::')\n\n    def valid(token):\n        return token is not None\n\n    def post(tlist, pidx, tidx, nidx):\n        return pidx, nidx\n\n    valid_prev = valid_next = valid\n    _group(tlist, sql.Identifier, match, valid_prev, valid_next, post)\n\n\ndef group_period(tlist):\n    def match(token):\n        return token.match(T.Punctuation, '.')\n\n    def valid_prev(token):\n        sqlcls = sql.SquareBrackets, sql.Identifier\n        ttypes = T.Name, T.String.Symbol\n        return imt(token, i=sqlcls, t=ttypes)\n\n    def valid_next(token):\n        # issue261, allow invalid next token\n        return True\n\n    def post(tlist, pidx, tidx, nidx):\n        # next_ validation is being performed here. issue261\n        sqlcls = sql.SquareBrackets, sql.Function\n        ttypes = T.Name, T.String.Symbol, T.Wildcard\n        next_ = tlist[nidx] if nidx is not None else None\n        valid_next = imt(next_, i=sqlcls, t=ttypes)\n\n        return (pidx, nidx) if valid_next else (pidx, tidx)\n\n    _group(tlist, sql.Identifier, match, valid_prev, valid_next, post)\n\n\ndef group_as(tlist):\n    def match(token):\n        return token.is_keyword and token.normalized == 'AS'\n\n    def valid_prev(token):\n        return token.normalized == 'NULL' or not token.is_keyword\n\n    def valid_next(token):\n        ttypes = T.DML, T.DDL\n        return not imt(token, t=ttypes) and token is not None\n\n    def post(tlist, pidx, tidx, nidx):\n        return pidx, nidx\n\n    _group(tlist, sql.Identifier, match, valid_prev, valid_next, post)\n\n\ndef group_assignment(tlist):\n    def match(token):\n        return token.match(T.Assignment, ':=')\n\n    def valid(token):\n        return token is not None\n\n    def post(tlist, pidx, tidx, nidx):\n        m_semicolon = T.Punctuation, ';'\n        snidx, _ = tlist.token_next_by(m=m_semicolon, idx=nidx)\n        nidx = snidx or nidx\n        return pidx, nidx\n\n    valid_prev = valid_next = valid\n    _group(tlist, sql.Assignment, match, valid_prev, valid_next, post)\n\n\ndef group_comparison(tlist):\n    sqlcls = (sql.Parenthesis, sql.Function, sql.Identifier,\n              sql.Operation)\n    ttypes = T_NUMERICAL + T_STRING + T_NAME\n\n    def match(token):\n        return token.ttype == T.Operator.Comparison\n\n    def valid(token):\n        if imt(token, t=ttypes, i=sqlcls):\n            return True\n        elif token and token.is_keyword and token.normalized == 'NULL':\n            return True\n        else:\n            return False\n\n    def post(tlist, pidx, tidx, nidx):\n        return pidx, nidx\n\n    valid_prev = valid_next = valid\n    _group(tlist, sql.Comparison, match,\n           valid_prev, valid_next, post, extend=False)\n\n\n@recurse(sql.Identifier)\ndef group_identifier(tlist):\n    ttypes = (T.String.Symbol, T.Name)\n\n    tidx, token = tlist.token_next_by(t=ttypes)\n    while token:\n        tlist.group_tokens(sql.Identifier, tidx, tidx)\n        tidx, token = tlist.token_next_by(t=ttypes, idx=tidx)\n\n\ndef group_arrays(tlist):\n    sqlcls = sql.SquareBrackets, sql.Identifier, sql.Function\n    ttypes = T.Name, T.String.Symbol\n\n    def match(token):\n        return isinstance(token, sql.SquareBrackets)\n\n    def valid_prev(token):\n        return imt(token, i=sqlcls, t=ttypes)\n\n    def valid_next(token):\n        return True\n\n    def post(tlist, pidx, tidx, nidx):\n        return pidx, tidx\n\n    _group(tlist, sql.Identifier, match,\n           valid_prev, valid_next, post, extend=True, recurse=False)\n\n\ndef group_operator(tlist):\n    ttypes = T_NUMERICAL + T_STRING + T_NAME\n    sqlcls = (sql.SquareBrackets, sql.Parenthesis, sql.Function,\n              sql.Identifier, sql.Operation)\n\n    def match(token):\n        return imt(token, t=(T.Operator, T.Wildcard))\n\n    def valid(token):\n        return imt(token, i=sqlcls, t=ttypes)\n\n    def post(tlist, pidx, tidx, nidx):\n        tlist[tidx].ttype = T.Operator\n        return pidx, nidx\n\n    valid_prev = valid_next = valid\n    _group(tlist, sql.Operation, match,\n           valid_prev, valid_next, post, extend=False)\n\n\ndef group_identifier_list(tlist):\n    m_role = T.Keyword, ('null', 'role')\n    sqlcls = (sql.Function, sql.Case, sql.Identifier, sql.Comparison,\n              sql.IdentifierList, sql.Operation)\n    ttypes = (T_NUMERICAL + T_STRING + T_NAME +\n              (T.Keyword, T.Comment, T.Wildcard))\n\n    def match(token):\n        return token.match(T.Punctuation, ',')\n\n    def valid(token):\n        return imt(token, i=sqlcls, m=m_role, t=ttypes)\n\n    def post(tlist, pidx, tidx, nidx):\n        return pidx, nidx\n\n    valid_prev = valid_next = valid\n    _group(tlist, sql.IdentifierList, match,\n           valid_prev, valid_next, post, extend=True)\n\n\n@recurse(sql.Comment)\ndef group_comments(tlist):\n    tidx, token = tlist.token_next_by(t=T.Comment)\n    while token:\n        eidx, end = tlist.token_not_matching(\n            lambda tk: imt(tk, t=T.Comment) or tk.is_whitespace, idx=tidx)\n        if end is not None:\n            eidx, end = tlist.token_prev(eidx, skip_ws=False)\n            tlist.group_tokens(sql.Comment, tidx, eidx)\n\n        tidx, token = tlist.token_next_by(t=T.Comment, idx=tidx)\n\n\n@recurse(sql.Where)\ndef group_where(tlist):\n    tidx, token = tlist.token_next_by(m=sql.Where.M_OPEN)\n    while token:\n        eidx, end = tlist.token_next_by(m=sql.Where.M_CLOSE, idx=tidx)\n\n        if end is None:\n            end = tlist._groupable_tokens[-1]\n        else:\n            end = tlist.tokens[eidx - 1]\n        # TODO: convert this to eidx instead of end token.\n        # i think above values are len(tlist) and eidx-1\n        eidx = tlist.token_index(end)\n        tlist.group_tokens(sql.Where, tidx, eidx)\n        tidx, token = tlist.token_next_by(m=sql.Where.M_OPEN, idx=tidx)\n\n\n@recurse()\ndef group_aliased(tlist):\n    I_ALIAS = (sql.Parenthesis, sql.Function, sql.Case, sql.Identifier,\n               sql.Operation)\n\n    tidx, token = tlist.token_next_by(i=I_ALIAS, t=T.Number)\n    while token:\n        nidx, next_ = tlist.token_next(tidx)\n        if isinstance(next_, sql.Identifier):\n            tlist.group_tokens(sql.Identifier, tidx, nidx, extend=True)\n        tidx, token = tlist.token_next_by(i=I_ALIAS, t=T.Number, idx=tidx)\n\n\n@recurse(sql.Function)\ndef group_functions(tlist):\n    has_create = False\n    has_table = False\n    for tmp_token in tlist.tokens:\n        if tmp_token.value == 'CREATE':\n            has_create = True\n        if tmp_token.value == 'TABLE':\n            has_table = True\n    if has_create and has_table:\n        return\n\n    tidx, token = tlist.token_next_by(t=T.Name)\n    while token:\n        nidx, next_ = tlist.token_next(tidx)\n        if isinstance(next_, sql.Parenthesis):\n            tlist.group_tokens(sql.Function, tidx, nidx)\n        tidx, token = tlist.token_next_by(t=T.Name, idx=tidx)\n\n\ndef group_order(tlist):\n    \"\"\"Group together Identifier and Asc/Desc token\"\"\"\n    tidx, token = tlist.token_next_by(t=T.Keyword.Order)\n    while token:\n        pidx, prev_ = tlist.token_prev(tidx)\n        if imt(prev_, i=sql.Identifier, t=T.Number):\n            tlist.group_tokens(sql.Identifier, pidx, tidx)\n            tidx = pidx\n        tidx, token = tlist.token_next_by(t=T.Keyword.Order, idx=tidx)\n\n\n@recurse()\ndef align_comments(tlist):\n    tidx, token = tlist.token_next_by(i=sql.Comment)\n    while token:\n        pidx, prev_ = tlist.token_prev(tidx)\n        if isinstance(prev_, sql.TokenList):\n            tlist.group_tokens(sql.TokenList, pidx, tidx, extend=True)\n            tidx = pidx\n        tidx, token = tlist.token_next_by(i=sql.Comment, idx=tidx)\n\n\ndef group(stmt):\n    for func in [\n        group_comments,\n\n        # _group_matching\n        group_brackets,\n        group_parenthesis,\n        group_case,\n        group_if,\n        group_for,\n        group_begin,\n\n        group_functions,\n        group_where,\n        group_period,\n        group_arrays,\n        group_identifier,\n        group_order,\n        group_typecasts,\n        group_operator,\n        group_as,\n        group_aliased,\n        group_assignment,\n        group_comparison,\n\n        align_comments,\n        group_identifier_list,\n    ]:\n        func(stmt)\n    return stmt\n\n\ndef _group(tlist, cls, match,\n           valid_prev=lambda t: True,\n           valid_next=lambda t: True,\n           post=None,\n           extend=True,\n           recurse=True\n           ):\n    \"\"\"Groups together tokens that are joined by a middle token. ie. x < y\"\"\"\n\n    tidx_offset = 0\n    pidx, prev_ = None, None\n    for idx, token in enumerate(list(tlist)):\n        tidx = idx - tidx_offset\n\n        if token.is_whitespace:\n            continue\n\n        if recurse and token.is_group and not isinstance(token, cls):\n            _group(token, cls, match, valid_prev, valid_next, post, extend)\n\n        if match(token):\n            nidx, next_ = tlist.token_next(tidx)\n            if prev_ and valid_prev(prev_) and valid_next(next_):\n                from_idx, to_idx = post(tlist, pidx, tidx, nidx)\n                grp = tlist.group_tokens(cls, from_idx, to_idx, extend=extend)\n\n                tidx_offset += to_idx - from_idx\n                pidx, prev_ = from_idx, grp\n                continue\n\n        pidx, prev_ = tidx, token\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/engine/statement_splitter.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\nfrom sqlparse import sql, tokens as T\n\n\nclass StatementSplitter(object):\n    \"\"\"Filter that split stream at individual statements\"\"\"\n\n    def __init__(self):\n        self._reset()\n\n    def _reset(self):\n        \"\"\"Set the filter attributes to its default values\"\"\"\n        self._in_declare = False\n        self._is_create = False\n        self._begin_depth = 0\n\n        self.consume_ws = False\n        self.tokens = []\n        self.level = 0\n\n    def _change_splitlevel(self, ttype, value):\n        \"\"\"Get the new split level (increase, decrease or remain equal)\"\"\"\n        # ANSI\n        # if normal token return\n        # wouldn't parenthesis increase/decrease a level?\n        # no, inside a paranthesis can't start new statement\n        if ttype not in T.Keyword:\n            return 0\n\n        # Everything after here is ttype = T.Keyword\n        # Also to note, once entered an If statement you are done and basically\n        # returning\n        unified = value.upper()\n\n        # three keywords begin with CREATE, but only one of them is DDL\n        # DDL Create though can contain more words such as \"or replace\"\n        if ttype is T.Keyword.DDL and unified.startswith('CREATE'):\n            self._is_create = True\n            return 0\n\n        # can have nested declare inside of being...\n        if unified == 'DECLARE' and self._is_create and self._begin_depth == 0:\n            self._in_declare = True\n            return 1\n\n        if unified == 'BEGIN':\n            self._begin_depth += 1\n            if self._is_create:\n                # FIXME(andi): This makes no sense.\n                return 1\n            return 0\n\n        # Should this respect a preceeding BEGIN?\n        # In CASE ... WHEN ... END this results in a split level -1.\n        # Would having multiple CASE WHEN END and a Assigment Operator\n        # cause the statement to cut off prematurely?\n        if unified == 'END':\n            self._begin_depth = max(0, self._begin_depth - 1)\n            return -1\n\n        if (unified in ('IF', 'FOR', 'WHILE') and\n                self._is_create and self._begin_depth > 0):\n            return 1\n\n        if unified in ('END IF', 'END FOR', 'END WHILE'):\n            return -1\n\n        # Default\n        return 0\n\n    def process(self, stream):\n        \"\"\"Process the stream\"\"\"\n        EOS_TTYPE = T.Whitespace, T.Comment.Single\n\n        # Run over all stream tokens\n        for ttype, value in stream:\n            # Yield token if we finished a statement and there's no whitespaces\n            # It will count newline token as a non whitespace. In this context\n            # whitespace ignores newlines.\n            # why don't multi line comments also count?\n            if self.consume_ws and ttype not in EOS_TTYPE:\n                yield sql.Statement(self.tokens)\n\n                # Reset filter and prepare to process next statement\n                self._reset()\n\n            # Change current split level (increase, decrease or remain equal)\n            self.level += self._change_splitlevel(ttype, value)\n\n            # Append the token to the current statement\n            self.tokens.append(sql.Token(ttype, value))\n\n            # Check if we get the end of a statement\n            if self.level <= 0 and ttype is T.Punctuation and value == ';':\n                self.consume_ws = True\n\n        # Yield pending statement (if any)\n        if self.tokens:\n            yield sql.Statement(self.tokens)\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/exceptions.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\n\"\"\"Exceptions used in this package.\"\"\"\n\n\nclass SQLParseError(Exception):\n    \"\"\"Base class for exceptions in this module.\"\"\"\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/filters/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\nfrom sqlparse.filters.others import SerializerUnicode\nfrom sqlparse.filters.others import StripCommentsFilter\nfrom sqlparse.filters.others import StripWhitespaceFilter\nfrom sqlparse.filters.others import SpacesAroundOperatorsFilter\n\nfrom sqlparse.filters.output import OutputPHPFilter\nfrom sqlparse.filters.output import OutputPythonFilter\n\nfrom sqlparse.filters.tokens import KeywordCaseFilter\nfrom sqlparse.filters.tokens import IdentifierCaseFilter\nfrom sqlparse.filters.tokens import TruncateStringFilter\n\nfrom sqlparse.filters.reindent import ReindentFilter\nfrom sqlparse.filters.right_margin import RightMarginFilter\nfrom sqlparse.filters.aligned_indent import AlignedIndentFilter\n\n__all__ = [\n    'SerializerUnicode',\n    'StripCommentsFilter',\n    'StripWhitespaceFilter',\n    'SpacesAroundOperatorsFilter',\n\n    'OutputPHPFilter',\n    'OutputPythonFilter',\n\n    'KeywordCaseFilter',\n    'IdentifierCaseFilter',\n    'TruncateStringFilter',\n\n    'ReindentFilter',\n    'RightMarginFilter',\n    'AlignedIndentFilter',\n]\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/filters/aligned_indent.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\nfrom sqlparse import sql, tokens as T\nfrom sqlparse.compat import text_type\nfrom sqlparse.utils import offset, indent\n\n\nclass AlignedIndentFilter(object):\n    join_words = (r'((LEFT\\s+|RIGHT\\s+|FULL\\s+)?'\n                  r'(INNER\\s+|OUTER\\s+|STRAIGHT\\s+)?|'\n                  r'(CROSS\\s+|NATURAL\\s+)?)?JOIN\\b')\n    split_words = ('FROM',\n                   join_words, 'ON',\n                   'WHERE', 'AND', 'OR',\n                   'GROUP', 'HAVING', 'LIMIT',\n                   'ORDER', 'UNION', 'VALUES',\n                   'SET', 'BETWEEN', 'EXCEPT')\n\n    def __init__(self, char=' ', n='\\n'):\n        self.n = n\n        self.offset = 0\n        self.indent = 0\n        self.char = char\n        self._max_kwd_len = len('select')\n\n    def nl(self, offset=1):\n        # offset = 1 represent a single space after SELECT\n        offset = -len(offset) if not isinstance(offset, int) else offset\n        # add two for the space and parens\n        indent = self.indent * (2 + self._max_kwd_len)\n\n        return sql.Token(T.Whitespace, self.n + self.char * (\n            self._max_kwd_len + offset + indent + self.offset))\n\n    def _process_statement(self, tlist):\n        if tlist.tokens[0].is_whitespace and self.indent == 0:\n            tlist.tokens.pop(0)\n\n        # process the main query body\n        self._process(sql.TokenList(tlist.tokens))\n\n    def _process_parenthesis(self, tlist):\n        # if this isn't a subquery, don't re-indent\n        _, token = tlist.token_next_by(m=(T.DML, 'SELECT'))\n        if token is not None:\n            with indent(self):\n                tlist.insert_after(tlist[0], self.nl('SELECT'))\n                # process the inside of the parantheses\n                self._process_default(tlist)\n\n            # de-indent last parenthesis\n            tlist.insert_before(tlist[-1], self.nl())\n\n    def _process_identifierlist(self, tlist):\n        # columns being selected\n        identifiers = list(tlist.get_identifiers())\n        identifiers.pop(0)\n        [tlist.insert_before(token, self.nl()) for token in identifiers]\n        self._process_default(tlist)\n\n    def _process_case(self, tlist):\n        offset_ = len('case ') + len('when ')\n        cases = tlist.get_cases(skip_ws=True)\n        # align the end as well\n        end_token = tlist.token_next_by(m=(T.Keyword, 'END'))[1]\n        cases.append((None, [end_token]))\n\n        condition_width = [len(' '.join(map(text_type, cond))) if cond else 0\n                           for cond, _ in cases]\n        max_cond_width = max(condition_width)\n\n        for i, (cond, value) in enumerate(cases):\n            # cond is None when 'else or end'\n            stmt = cond[0] if cond else value[0]\n\n            if i > 0:\n                tlist.insert_before(stmt, self.nl(\n                    offset_ - len(text_type(stmt))))\n            if cond:\n                ws = sql.Token(T.Whitespace, self.char * (\n                    max_cond_width - condition_width[i]))\n                tlist.insert_after(cond[-1], ws)\n\n    def _next_token(self, tlist, idx=-1):\n        split_words = T.Keyword, self.split_words, True\n        tidx, token = tlist.token_next_by(m=split_words, idx=idx)\n        # treat \"BETWEEN x and y\" as a single statement\n        if token and token.normalized == 'BETWEEN':\n            tidx, token = self._next_token(tlist, tidx)\n            if token and token.normalized == 'AND':\n                tidx, token = self._next_token(tlist, tidx)\n        return tidx, token\n\n    def _split_kwds(self, tlist):\n        tidx, token = self._next_token(tlist)\n        while token:\n            # joins are special case. only consider the first word as aligner\n            if token.match(T.Keyword, self.join_words, regex=True):\n                token_indent = token.value.split()[0]\n            else:\n                token_indent = text_type(token)\n            tlist.insert_before(token, self.nl(token_indent))\n            tidx += 1\n            tidx, token = self._next_token(tlist, tidx)\n\n    def _process_default(self, tlist):\n        self._split_kwds(tlist)\n        # process any sub-sub statements\n        for sgroup in tlist.get_sublists():\n            idx = tlist.token_index(sgroup)\n            pidx, prev_ = tlist.token_prev(idx)\n            # HACK: make \"group/order by\" work. Longer than max_len.\n            offset_ = 3 if (prev_ and prev_.match(T.Keyword, 'BY')) else 0\n            with offset(self, offset_):\n                self._process(sgroup)\n\n    def _process(self, tlist):\n        func_name = '_process_{cls}'.format(cls=type(tlist).__name__)\n        func = getattr(self, func_name.lower(), self._process_default)\n        func(tlist)\n\n    def process(self, stmt):\n        self._process(stmt)\n        return stmt\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/filters/others.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\nfrom sqlparse import sql, tokens as T\nfrom sqlparse.utils import split_unquoted_newlines\n\n\nclass StripCommentsFilter(object):\n    @staticmethod\n    def _process(tlist):\n        def get_next_comment():\n            # TODO(andi) Comment types should be unified, see related issue38\n            return tlist.token_next_by(i=sql.Comment, t=T.Comment)\n\n        tidx, token = get_next_comment()\n        while token:\n            pidx, prev_ = tlist.token_prev(tidx, skip_ws=False)\n            nidx, next_ = tlist.token_next(tidx, skip_ws=False)\n            # Replace by whitespace if prev and next exist and if they're not\n            # whitespaces. This doesn't apply if prev or next is a paranthesis.\n            if (prev_ is None or next_ is None or\n                    prev_.is_whitespace or prev_.match(T.Punctuation, '(') or\n                    next_.is_whitespace or next_.match(T.Punctuation, ')')):\n                tlist.tokens.remove(token)\n            else:\n                tlist.tokens[tidx] = sql.Token(T.Whitespace, ' ')\n\n            tidx, token = get_next_comment()\n\n    def process(self, stmt):\n        [self.process(sgroup) for sgroup in stmt.get_sublists()]\n        StripCommentsFilter._process(stmt)\n        return stmt\n\n\nclass StripWhitespaceFilter(object):\n    def _stripws(self, tlist):\n        func_name = '_stripws_{cls}'.format(cls=type(tlist).__name__)\n        func = getattr(self, func_name.lower(), self._stripws_default)\n        func(tlist)\n\n    @staticmethod\n    def _stripws_default(tlist):\n        last_was_ws = False\n        is_first_char = True\n        for token in tlist.tokens:\n            if token.is_whitespace:\n                token.value = '' if last_was_ws or is_first_char else ' '\n            last_was_ws = token.is_whitespace\n            is_first_char = False\n\n    def _stripws_identifierlist(self, tlist):\n        # Removes newlines before commas, see issue140\n        last_nl = None\n        for token in list(tlist.tokens):\n            if last_nl and token.ttype is T.Punctuation and token.value == ',':\n                tlist.tokens.remove(last_nl)\n            last_nl = token if token.is_whitespace else None\n\n            # next_ = tlist.token_next(token, skip_ws=False)\n            # if (next_ and not next_.is_whitespace and\n            #             token.ttype is T.Punctuation and token.value == ','):\n            #     tlist.insert_after(token, sql.Token(T.Whitespace, ' '))\n        return self._stripws_default(tlist)\n\n    def _stripws_parenthesis(self, tlist):\n        if tlist.tokens[1].is_whitespace:\n            tlist.tokens.pop(1)\n        if tlist.tokens[-2].is_whitespace:\n            tlist.tokens.pop(-2)\n        self._stripws_default(tlist)\n\n    def process(self, stmt, depth=0):\n        [self.process(sgroup, depth + 1) for sgroup in stmt.get_sublists()]\n        self._stripws(stmt)\n        if depth == 0 and stmt.tokens and stmt.tokens[-1].is_whitespace:\n            stmt.tokens.pop(-1)\n        return stmt\n\n\nclass SpacesAroundOperatorsFilter(object):\n    @staticmethod\n    def _process(tlist):\n\n        ttypes = (T.Operator, T.Comparison)\n        tidx, token = tlist.token_next_by(t=ttypes)\n        while token:\n            nidx, next_ = tlist.token_next(tidx, skip_ws=False)\n            if next_ and next_.ttype != T.Whitespace:\n                tlist.insert_after(tidx, sql.Token(T.Whitespace, ' '))\n\n            pidx, prev_ = tlist.token_prev(tidx, skip_ws=False)\n            if prev_ and prev_.ttype != T.Whitespace:\n                tlist.insert_before(tidx, sql.Token(T.Whitespace, ' '))\n                tidx += 1  # has to shift since token inserted before it\n\n            # assert tlist.token_index(token) == tidx\n            tidx, token = tlist.token_next_by(t=ttypes, idx=tidx)\n\n    def process(self, stmt):\n        [self.process(sgroup) for sgroup in stmt.get_sublists()]\n        SpacesAroundOperatorsFilter._process(stmt)\n        return stmt\n\n\n# ---------------------------\n# postprocess\n\nclass SerializerUnicode(object):\n    @staticmethod\n    def process(stmt):\n        lines = split_unquoted_newlines(stmt)\n        return '\\n'.join(line.rstrip() for line in lines)\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/filters/output.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\nfrom sqlparse import sql, tokens as T\nfrom sqlparse.compat import text_type\n\n\nclass OutputFilter(object):\n    varname_prefix = ''\n\n    def __init__(self, varname='sql'):\n        self.varname = self.varname_prefix + varname\n        self.count = 0\n\n    def _process(self, stream, varname, has_nl):\n        raise NotImplementedError\n\n    def process(self, stmt):\n        self.count += 1\n        if self.count > 1:\n            varname = u'{f.varname}{f.count}'.format(f=self)\n        else:\n            varname = self.varname\n\n        has_nl = len(text_type(stmt).strip().splitlines()) > 1\n        stmt.tokens = self._process(stmt.tokens, varname, has_nl)\n        return stmt\n\n\nclass OutputPythonFilter(OutputFilter):\n    def _process(self, stream, varname, has_nl):\n        # SQL query asignation to varname\n        if self.count > 1:\n            yield sql.Token(T.Whitespace, '\\n')\n        yield sql.Token(T.Name, varname)\n        yield sql.Token(T.Whitespace, ' ')\n        yield sql.Token(T.Operator, '=')\n        yield sql.Token(T.Whitespace, ' ')\n        if has_nl:\n            yield sql.Token(T.Operator, '(')\n        yield sql.Token(T.Text, \"'\")\n\n        # Print the tokens on the quote\n        for token in stream:\n            # Token is a new line separator\n            if token.is_whitespace and '\\n' in token.value:\n                # Close quote and add a new line\n                yield sql.Token(T.Text, \" '\")\n                yield sql.Token(T.Whitespace, '\\n')\n\n                # Quote header on secondary lines\n                yield sql.Token(T.Whitespace, ' ' * (len(varname) + 4))\n                yield sql.Token(T.Text, \"'\")\n\n                # Indentation\n                after_lb = token.value.split('\\n', 1)[1]\n                if after_lb:\n                    yield sql.Token(T.Whitespace, after_lb)\n                continue\n\n            # Token has escape chars\n            elif \"'\" in token.value:\n                token.value = token.value.replace(\"'\", \"\\\\'\")\n\n            # Put the token\n            yield sql.Token(T.Text, token.value)\n\n        # Close quote\n        yield sql.Token(T.Text, \"'\")\n        if has_nl:\n            yield sql.Token(T.Operator, ')')\n\n\nclass OutputPHPFilter(OutputFilter):\n    varname_prefix = '$'\n\n    def _process(self, stream, varname, has_nl):\n        # SQL query asignation to varname (quote header)\n        if self.count > 1:\n            yield sql.Token(T.Whitespace, '\\n')\n        yield sql.Token(T.Name, varname)\n        yield sql.Token(T.Whitespace, ' ')\n        if has_nl:\n            yield sql.Token(T.Whitespace, ' ')\n        yield sql.Token(T.Operator, '=')\n        yield sql.Token(T.Whitespace, ' ')\n        yield sql.Token(T.Text, '\"')\n\n        # Print the tokens on the quote\n        for token in stream:\n            # Token is a new line separator\n            if token.is_whitespace and '\\n' in token.value:\n                # Close quote and add a new line\n                yield sql.Token(T.Text, ' \";')\n                yield sql.Token(T.Whitespace, '\\n')\n\n                # Quote header on secondary lines\n                yield sql.Token(T.Name, varname)\n                yield sql.Token(T.Whitespace, ' ')\n                yield sql.Token(T.Operator, '.=')\n                yield sql.Token(T.Whitespace, ' ')\n                yield sql.Token(T.Text, '\"')\n\n                # Indentation\n                after_lb = token.value.split('\\n', 1)[1]\n                if after_lb:\n                    yield sql.Token(T.Whitespace, after_lb)\n                continue\n\n            # Token has escape chars\n            elif '\"' in token.value:\n                token.value = token.value.replace('\"', '\\\\\"')\n\n            # Put the token\n            yield sql.Token(T.Text, token.value)\n\n        # Close quote\n        yield sql.Token(T.Text, '\"')\n        yield sql.Token(T.Punctuation, ';')\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/filters/reindent.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\nfrom sqlparse import sql, tokens as T\nfrom sqlparse.compat import text_type\nfrom sqlparse.utils import offset, indent\n\n\nclass ReindentFilter(object):\n    def __init__(self, width=2, char=' ', wrap_after=0, n='\\n',\n                 comma_first=False):\n        self.n = n\n        self.width = width\n        self.char = char\n        self.indent = 0\n        self.offset = 0\n        self.wrap_after = wrap_after\n        self.comma_first = comma_first\n        self._curr_stmt = None\n        self._last_stmt = None\n\n    def _flatten_up_to_token(self, token):\n        \"\"\"Yields all tokens up to token but excluding current.\"\"\"\n        if token.is_group:\n            token = next(token.flatten())\n\n        for t in self._curr_stmt.flatten():\n            if t == token:\n                break\n            yield t\n\n    @property\n    def leading_ws(self):\n        return self.offset + self.indent * self.width\n\n    def _get_offset(self, token):\n        raw = u''.join(map(text_type, self._flatten_up_to_token(token)))\n        line = (raw or '\\n').splitlines()[-1]\n        # Now take current offset into account and return relative offset.\n        return len(line) - len(self.char * self.leading_ws)\n\n    def nl(self, offset=0):\n        return sql.Token(\n            T.Whitespace,\n            self.n + self.char * max(0, self.leading_ws + offset))\n\n    def _next_token(self, tlist, idx=-1):\n        split_words = ('FROM', 'STRAIGHT_JOIN$', 'JOIN$', 'AND', 'OR',\n                       'GROUP', 'ORDER', 'UNION', 'VALUES',\n                       'SET', 'BETWEEN', 'EXCEPT', 'HAVING', 'LIMIT')\n        m_split = T.Keyword, split_words, True\n        tidx, token = tlist.token_next_by(m=m_split, idx=idx)\n\n        if token and token.normalized == 'BETWEEN':\n            tidx, token = self._next_token(tlist, tidx)\n\n            if token and token.normalized == 'AND':\n                tidx, token = self._next_token(tlist, tidx)\n\n        return tidx, token\n\n    def _split_kwds(self, tlist):\n        tidx, token = self._next_token(tlist)\n        while token:\n            pidx, prev_ = tlist.token_prev(tidx, skip_ws=False)\n            uprev = text_type(prev_)\n\n            if prev_ and prev_.is_whitespace:\n                del tlist.tokens[pidx]\n                tidx -= 1\n\n            if not (uprev.endswith('\\n') or uprev.endswith('\\r')):\n                tlist.insert_before(tidx, self.nl())\n                tidx += 1\n\n            tidx, token = self._next_token(tlist, tidx)\n\n    def _split_statements(self, tlist):\n        ttypes = T.Keyword.DML, T.Keyword.DDL\n        tidx, token = tlist.token_next_by(t=ttypes)\n        while token:\n            pidx, prev_ = tlist.token_prev(tidx, skip_ws=False)\n            if prev_ and prev_.is_whitespace:\n                del tlist.tokens[pidx]\n                tidx -= 1\n            # only break if it's not the first token\n            if prev_:\n                tlist.insert_before(tidx, self.nl())\n                tidx += 1\n            tidx, token = tlist.token_next_by(t=ttypes, idx=tidx)\n\n    def _process(self, tlist):\n        func_name = '_process_{cls}'.format(cls=type(tlist).__name__)\n        func = getattr(self, func_name.lower(), self._process_default)\n        func(tlist)\n\n    def _process_where(self, tlist):\n        tidx, token = tlist.token_next_by(m=(T.Keyword, 'WHERE'))\n        # issue121, errors in statement fixed??\n        tlist.insert_before(tidx, self.nl())\n\n        with indent(self):\n            self._process_default(tlist)\n\n    def _process_parenthesis(self, tlist):\n        ttypes = T.Keyword.DML, T.Keyword.DDL\n        _, is_dml_dll = tlist.token_next_by(t=ttypes)\n        fidx, first = tlist.token_next_by(m=sql.Parenthesis.M_OPEN)\n\n        with indent(self, 1 if is_dml_dll else 0):\n            tlist.tokens.insert(0, self.nl()) if is_dml_dll else None\n            with offset(self, self._get_offset(first) + 1):\n                self._process_default(tlist, not is_dml_dll)\n\n    def _process_identifierlist(self, tlist):\n        identifiers = list(tlist.get_identifiers())\n        first = next(identifiers.pop(0).flatten())\n        num_offset = 1 if self.char == '\\t' else self._get_offset(first)\n        if not tlist.within(sql.Function):\n            with offset(self, num_offset):\n                position = 0\n                for token in identifiers:\n                    # Add 1 for the \",\" separator\n                    position += len(token.value) + 1\n                    if position > (self.wrap_after - self.offset):\n                        adjust = 0\n                        if self.comma_first:\n                            adjust = -2\n                            _, comma = tlist.token_prev(\n                                tlist.token_index(token))\n                            if comma is None:\n                                continue\n                            token = comma\n                        tlist.insert_before(token, self.nl(offset=adjust))\n                        if self.comma_first:\n                            _, ws = tlist.token_next(\n                                tlist.token_index(token), skip_ws=False)\n                            if (ws is not None\n                                    and ws.ttype is not T.Text.Whitespace):\n                                tlist.insert_after(\n                                    token, sql.Token(T.Whitespace, ' '))\n                        position = 0\n        self._process_default(tlist)\n\n    def _process_case(self, tlist):\n        iterable = iter(tlist.get_cases())\n        cond, _ = next(iterable)\n        first = next(cond[0].flatten())\n\n        with offset(self, self._get_offset(tlist[0])):\n            with offset(self, self._get_offset(first)):\n                for cond, value in iterable:\n                    token = value[0] if cond is None else cond[0]\n                    tlist.insert_before(token, self.nl())\n\n                # Line breaks on group level are done. let's add an offset of\n                # len \"when \", \"then \", \"else \"\n                with offset(self, len(\"WHEN \")):\n                    self._process_default(tlist)\n            end_idx, end = tlist.token_next_by(m=sql.Case.M_CLOSE)\n            if end_idx is not None:\n                tlist.insert_before(end_idx, self.nl())\n\n    def _process_default(self, tlist, stmts=True):\n        self._split_statements(tlist) if stmts else None\n        self._split_kwds(tlist)\n        for sgroup in tlist.get_sublists():\n            self._process(sgroup)\n\n    def process(self, stmt):\n        self._curr_stmt = stmt\n        self._process(stmt)\n\n        if self._last_stmt is not None:\n            nl = '\\n' if text_type(self._last_stmt).endswith('\\n') else '\\n\\n'\n            stmt.tokens.insert(0, sql.Token(T.Whitespace, nl))\n\n        self._last_stmt = stmt\n        return stmt\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/filters/right_margin.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\nimport re\n\nfrom sqlparse import sql, tokens as T\nfrom sqlparse.compat import text_type\n\n\n# FIXME: Doesn't work\nclass RightMarginFilter(object):\n    keep_together = (\n        # sql.TypeCast, sql.Identifier, sql.Alias,\n    )\n\n    def __init__(self, width=79):\n        self.width = width\n        self.line = ''\n\n    def _process(self, group, stream):\n        for token in stream:\n            if token.is_whitespace and '\\n' in token.value:\n                if token.value.endswith('\\n'):\n                    self.line = ''\n                else:\n                    self.line = token.value.splitlines()[-1]\n            elif token.is_group and type(token) not in self.keep_together:\n                token.tokens = self._process(token, token.tokens)\n            else:\n                val = text_type(token)\n                if len(self.line) + len(val) > self.width:\n                    match = re.search(r'^ +', self.line)\n                    if match is not None:\n                        indent = match.group()\n                    else:\n                        indent = ''\n                    yield sql.Token(T.Whitespace, '\\n{0}'.format(indent))\n                    self.line = indent\n                self.line += val\n            yield token\n\n    def process(self, group):\n        # return\n        # group.tokens = self._process(group, group.tokens)\n        raise NotImplementedError\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/filters/tokens.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\nfrom sqlparse import tokens as T\nfrom sqlparse.compat import text_type\n\n\nclass _CaseFilter(object):\n    ttype = None\n\n    def __init__(self, case=None):\n        case = case or 'upper'\n        self.convert = getattr(text_type, case)\n\n    def process(self, stream):\n        for ttype, value in stream:\n            if ttype in self.ttype:\n                value = self.convert(value)\n            yield ttype, value\n\n\nclass KeywordCaseFilter(_CaseFilter):\n    ttype = T.Keyword\n\n\nclass IdentifierCaseFilter(_CaseFilter):\n    ttype = T.Name, T.String.Symbol\n\n    def process(self, stream):\n        for ttype, value in stream:\n            if ttype in self.ttype and value.strip()[0] != '\"':\n                value = self.convert(value)\n            yield ttype, value\n\n\nclass TruncateStringFilter(object):\n    def __init__(self, width, char):\n        self.width = width\n        self.char = char\n\n    def process(self, stream):\n        for ttype, value in stream:\n            if ttype != T.Literal.String.Single:\n                yield ttype, value\n                continue\n\n            if value[:2] == \"''\":\n                inner = value[2:-2]\n                quote = \"''\"\n            else:\n                inner = value[1:-1]\n                quote = \"'\"\n\n            if len(inner) > self.width:\n                value = ''.join((quote, inner[:self.width], self.char, quote))\n            yield ttype, value\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/formatter.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\n\"\"\"SQL formatter\"\"\"\n\nfrom sqlparse import filters\nfrom sqlparse.exceptions import SQLParseError\n\n\ndef validate_options(options):\n    \"\"\"Validates options.\"\"\"\n    kwcase = options.get('keyword_case')\n    if kwcase not in [None, 'upper', 'lower', 'capitalize']:\n        raise SQLParseError('Invalid value for keyword_case: '\n                            '{0!r}'.format(kwcase))\n\n    idcase = options.get('identifier_case')\n    if idcase not in [None, 'upper', 'lower', 'capitalize']:\n        raise SQLParseError('Invalid value for identifier_case: '\n                            '{0!r}'.format(idcase))\n\n    ofrmt = options.get('output_format')\n    if ofrmt not in [None, 'sql', 'python', 'php']:\n        raise SQLParseError('Unknown output format: '\n                            '{0!r}'.format(ofrmt))\n\n    strip_comments = options.get('strip_comments', False)\n    if strip_comments not in [True, False]:\n        raise SQLParseError('Invalid value for strip_comments: '\n                            '{0!r}'.format(strip_comments))\n\n    space_around_operators = options.get('use_space_around_operators', False)\n    if space_around_operators not in [True, False]:\n        raise SQLParseError('Invalid value for use_space_around_operators: '\n                            '{0!r}'.format(space_around_operators))\n\n    strip_ws = options.get('strip_whitespace', False)\n    if strip_ws not in [True, False]:\n        raise SQLParseError('Invalid value for strip_whitespace: '\n                            '{0!r}'.format(strip_ws))\n\n    truncate_strings = options.get('truncate_strings')\n    if truncate_strings is not None:\n        try:\n            truncate_strings = int(truncate_strings)\n        except (ValueError, TypeError):\n            raise SQLParseError('Invalid value for truncate_strings: '\n                                '{0!r}'.format(truncate_strings))\n        if truncate_strings <= 1:\n            raise SQLParseError('Invalid value for truncate_strings: '\n                                '{0!r}'.format(truncate_strings))\n        options['truncate_strings'] = truncate_strings\n        options['truncate_char'] = options.get('truncate_char', '[...]')\n\n    reindent = options.get('reindent', False)\n    if reindent not in [True, False]:\n        raise SQLParseError('Invalid value for reindent: '\n                            '{0!r}'.format(reindent))\n    elif reindent:\n        options['strip_whitespace'] = True\n\n    reindent_aligned = options.get('reindent_aligned', False)\n    if reindent_aligned not in [True, False]:\n        raise SQLParseError('Invalid value for reindent_aligned: '\n                            '{0!r}'.format(reindent))\n    elif reindent_aligned:\n        options['strip_whitespace'] = True\n\n    indent_tabs = options.get('indent_tabs', False)\n    if indent_tabs not in [True, False]:\n        raise SQLParseError('Invalid value for indent_tabs: '\n                            '{0!r}'.format(indent_tabs))\n    elif indent_tabs:\n        options['indent_char'] = '\\t'\n    else:\n        options['indent_char'] = ' '\n\n    indent_width = options.get('indent_width', 2)\n    try:\n        indent_width = int(indent_width)\n    except (TypeError, ValueError):\n        raise SQLParseError('indent_width requires an integer')\n    if indent_width < 1:\n        raise SQLParseError('indent_width requires a positive integer')\n    options['indent_width'] = indent_width\n\n    wrap_after = options.get('wrap_after', 0)\n    try:\n        wrap_after = int(wrap_after)\n    except (TypeError, ValueError):\n        raise SQLParseError('wrap_after requires an integer')\n    if wrap_after < 0:\n        raise SQLParseError('wrap_after requires a positive integer')\n    options['wrap_after'] = wrap_after\n\n    comma_first = options.get('comma_first', False)\n    if comma_first not in [True, False]:\n        raise SQLParseError('comma_first requires a boolean value')\n    options['comma_first'] = comma_first\n\n    right_margin = options.get('right_margin')\n    if right_margin is not None:\n        try:\n            right_margin = int(right_margin)\n        except (TypeError, ValueError):\n            raise SQLParseError('right_margin requires an integer')\n        if right_margin < 10:\n            raise SQLParseError('right_margin requires an integer > 10')\n    options['right_margin'] = right_margin\n\n    return options\n\n\ndef build_filter_stack(stack, options):\n    \"\"\"Setup and return a filter stack.\n\n    Args:\n      stack: :class:`~sqlparse.filters.FilterStack` instance\n      options: Dictionary with options validated by validate_options.\n    \"\"\"\n    # Token filter\n    if options.get('keyword_case'):\n        stack.preprocess.append(\n            filters.KeywordCaseFilter(options['keyword_case']))\n\n    if options.get('identifier_case'):\n        stack.preprocess.append(\n            filters.IdentifierCaseFilter(options['identifier_case']))\n\n    if options.get('truncate_strings'):\n        stack.preprocess.append(filters.TruncateStringFilter(\n            width=options['truncate_strings'], char=options['truncate_char']))\n\n    if options.get('use_space_around_operators', False):\n        stack.enable_grouping()\n        stack.stmtprocess.append(filters.SpacesAroundOperatorsFilter())\n\n    # After grouping\n    if options.get('strip_comments'):\n        stack.enable_grouping()\n        stack.stmtprocess.append(filters.StripCommentsFilter())\n\n    if options.get('strip_whitespace') or options.get('reindent'):\n        stack.enable_grouping()\n        stack.stmtprocess.append(filters.StripWhitespaceFilter())\n\n    if options.get('reindent'):\n        stack.enable_grouping()\n        stack.stmtprocess.append(\n            filters.ReindentFilter(char=options['indent_char'],\n                                   width=options['indent_width'],\n                                   wrap_after=options['wrap_after'],\n                                   comma_first=options['comma_first']))\n\n    if options.get('reindent_aligned', False):\n        stack.enable_grouping()\n        stack.stmtprocess.append(\n            filters.AlignedIndentFilter(char=options['indent_char']))\n\n    if options.get('right_margin'):\n        stack.enable_grouping()\n        stack.stmtprocess.append(\n            filters.RightMarginFilter(width=options['right_margin']))\n\n    # Serializer\n    if options.get('output_format'):\n        frmt = options['output_format']\n        if frmt.lower() == 'php':\n            fltr = filters.OutputPHPFilter()\n        elif frmt.lower() == 'python':\n            fltr = filters.OutputPythonFilter()\n        else:\n            fltr = None\n        if fltr is not None:\n            stack.postprocess.append(fltr)\n\n    return stack\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/keywords.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\nimport re\n\nfrom sqlparse import tokens\n\n\ndef is_keyword(value):\n    val = value.upper()\n    return (KEYWORDS_COMMON.get(val) or\n            KEYWORDS_ORACLE.get(val) or\n            KEYWORDS.get(val, tokens.Name)), value\n\n\nSQL_REGEX = {\n    'root': [\n        (r'(--|# )\\+.*?(\\r\\n|\\r|\\n|$)', tokens.Comment.Single.Hint),\n        (r'/\\*\\+[\\s\\S]*?\\*/', tokens.Comment.Multiline.Hint),\n\n        (r'(--|# ).*?(\\r\\n|\\r|\\n|$)', tokens.Comment.Single),\n        (r'/\\*[\\s\\S]*?\\*/', tokens.Comment.Multiline),\n\n        (r'(\\r\\n|\\r|\\n)', tokens.Newline),\n        (r'\\s+', tokens.Whitespace),\n\n        (r':=', tokens.Assignment),\n        (r'::', tokens.Punctuation),\n\n        (r'\\*', tokens.Wildcard),\n\n        (r\"`(``|[^`])*`\", tokens.Name),\n        (r\"´(´´|[^´])*´\", tokens.Name),\n        (r'(\\$(?:[_A-Z]\\w*)?\\$)[\\s\\S]*?\\1', tokens.Literal),\n\n        (r'\\?', tokens.Name.Placeholder),\n        (r'%(\\(\\w+\\))?s', tokens.Name.Placeholder),\n        (r'(?<!\\w)[$:?]\\w+', tokens.Name.Placeholder),\n\n        # FIXME(andi): VALUES shouldn't be listed here\n        # see https://github.com/andialbrecht/sqlparse/pull/64\n        # IN is special, it may be followed by a parenthesis, but\n        # is never a functino, see issue183\n        (r'(CASE|IN|VALUES|USING)\\b', tokens.Keyword),\n\n        (r'(@|##|#)[A-Z]\\w+', tokens.Name),\n\n        # see issue #39\n        # Spaces around period `schema . name` are valid identifier\n        # TODO: Spaces before period not implemented\n        (r'[A-Z]\\w*(?=\\s*\\.)', tokens.Name),  # 'Name'   .\n        (r'(?<=\\.)[A-Z]\\w*', tokens.Name),  # .'Name'\n        (r'[A-Z]\\w*(?=\\()', tokens.Name),  # side effect: change kw to func\n\n        # TODO: `1.` and `.1` are valid numbers\n        (r'-?0x[\\dA-F]+', tokens.Number.Hexadecimal),\n        (r'-?\\d*(\\.\\d+)?E-?\\d+', tokens.Number.Float),\n        (r'-?\\d*\\.\\d+', tokens.Number.Float),\n        (r'-?\\d+', tokens.Number.Integer),\n\n        (r\"'(''|\\\\\\\\|\\\\'|[^'])*'\", tokens.String.Single),\n        # not a real string literal in ANSI SQL:\n        (r'(\"\"|\".*?[^\\\\]\")', tokens.String.Symbol),\n        # sqlite names can be escaped with [square brackets]. left bracket\n        # cannot be preceded by word character or a right bracket --\n        # otherwise it's probably an array index\n        (r'(?<![\\w\\])])(\\[[^\\]]+\\])', tokens.Name),\n        (r'((LEFT\\s+|RIGHT\\s+|FULL\\s+)?(INNER\\s+|OUTER\\s+|STRAIGHT\\s+)?'\n         r'|(CROSS\\s+|NATURAL\\s+)?)?JOIN\\b', tokens.Keyword),\n        (r'END(\\s+IF|\\s+LOOP|\\s+WHILE)?\\b', tokens.Keyword),\n        (r'NOT\\s+NULL\\b', tokens.Keyword),\n        (r'UNION\\s+ALL\\b', tokens.Keyword),\n        (r'CREATE(\\s+OR\\s+REPLACE)?\\b', tokens.Keyword.DDL),\n        (r'DOUBLE\\s+PRECISION\\b', tokens.Name.Builtin),\n\n        (r'[_A-Z][_$#\\w]*', is_keyword),\n\n        (r'[;:()\\[\\],\\.]', tokens.Punctuation),\n        (r'[<>=~!]+', tokens.Operator.Comparison),\n        (r'[+/@#%^&|`?^-]+', tokens.Operator),\n    ]}\n\nFLAGS = re.IGNORECASE | re.UNICODE\nSQL_REGEX = [(re.compile(rx, FLAGS).match, tt) for rx, tt in SQL_REGEX['root']]\n\nKEYWORDS = {\n    'ABORT': tokens.Keyword,\n    'ABS': tokens.Keyword,\n    'ABSOLUTE': tokens.Keyword,\n    'ACCESS': tokens.Keyword,\n    'ADA': tokens.Keyword,\n    'ADD': tokens.Keyword,\n    'ADMIN': tokens.Keyword,\n    'AFTER': tokens.Keyword,\n    'AGGREGATE': tokens.Keyword,\n    'ALIAS': tokens.Keyword,\n    'ALL': tokens.Keyword,\n    'ALLOCATE': tokens.Keyword,\n    'ANALYSE': tokens.Keyword,\n    'ANALYZE': tokens.Keyword,\n    'ANY': tokens.Keyword,\n    'ARRAYLEN': tokens.Keyword,\n    'ARE': tokens.Keyword,\n    'ASC': tokens.Keyword.Order,\n    'ASENSITIVE': tokens.Keyword,\n    'ASSERTION': tokens.Keyword,\n    'ASSIGNMENT': tokens.Keyword,\n    'ASYMMETRIC': tokens.Keyword,\n    'AT': tokens.Keyword,\n    'ATOMIC': tokens.Keyword,\n    'AUDIT': tokens.Keyword,\n    'AUTHORIZATION': tokens.Keyword,\n    'AVG': tokens.Keyword,\n\n    'BACKWARD': tokens.Keyword,\n    'BEFORE': tokens.Keyword,\n    'BEGIN': tokens.Keyword,\n    'BETWEEN': tokens.Keyword,\n    'BITVAR': tokens.Keyword,\n    'BIT_LENGTH': tokens.Keyword,\n    'BOTH': tokens.Keyword,\n    'BREADTH': tokens.Keyword,\n\n    # 'C': tokens.Keyword,  # most likely this is an alias\n    'CACHE': tokens.Keyword,\n    'CALL': tokens.Keyword,\n    'CALLED': tokens.Keyword,\n    'CARDINALITY': tokens.Keyword,\n    'CASCADE': tokens.Keyword,\n    'CASCADED': tokens.Keyword,\n    'CAST': tokens.Keyword,\n    'CATALOG': tokens.Keyword,\n    'CATALOG_NAME': tokens.Keyword,\n    'CHAIN': tokens.Keyword,\n    'CHARACTERISTICS': tokens.Keyword,\n    'CHARACTER_LENGTH': tokens.Keyword,\n    'CHARACTER_SET_CATALOG': tokens.Keyword,\n    'CHARACTER_SET_NAME': tokens.Keyword,\n    'CHARACTER_SET_SCHEMA': tokens.Keyword,\n    'CHAR_LENGTH': tokens.Keyword,\n    'CHECK': tokens.Keyword,\n    'CHECKED': tokens.Keyword,\n    'CHECKPOINT': tokens.Keyword,\n    'CLASS': tokens.Keyword,\n    'CLASS_ORIGIN': tokens.Keyword,\n    'CLOB': tokens.Keyword,\n    'CLOSE': tokens.Keyword,\n    'CLUSTER': tokens.Keyword,\n    'COALESCE': tokens.Keyword,\n    'COBOL': tokens.Keyword,\n    'COLLATE': tokens.Keyword,\n    'COLLATION': tokens.Keyword,\n    'COLLATION_CATALOG': tokens.Keyword,\n    'COLLATION_NAME': tokens.Keyword,\n    'COLLATION_SCHEMA': tokens.Keyword,\n    'COLLECT': tokens.Keyword,\n    'COLUMN': tokens.Keyword,\n    'COLUMN_NAME': tokens.Keyword,\n    'COMPRESS': tokens.Keyword,\n    'COMMAND_FUNCTION': tokens.Keyword,\n    'COMMAND_FUNCTION_CODE': tokens.Keyword,\n    'COMMENT': tokens.Keyword,\n    'COMMIT': tokens.Keyword.DML,\n    'COMMITTED': tokens.Keyword,\n    'COMPLETION': tokens.Keyword,\n    'CONCURRENTLY': tokens.Keyword,\n    'CONDITION_NUMBER': tokens.Keyword,\n    'CONNECT': tokens.Keyword,\n    'CONNECTION': tokens.Keyword,\n    'CONNECTION_NAME': tokens.Keyword,\n    'CONSTRAINT': tokens.Keyword,\n    'CONSTRAINTS': tokens.Keyword,\n    'CONSTRAINT_CATALOG': tokens.Keyword,\n    'CONSTRAINT_NAME': tokens.Keyword,\n    'CONSTRAINT_SCHEMA': tokens.Keyword,\n    'CONSTRUCTOR': tokens.Keyword,\n    'CONTAINS': tokens.Keyword,\n    'CONTINUE': tokens.Keyword,\n    'CONVERSION': tokens.Keyword,\n    'CONVERT': tokens.Keyword,\n    'COPY': tokens.Keyword,\n    'CORRESPONTING': tokens.Keyword,\n    'COUNT': tokens.Keyword,\n    'CREATEDB': tokens.Keyword,\n    'CREATEUSER': tokens.Keyword,\n    'CROSS': tokens.Keyword,\n    'CUBE': tokens.Keyword,\n    'CURRENT': tokens.Keyword,\n    'CURRENT_DATE': tokens.Keyword,\n    'CURRENT_PATH': tokens.Keyword,\n    'CURRENT_ROLE': tokens.Keyword,\n    'CURRENT_TIME': tokens.Keyword,\n    'CURRENT_TIMESTAMP': tokens.Keyword,\n    'CURRENT_USER': tokens.Keyword,\n    'CURSOR': tokens.Keyword,\n    'CURSOR_NAME': tokens.Keyword,\n    'CYCLE': tokens.Keyword,\n\n    'DATA': tokens.Keyword,\n    'DATABASE': tokens.Keyword,\n    'DATETIME_INTERVAL_CODE': tokens.Keyword,\n    'DATETIME_INTERVAL_PRECISION': tokens.Keyword,\n    'DAY': tokens.Keyword,\n    'DEALLOCATE': tokens.Keyword,\n    'DECLARE': tokens.Keyword,\n    'DEFAULT': tokens.Keyword,\n    'DEFAULTS': tokens.Keyword,\n    'DEFERRABLE': tokens.Keyword,\n    'DEFERRED': tokens.Keyword,\n    'DEFINED': tokens.Keyword,\n    'DEFINER': tokens.Keyword,\n    'DELIMITER': tokens.Keyword,\n    'DELIMITERS': tokens.Keyword,\n    'DEREF': tokens.Keyword,\n    'DESC': tokens.Keyword.Order,\n    'DESCRIBE': tokens.Keyword,\n    'DESCRIPTOR': tokens.Keyword,\n    'DESTROY': tokens.Keyword,\n    'DESTRUCTOR': tokens.Keyword,\n    'DETERMINISTIC': tokens.Keyword,\n    'DIAGNOSTICS': tokens.Keyword,\n    'DICTIONARY': tokens.Keyword,\n    'DISABLE': tokens.Keyword,\n    'DISCONNECT': tokens.Keyword,\n    'DISPATCH': tokens.Keyword,\n    'DO': tokens.Keyword,\n    'DOMAIN': tokens.Keyword,\n    'DYNAMIC': tokens.Keyword,\n    'DYNAMIC_FUNCTION': tokens.Keyword,\n    'DYNAMIC_FUNCTION_CODE': tokens.Keyword,\n\n    'EACH': tokens.Keyword,\n    'ENABLE': tokens.Keyword,\n    'ENCODING': tokens.Keyword,\n    'ENCRYPTED': tokens.Keyword,\n    'END-EXEC': tokens.Keyword,\n    'EQUALS': tokens.Keyword,\n    'ESCAPE': tokens.Keyword,\n    'EVERY': tokens.Keyword,\n    'EXCEPT': tokens.Keyword,\n    'EXCEPTION': tokens.Keyword,\n    'EXCLUDING': tokens.Keyword,\n    'EXCLUSIVE': tokens.Keyword,\n    'EXEC': tokens.Keyword,\n    'EXECUTE': tokens.Keyword,\n    'EXISTING': tokens.Keyword,\n    'EXISTS': tokens.Keyword,\n    'EXTERNAL': tokens.Keyword,\n    'EXTRACT': tokens.Keyword,\n\n    'FALSE': tokens.Keyword,\n    'FETCH': tokens.Keyword,\n    'FILE': tokens.Keyword,\n    'FINAL': tokens.Keyword,\n    'FIRST': tokens.Keyword,\n    'FORCE': tokens.Keyword,\n    'FOREACH': tokens.Keyword,\n    'FOREIGN': tokens.Keyword,\n    'FORTRAN': tokens.Keyword,\n    'FORWARD': tokens.Keyword,\n    'FOUND': tokens.Keyword,\n    'FREE': tokens.Keyword,\n    'FREEZE': tokens.Keyword,\n    'FULL': tokens.Keyword,\n    'FUNCTION': tokens.Keyword,\n\n    # 'G': tokens.Keyword,\n    'GENERAL': tokens.Keyword,\n    'GENERATED': tokens.Keyword,\n    'GET': tokens.Keyword,\n    'GLOBAL': tokens.Keyword,\n    'GO': tokens.Keyword,\n    'GOTO': tokens.Keyword,\n    'GRANT': tokens.Keyword,\n    'GRANTED': tokens.Keyword,\n    'GROUPING': tokens.Keyword,\n\n    'HANDLER': tokens.Keyword,\n    'HAVING': tokens.Keyword,\n    'HIERARCHY': tokens.Keyword,\n    'HOLD': tokens.Keyword,\n    'HOST': tokens.Keyword,\n\n    'IDENTIFIED': tokens.Keyword,\n    'IDENTITY': tokens.Keyword,\n    'IGNORE': tokens.Keyword,\n    'ILIKE': tokens.Keyword,\n    'IMMEDIATE': tokens.Keyword,\n    'IMMUTABLE': tokens.Keyword,\n\n    'IMPLEMENTATION': tokens.Keyword,\n    'IMPLICIT': tokens.Keyword,\n    'INCLUDING': tokens.Keyword,\n    'INCREMENT': tokens.Keyword,\n    'INDEX': tokens.Keyword,\n\n    'INDITCATOR': tokens.Keyword,\n    'INFIX': tokens.Keyword,\n    'INHERITS': tokens.Keyword,\n    'INITIAL': tokens.Keyword,\n    'INITIALIZE': tokens.Keyword,\n    'INITIALLY': tokens.Keyword,\n    'INOUT': tokens.Keyword,\n    'INPUT': tokens.Keyword,\n    'INSENSITIVE': tokens.Keyword,\n    'INSTANTIABLE': tokens.Keyword,\n    'INSTEAD': tokens.Keyword,\n    'INTERSECT': tokens.Keyword,\n    'INTO': tokens.Keyword,\n    'INVOKER': tokens.Keyword,\n    'IS': tokens.Keyword,\n    'ISNULL': tokens.Keyword,\n    'ISOLATION': tokens.Keyword,\n    'ITERATE': tokens.Keyword,\n\n    # 'K': tokens.Keyword,\n    'KEY': tokens.Keyword,\n    'KEY_MEMBER': tokens.Keyword,\n    'KEY_TYPE': tokens.Keyword,\n\n    'LANCOMPILER': tokens.Keyword,\n    'LANGUAGE': tokens.Keyword,\n    'LARGE': tokens.Keyword,\n    'LAST': tokens.Keyword,\n    'LATERAL': tokens.Keyword,\n    'LEADING': tokens.Keyword,\n    'LENGTH': tokens.Keyword,\n    'LESS': tokens.Keyword,\n    'LEVEL': tokens.Keyword,\n    'LIMIT': tokens.Keyword,\n    'LISTEN': tokens.Keyword,\n    'LOAD': tokens.Keyword,\n    'LOCAL': tokens.Keyword,\n    'LOCALTIME': tokens.Keyword,\n    'LOCALTIMESTAMP': tokens.Keyword,\n    'LOCATION': tokens.Keyword,\n    'LOCATOR': tokens.Keyword,\n    'LOCK': tokens.Keyword,\n    'LOWER': tokens.Keyword,\n\n    # 'M': tokens.Keyword,\n    'MAP': tokens.Keyword,\n    'MATCH': tokens.Keyword,\n    'MAXEXTENTS': tokens.Keyword,\n    'MAXVALUE': tokens.Keyword,\n    'MESSAGE_LENGTH': tokens.Keyword,\n    'MESSAGE_OCTET_LENGTH': tokens.Keyword,\n    'MESSAGE_TEXT': tokens.Keyword,\n    'METHOD': tokens.Keyword,\n    'MINUTE': tokens.Keyword,\n    'MINUS': tokens.Keyword,\n    'MINVALUE': tokens.Keyword,\n    'MOD': tokens.Keyword,\n    'MODE': tokens.Keyword,\n    'MODIFIES': tokens.Keyword,\n    'MODIFY': tokens.Keyword,\n    'MONTH': tokens.Keyword,\n    'MORE': tokens.Keyword,\n    'MOVE': tokens.Keyword,\n    'MUMPS': tokens.Keyword,\n\n    'NAMES': tokens.Keyword,\n    'NATIONAL': tokens.Keyword,\n    'NATURAL': tokens.Keyword,\n    'NCHAR': tokens.Keyword,\n    'NCLOB': tokens.Keyword,\n    'NEW': tokens.Keyword,\n    'NEXT': tokens.Keyword,\n    'NO': tokens.Keyword,\n    'NOAUDIT': tokens.Keyword,\n    'NOCOMPRESS': tokens.Keyword,\n    'NOCREATEDB': tokens.Keyword,\n    'NOCREATEUSER': tokens.Keyword,\n    'NONE': tokens.Keyword,\n    'NOT': tokens.Keyword,\n    'NOTFOUND': tokens.Keyword,\n    'NOTHING': tokens.Keyword,\n    'NOTIFY': tokens.Keyword,\n    'NOTNULL': tokens.Keyword,\n    'NOWAIT': tokens.Keyword,\n    'NULL': tokens.Keyword,\n    'NULLABLE': tokens.Keyword,\n    'NULLIF': tokens.Keyword,\n\n    'OBJECT': tokens.Keyword,\n    'OCTET_LENGTH': tokens.Keyword,\n    'OF': tokens.Keyword,\n    'OFF': tokens.Keyword,\n    'OFFLINE': tokens.Keyword,\n    'OFFSET': tokens.Keyword,\n    'OIDS': tokens.Keyword,\n    'OLD': tokens.Keyword,\n    'ONLINE': tokens.Keyword,\n    'ONLY': tokens.Keyword,\n    'OPEN': tokens.Keyword,\n    'OPERATION': tokens.Keyword,\n    'OPERATOR': tokens.Keyword,\n    'OPTION': tokens.Keyword,\n    'OPTIONS': tokens.Keyword,\n    'ORDINALITY': tokens.Keyword,\n    'OUT': tokens.Keyword,\n    'OUTPUT': tokens.Keyword,\n    'OVERLAPS': tokens.Keyword,\n    'OVERLAY': tokens.Keyword,\n    'OVERRIDING': tokens.Keyword,\n    'OWNER': tokens.Keyword,\n\n    'PAD': tokens.Keyword,\n    'PARAMETER': tokens.Keyword,\n    'PARAMETERS': tokens.Keyword,\n    'PARAMETER_MODE': tokens.Keyword,\n    'PARAMATER_NAME': tokens.Keyword,\n    'PARAMATER_ORDINAL_POSITION': tokens.Keyword,\n    'PARAMETER_SPECIFIC_CATALOG': tokens.Keyword,\n    'PARAMETER_SPECIFIC_NAME': tokens.Keyword,\n    'PARAMATER_SPECIFIC_SCHEMA': tokens.Keyword,\n    'PARTIAL': tokens.Keyword,\n    'PASCAL': tokens.Keyword,\n    'PCTFREE': tokens.Keyword,\n    'PENDANT': tokens.Keyword,\n    'PLACING': tokens.Keyword,\n    'PLI': tokens.Keyword,\n    'POSITION': tokens.Keyword,\n    'POSTFIX': tokens.Keyword,\n    'PRECISION': tokens.Keyword,\n    'PREFIX': tokens.Keyword,\n    'PREORDER': tokens.Keyword,\n    'PREPARE': tokens.Keyword,\n    'PRESERVE': tokens.Keyword,\n    'PRIMARY': tokens.Keyword,\n    'PRIOR': tokens.Keyword,\n    'PRIVILEGES': tokens.Keyword,\n    'PROCEDURAL': tokens.Keyword,\n    'PROCEDURE': tokens.Keyword,\n    'PUBLIC': tokens.Keyword,\n\n    'RAISE': tokens.Keyword,\n    'RAW': tokens.Keyword,\n    'READ': tokens.Keyword,\n    'READS': tokens.Keyword,\n    'RECHECK': tokens.Keyword,\n    'RECURSIVE': tokens.Keyword,\n    'REF': tokens.Keyword,\n    'REFERENCES': tokens.Keyword,\n    'REFERENCING': tokens.Keyword,\n    'REINDEX': tokens.Keyword,\n    'RELATIVE': tokens.Keyword,\n    'RENAME': tokens.Keyword,\n    'REPEATABLE': tokens.Keyword,\n    'RESET': tokens.Keyword,\n    'RESOURCE': tokens.Keyword,\n    'RESTART': tokens.Keyword,\n    'RESTRICT': tokens.Keyword,\n    'RESULT': tokens.Keyword,\n    'RETURN': tokens.Keyword,\n    'RETURNED_LENGTH': tokens.Keyword,\n    'RETURNED_OCTET_LENGTH': tokens.Keyword,\n    'RETURNED_SQLSTATE': tokens.Keyword,\n    'RETURNING': tokens.Keyword,\n    'RETURNS': tokens.Keyword,\n    'REVOKE': tokens.Keyword,\n    'RIGHT': tokens.Keyword,\n    'ROLE': tokens.Keyword,\n    'ROLLBACK': tokens.Keyword.DML,\n    'ROLLUP': tokens.Keyword,\n    'ROUTINE': tokens.Keyword,\n    'ROUTINE_CATALOG': tokens.Keyword,\n    'ROUTINE_NAME': tokens.Keyword,\n    'ROUTINE_SCHEMA': tokens.Keyword,\n    'ROW': tokens.Keyword,\n    'ROWS': tokens.Keyword,\n    'ROW_COUNT': tokens.Keyword,\n    'RULE': tokens.Keyword,\n\n    'SAVE_POINT': tokens.Keyword,\n    'SCALE': tokens.Keyword,\n    'SCHEMA': tokens.Keyword,\n    'SCHEMA_NAME': tokens.Keyword,\n    'SCOPE': tokens.Keyword,\n    'SCROLL': tokens.Keyword,\n    'SEARCH': tokens.Keyword,\n    'SECOND': tokens.Keyword,\n    'SECURITY': tokens.Keyword,\n    'SELF': tokens.Keyword,\n    'SENSITIVE': tokens.Keyword,\n    'SEQUENCE': tokens.Keyword,\n    'SERIALIZABLE': tokens.Keyword,\n    'SERVER_NAME': tokens.Keyword,\n    'SESSION': tokens.Keyword,\n    'SESSION_USER': tokens.Keyword,\n    'SETOF': tokens.Keyword,\n    'SETS': tokens.Keyword,\n    'SHARE': tokens.Keyword,\n    'SHOW': tokens.Keyword,\n    'SIMILAR': tokens.Keyword,\n    'SIMPLE': tokens.Keyword,\n    'SIZE': tokens.Keyword,\n    'SOME': tokens.Keyword,\n    'SOURCE': tokens.Keyword,\n    'SPACE': tokens.Keyword,\n    'SPECIFIC': tokens.Keyword,\n    'SPECIFICTYPE': tokens.Keyword,\n    'SPECIFIC_NAME': tokens.Keyword,\n    'SQL': tokens.Keyword,\n    'SQLBUF': tokens.Keyword,\n    'SQLCODE': tokens.Keyword,\n    'SQLERROR': tokens.Keyword,\n    'SQLEXCEPTION': tokens.Keyword,\n    'SQLSTATE': tokens.Keyword,\n    'SQLWARNING': tokens.Keyword,\n    'STABLE': tokens.Keyword,\n    'START': tokens.Keyword.DML,\n    # 'STATE': tokens.Keyword,\n    'STATEMENT': tokens.Keyword,\n    'STATIC': tokens.Keyword,\n    'STATISTICS': tokens.Keyword,\n    'STDIN': tokens.Keyword,\n    'STDOUT': tokens.Keyword,\n    'STORAGE': tokens.Keyword,\n    'STRICT': tokens.Keyword,\n    'STRUCTURE': tokens.Keyword,\n    'STYPE': tokens.Keyword,\n    'SUBCLASS_ORIGIN': tokens.Keyword,\n    'SUBLIST': tokens.Keyword,\n    'SUBSTRING': tokens.Keyword,\n    'SUCCESSFUL': tokens.Keyword,\n    'SUM': tokens.Keyword,\n    'SYMMETRIC': tokens.Keyword,\n    'SYNONYM': tokens.Keyword,\n    'SYSID': tokens.Keyword,\n    'SYSTEM': tokens.Keyword,\n    'SYSTEM_USER': tokens.Keyword,\n\n    'TABLE': tokens.Keyword,\n    'TABLE_NAME': tokens.Keyword,\n    'TEMP': tokens.Keyword,\n    'TEMPLATE': tokens.Keyword,\n    'TEMPORARY': tokens.Keyword,\n    'TERMINATE': tokens.Keyword,\n    'THAN': tokens.Keyword,\n    'TIMESTAMP': tokens.Keyword,\n    'TIMEZONE_HOUR': tokens.Keyword,\n    'TIMEZONE_MINUTE': tokens.Keyword,\n    'TO': tokens.Keyword,\n    'TOAST': tokens.Keyword,\n    'TRAILING': tokens.Keyword,\n    'TRANSATION': tokens.Keyword,\n    'TRANSACTIONS_COMMITTED': tokens.Keyword,\n    'TRANSACTIONS_ROLLED_BACK': tokens.Keyword,\n    'TRANSATION_ACTIVE': tokens.Keyword,\n    'TRANSFORM': tokens.Keyword,\n    'TRANSFORMS': tokens.Keyword,\n    'TRANSLATE': tokens.Keyword,\n    'TRANSLATION': tokens.Keyword,\n    'TREAT': tokens.Keyword,\n    'TRIGGER': tokens.Keyword,\n    'TRIGGER_CATALOG': tokens.Keyword,\n    'TRIGGER_NAME': tokens.Keyword,\n    'TRIGGER_SCHEMA': tokens.Keyword,\n    'TRIM': tokens.Keyword,\n    'TRUE': tokens.Keyword,\n    'TRUNCATE': tokens.Keyword,\n    'TRUSTED': tokens.Keyword,\n    'TYPE': tokens.Keyword,\n\n    'UID': tokens.Keyword,\n    'UNCOMMITTED': tokens.Keyword,\n    'UNDER': tokens.Keyword,\n    'UNENCRYPTED': tokens.Keyword,\n    'UNION': tokens.Keyword,\n    'UNIQUE': tokens.Keyword,\n    'UNKNOWN': tokens.Keyword,\n    'UNLISTEN': tokens.Keyword,\n    'UNNAMED': tokens.Keyword,\n    'UNNEST': tokens.Keyword,\n    'UNTIL': tokens.Keyword,\n    'UPPER': tokens.Keyword,\n    'USAGE': tokens.Keyword,\n    'USE': tokens.Keyword,\n    'USER': tokens.Keyword,\n    'USER_DEFINED_TYPE_CATALOG': tokens.Keyword,\n    'USER_DEFINED_TYPE_NAME': tokens.Keyword,\n    'USER_DEFINED_TYPE_SCHEMA': tokens.Keyword,\n    'USING': tokens.Keyword,\n\n    'VACUUM': tokens.Keyword,\n    'VALID': tokens.Keyword,\n    'VALIDATE': tokens.Keyword,\n    'VALIDATOR': tokens.Keyword,\n    'VALUES': tokens.Keyword,\n    'VARIABLE': tokens.Keyword,\n    'VERBOSE': tokens.Keyword,\n    'VERSION': tokens.Keyword,\n    'VIEW': tokens.Keyword,\n    'VOLATILE': tokens.Keyword,\n\n    'WHENEVER': tokens.Keyword,\n    'WITH': tokens.Keyword.CTE,\n    'WITHOUT': tokens.Keyword,\n    'WORK': tokens.Keyword,\n    'WRITE': tokens.Keyword,\n\n    'YEAR': tokens.Keyword,\n\n    'ZONE': tokens.Keyword,\n\n    # Name.Builtin\n    'ARRAY': tokens.Name.Builtin,\n    'BIGINT': tokens.Name.Builtin,\n    'BINARY': tokens.Name.Builtin,\n    'BIT': tokens.Name.Builtin,\n    'BLOB': tokens.Name.Builtin,\n    'BOOLEAN': tokens.Name.Builtin,\n    'CHAR': tokens.Name.Builtin,\n    'CHARACTER': tokens.Name.Builtin,\n    'DATE': tokens.Name.Builtin,\n    'DEC': tokens.Name.Builtin,\n    'DECIMAL': tokens.Name.Builtin,\n    'FLOAT': tokens.Name.Builtin,\n    'INT': tokens.Name.Builtin,\n    'INT8': tokens.Name.Builtin,\n    'INTEGER': tokens.Name.Builtin,\n    'INTERVAL': tokens.Name.Builtin,\n    'LONG': tokens.Name.Builtin,\n    'NUMBER': tokens.Name.Builtin,\n    'NUMERIC': tokens.Name.Builtin,\n    'REAL': tokens.Name.Builtin,\n    'ROWID': tokens.Name.Builtin,\n    'ROWLABEL': tokens.Name.Builtin,\n    'ROWNUM': tokens.Name.Builtin,\n    'SERIAL': tokens.Name.Builtin,\n    'SERIAL8': tokens.Name.Builtin,\n    'SIGNED': tokens.Name.Builtin,\n    'SMALLINT': tokens.Name.Builtin,\n    'SYSDATE': tokens.Name.Builtin,\n    'TEXT': tokens.Name.Builtin,\n    'TINYINT': tokens.Name.Builtin,\n    'UNSIGNED': tokens.Name.Builtin,\n    'VARCHAR': tokens.Name.Builtin,\n    'VARCHAR2': tokens.Name.Builtin,\n    'VARYING': tokens.Name.Builtin,\n}\n\nKEYWORDS_COMMON = {\n    'SELECT': tokens.Keyword.DML,\n    'INSERT': tokens.Keyword.DML,\n    'DELETE': tokens.Keyword.DML,\n    'UPDATE': tokens.Keyword.DML,\n    'REPLACE': tokens.Keyword.DML,\n    'MERGE': tokens.Keyword.DML,\n    'DROP': tokens.Keyword.DDL,\n    'CREATE': tokens.Keyword.DDL,\n    'ALTER': tokens.Keyword.DDL,\n\n    'WHERE': tokens.Keyword,\n    'FROM': tokens.Keyword,\n    'INNER': tokens.Keyword,\n    'JOIN': tokens.Keyword,\n    'STRAIGHT_JOIN': tokens.Keyword,\n    'AND': tokens.Keyword,\n    'OR': tokens.Keyword,\n    'LIKE': tokens.Keyword,\n    'ON': tokens.Keyword,\n    'IN': tokens.Keyword,\n    'SET': tokens.Keyword,\n\n    'BY': tokens.Keyword,\n    'GROUP': tokens.Keyword,\n    'ORDER': tokens.Keyword,\n    'LEFT': tokens.Keyword,\n    'OUTER': tokens.Keyword,\n    'FULL': tokens.Keyword,\n\n    'IF': tokens.Keyword,\n    'END': tokens.Keyword,\n    'THEN': tokens.Keyword,\n    'LOOP': tokens.Keyword,\n    'AS': tokens.Keyword,\n    'ELSE': tokens.Keyword,\n    'FOR': tokens.Keyword,\n    'WHILE': tokens.Keyword,\n\n    'CASE': tokens.Keyword,\n    'WHEN': tokens.Keyword,\n    'MIN': tokens.Keyword,\n    'MAX': tokens.Keyword,\n    'DISTINCT': tokens.Keyword,\n}\n\nKEYWORDS_ORACLE = {\n    'ARCHIVE': tokens.Keyword,\n    'ARCHIVELOG': tokens.Keyword,\n\n    'BACKUP': tokens.Keyword,\n    'BECOME': tokens.Keyword,\n    'BLOCK': tokens.Keyword,\n    'BODY': tokens.Keyword,\n\n    'CANCEL': tokens.Keyword,\n    'CHANGE': tokens.Keyword,\n    'COMPILE': tokens.Keyword,\n    'CONTENTS': tokens.Keyword,\n    'CONTROLFILE': tokens.Keyword,\n\n    'DATAFILE': tokens.Keyword,\n    'DBA': tokens.Keyword,\n    'DISMOUNT': tokens.Keyword,\n    'DOUBLE': tokens.Keyword,\n    'DUMP': tokens.Keyword,\n\n    'EVENTS': tokens.Keyword,\n    'EXCEPTIONS': tokens.Keyword,\n    'EXPLAIN': tokens.Keyword,\n    'EXTENT': tokens.Keyword,\n    'EXTERNALLY': tokens.Keyword,\n\n    'FLUSH': tokens.Keyword,\n    'FREELIST': tokens.Keyword,\n    'FREELISTS': tokens.Keyword,\n\n    # groups seems too common as table name\n    # 'GROUPS': tokens.Keyword,\n\n    'INDICATOR': tokens.Keyword,\n    'INITRANS': tokens.Keyword,\n    'INSTANCE': tokens.Keyword,\n\n    'LAYER': tokens.Keyword,\n    'LINK': tokens.Keyword,\n    'LISTS': tokens.Keyword,\n    'LOGFILE': tokens.Keyword,\n\n    'MANAGE': tokens.Keyword,\n    'MANUAL': tokens.Keyword,\n    'MAXDATAFILES': tokens.Keyword,\n    'MAXINSTANCES': tokens.Keyword,\n    'MAXLOGFILES': tokens.Keyword,\n    'MAXLOGHISTORY': tokens.Keyword,\n    'MAXLOGMEMBERS': tokens.Keyword,\n    'MAXTRANS': tokens.Keyword,\n    'MINEXTENTS': tokens.Keyword,\n    'MODULE': tokens.Keyword,\n    'MOUNT': tokens.Keyword,\n\n    'NOARCHIVELOG': tokens.Keyword,\n    'NOCACHE': tokens.Keyword,\n    'NOCYCLE': tokens.Keyword,\n    'NOMAXVALUE': tokens.Keyword,\n    'NOMINVALUE': tokens.Keyword,\n    'NOORDER': tokens.Keyword,\n    'NORESETLOGS': tokens.Keyword,\n    'NORMAL': tokens.Keyword,\n    'NOSORT': tokens.Keyword,\n\n    'OPTIMAL': tokens.Keyword,\n    'OWN': tokens.Keyword,\n\n    'PACKAGE': tokens.Keyword,\n    'PARALLEL': tokens.Keyword,\n    'PCTINCREASE': tokens.Keyword,\n    'PCTUSED': tokens.Keyword,\n    'PLAN': tokens.Keyword,\n    'PRIVATE': tokens.Keyword,\n    'PROFILE': tokens.Keyword,\n\n    'QUOTA': tokens.Keyword,\n\n    'RECOVER': tokens.Keyword,\n    'RESETLOGS': tokens.Keyword,\n    'RESTRICTED': tokens.Keyword,\n    'REUSE': tokens.Keyword,\n    'ROLES': tokens.Keyword,\n\n    'SAVEPOINT': tokens.Keyword,\n    'SCN': tokens.Keyword,\n    'SECTION': tokens.Keyword,\n    'SEGMENT': tokens.Keyword,\n    'SHARED': tokens.Keyword,\n    'SNAPSHOT': tokens.Keyword,\n    'SORT': tokens.Keyword,\n    'STATEMENT_ID': tokens.Keyword,\n    'STOP': tokens.Keyword,\n    'SWITCH': tokens.Keyword,\n\n    'TABLES': tokens.Keyword,\n    'TABLESPACE': tokens.Keyword,\n    'THREAD': tokens.Keyword,\n    'TIME': tokens.Keyword,\n    'TRACING': tokens.Keyword,\n    'TRANSACTION': tokens.Keyword,\n    'TRIGGERS': tokens.Keyword,\n\n    'UNLIMITED': tokens.Keyword,\n}\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/lexer.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\n\"\"\"SQL Lexer\"\"\"\n\n# This code is based on the SqlLexer in pygments.\n# http://pygments.org/\n# It's separated from the rest of pygments to increase performance\n# and to allow some customizations.\n\nfrom sqlparse import tokens\nfrom sqlparse.keywords import SQL_REGEX\nfrom sqlparse.compat import bytes_type, text_type, file_types\nfrom sqlparse.utils import consume\n\n\nclass Lexer(object):\n    \"\"\"Lexer\n    Empty class. Leaving for backwards-compatibility\n    \"\"\"\n\n    @staticmethod\n    def get_tokens(text, encoding=None):\n        \"\"\"\n        Return an iterable of (tokentype, value) pairs generated from\n        `text`. If `unfiltered` is set to `True`, the filtering mechanism\n        is bypassed even if filters are defined.\n\n        Also preprocess the text, i.e. expand tabs and strip it if\n        wanted and applies registered filters.\n\n        Split ``text`` into (tokentype, text) pairs.\n\n        ``stack`` is the inital stack (default: ``['root']``)\n        \"\"\"\n        if isinstance(text, file_types):\n            text = text.read()\n\n        if isinstance(text, text_type):\n            pass\n        elif isinstance(text, bytes_type):\n            if encoding:\n                text = text.decode(encoding)\n            else:\n                try:\n                    text = text.decode('utf-8')\n                except UnicodeDecodeError:\n                    text = text.decode('unicode-escape')\n        else:\n            raise TypeError(u\"Expected text or file-like object, got {!r}\".\n                            format(type(text)))\n\n        iterable = enumerate(text)\n        for pos, char in iterable:\n            for rexmatch, action in SQL_REGEX:\n                m = rexmatch(text, pos)\n\n                if not m:\n                    continue\n                elif isinstance(action, tokens._TokenType):\n                    yield action, m.group()\n                elif callable(action):\n                    yield action(m.group())\n\n                consume(iterable, m.end() - pos - 1)\n                break\n            else:\n                yield tokens.Error, char\n\n\ndef tokenize(sql, encoding=None):\n    \"\"\"Tokenize sql.\n\n    Tokenize *sql* using the :class:`Lexer` and return a 2-tuple stream\n    of ``(token type, value)`` items.\n    \"\"\"\n    return Lexer().get_tokens(sql, encoding)\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/sql.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\n\"\"\"This module contains classes representing syntactical elements of SQL.\"\"\"\nfrom __future__ import print_function\n\nimport re\n\nfrom sqlparse import tokens as T\nfrom sqlparse.compat import string_types, text_type, unicode_compatible\nfrom sqlparse.utils import imt, remove_quotes\n\n\n@unicode_compatible\nclass Token(object):\n    \"\"\"Base class for all other classes in this module.\n\n    It represents a single token and has two instance attributes:\n    ``value`` is the unchange value of the token and ``ttype`` is\n    the type of the token.\n    \"\"\"\n\n    __slots__ = ('value', 'ttype', 'parent', 'normalized', 'is_keyword',\n                 'is_group', 'is_whitespace')\n\n    def __init__(self, ttype, value):\n        value = text_type(value)\n        self.value = value\n        self.ttype = ttype\n        self.parent = None\n        self.is_group = False\n        self.is_keyword = ttype in T.Keyword\n        self.is_whitespace = self.ttype in T.Whitespace\n        self.normalized = value.upper() if self.is_keyword else value\n\n    def __str__(self):\n        return self.value\n\n    # Pending tokenlist __len__ bug fix\n    # def __len__(self):\n    #     return len(self.value)\n\n    def __repr__(self):\n        cls = self._get_repr_name()\n        value = self._get_repr_value()\n\n        q = u'\"' if value.startswith(\"'\") and value.endswith(\"'\") else u\"'\"\n        return u\"<{cls} {q}{value}{q} at 0x{id:2X}>\".format(\n            id=id(self), **locals())\n\n    def _get_repr_name(self):\n        return str(self.ttype).split('.')[-1]\n\n    def _get_repr_value(self):\n        raw = text_type(self)\n        if len(raw) > 7:\n            raw = raw[:6] + '...'\n        return re.sub(r'\\s+', ' ', raw)\n\n    def flatten(self):\n        \"\"\"Resolve subgroups.\"\"\"\n        yield self\n\n    def match(self, ttype, values, regex=False):\n        \"\"\"Checks whether the token matches the given arguments.\n\n        *ttype* is a token type. If this token doesn't match the given token\n        type.\n        *values* is a list of possible values for this token. The values\n        are OR'ed together so if only one of the values matches ``True``\n        is returned. Except for keyword tokens the comparison is\n        case-sensitive. For convenience it's ok to pass in a single string.\n        If *regex* is ``True`` (default is ``False``) the given values are\n        treated as regular expressions.\n        \"\"\"\n        type_matched = self.ttype is ttype\n        if not type_matched or values is None:\n            return type_matched\n\n        if isinstance(values, string_types):\n            values = (values,)\n\n        if regex:\n            # TODO: Add test for regex with is_keyboard = false\n            flag = re.IGNORECASE if self.is_keyword else 0\n            values = (re.compile(v, flag) for v in values)\n\n            for pattern in values:\n                if pattern.search(self.normalized):\n                    return True\n            return False\n\n        if self.is_keyword:\n            values = (v.upper() for v in values)\n\n        return self.normalized in values\n\n    def within(self, group_cls):\n        \"\"\"Returns ``True`` if this token is within *group_cls*.\n\n        Use this method for example to check if an identifier is within\n        a function: ``t.within(sql.Function)``.\n        \"\"\"\n        parent = self.parent\n        while parent:\n            if isinstance(parent, group_cls):\n                return True\n            parent = parent.parent\n        return False\n\n    def is_child_of(self, other):\n        \"\"\"Returns ``True`` if this token is a direct child of *other*.\"\"\"\n        return self.parent == other\n\n    def has_ancestor(self, other):\n        \"\"\"Returns ``True`` if *other* is in this tokens ancestry.\"\"\"\n        parent = self.parent\n        while parent:\n            if parent == other:\n                return True\n            parent = parent.parent\n        return False\n\n\n@unicode_compatible\nclass TokenList(Token):\n    \"\"\"A group of tokens.\n\n    It has an additional instance attribute ``tokens`` which holds a\n    list of child-tokens.\n    \"\"\"\n\n    __slots__ = 'tokens'\n\n    def __init__(self, tokens=None):\n        self.tokens = tokens or []\n        [setattr(token, 'parent', self) for token in tokens]\n        super(TokenList, self).__init__(None, text_type(self))\n        self.is_group = True\n\n    def __str__(self):\n        return u''.join(token.value for token in self.flatten())\n\n    # weird bug\n    # def __len__(self):\n    #     return len(self.tokens)\n\n    def __iter__(self):\n        return iter(self.tokens)\n\n    def __getitem__(self, item):\n        return self.tokens[item]\n\n    def _get_repr_name(self):\n        return type(self).__name__\n\n    def _pprint_tree(self, max_depth=None, depth=0, f=None):\n        \"\"\"Pretty-print the object tree.\"\"\"\n        indent = u' | ' * depth\n        for idx, token in enumerate(self.tokens):\n            cls = token._get_repr_name()\n            value = token._get_repr_value()\n\n            q = u'\"' if value.startswith(\"'\") and value.endswith(\"'\") else u\"'\"\n            print(u\"{indent}{idx:2d} {cls} {q}{value}{q}\"\n                  .format(**locals()), file=f)\n\n            if token.is_group and (max_depth is None or depth < max_depth):\n                token._pprint_tree(max_depth, depth + 1, f)\n\n    def get_token_at_offset(self, offset):\n        \"\"\"Returns the token that is on position offset.\"\"\"\n        idx = 0\n        for token in self.flatten():\n            end = idx + len(token.value)\n            if idx <= offset < end:\n                return token\n            idx = end\n\n    def flatten(self):\n        \"\"\"Generator yielding ungrouped tokens.\n\n        This method is recursively called for all child tokens.\n        \"\"\"\n        for token in self.tokens:\n            if token.is_group:\n                for item in token.flatten():\n                    yield item\n            else:\n                yield token\n\n    def get_sublists(self):\n        for token in self.tokens:\n            if token.is_group:\n                yield token\n\n    @property\n    def _groupable_tokens(self):\n        return self.tokens\n\n    def _token_matching(self, funcs, start=0, end=None, reverse=False):\n        \"\"\"next token that match functions\"\"\"\n        if start is None:\n            return None\n\n        if not isinstance(funcs, (list, tuple)):\n            funcs = (funcs,)\n\n        if reverse:\n            assert end is None\n            for idx in range(start - 2, -1, -1):\n                token = self.tokens[idx]\n                for func in funcs:\n                    if func(token):\n                        return idx, token\n        else:\n            for idx, token in enumerate(self.tokens[start:end], start=start):\n                for func in funcs:\n                    if func(token):\n                        return idx, token\n        return None, None\n\n    def token_first(self, skip_ws=True, skip_cm=False):\n        \"\"\"Returns the first child token.\n\n        If *skip_ws* is ``True`` (the default), whitespace\n        tokens are ignored.\n\n        if *skip_cm* is ``True`` (default: ``False``), comments are\n        ignored too.\n        \"\"\"\n        # this on is inconsistent, using Comment instead of T.Comment...\n        funcs = lambda tk: not ((skip_ws and tk.is_whitespace) or\n                                (skip_cm and imt(tk, t=T.Comment, i=Comment)))\n        return self._token_matching(funcs)[1]\n\n    def token_next_by(self, i=None, m=None, t=None, idx=-1, end=None):\n        funcs = lambda tk: imt(tk, i, m, t)\n        idx += 1\n        return self._token_matching(funcs, idx, end)\n\n    def token_not_matching(self, funcs, idx):\n        funcs = (funcs,) if not isinstance(funcs, (list, tuple)) else funcs\n        funcs = [lambda tk: not func(tk) for func in funcs]\n        return self._token_matching(funcs, idx)\n\n    def token_matching(self, funcs, idx):\n        return self._token_matching(funcs, idx)[1]\n\n    def token_prev(self, idx, skip_ws=True, skip_cm=False):\n        \"\"\"Returns the previous token relative to *idx*.\n\n        If *skip_ws* is ``True`` (the default) whitespace tokens are ignored.\n        If *skip_cm* is ``True`` comments are ignored.\n        ``None`` is returned if there's no previous token.\n        \"\"\"\n        return self.token_next(idx, skip_ws, skip_cm, _reverse=True)\n\n    # TODO: May need to re-add default value to idx\n    def token_next(self, idx, skip_ws=True, skip_cm=False, _reverse=False):\n        \"\"\"Returns the next token relative to *idx*.\n\n        If *skip_ws* is ``True`` (the default) whitespace tokens are ignored.\n        If *skip_cm* is ``True`` comments are ignored.\n        ``None`` is returned if there's no next token.\n        \"\"\"\n        if idx is None:\n            return None, None\n        idx += 1  # alot of code usage current pre-compensates for this\n        funcs = lambda tk: not ((skip_ws and tk.is_whitespace) or\n                                (skip_cm and imt(tk, t=T.Comment, i=Comment)))\n        return self._token_matching(funcs, idx, reverse=_reverse)\n\n    def token_index(self, token, start=0):\n        \"\"\"Return list index of token.\"\"\"\n        start = start if isinstance(start, int) else self.token_index(start)\n        return start + self.tokens[start:].index(token)\n\n    def group_tokens(self, grp_cls, start, end, include_end=True,\n                     extend=False):\n        \"\"\"Replace tokens by an instance of *grp_cls*.\"\"\"\n        start_idx = start\n        start = self.tokens[start_idx]\n\n        end_idx = end + include_end\n\n        # will be needed later for new group_clauses\n        # while skip_ws and tokens and tokens[-1].is_whitespace:\n        #     tokens = tokens[:-1]\n\n        if extend and isinstance(start, grp_cls):\n            subtokens = self.tokens[start_idx + 1:end_idx]\n\n            grp = start\n            grp.tokens.extend(subtokens)\n            del self.tokens[start_idx + 1:end_idx]\n            grp.value = text_type(start)\n        else:\n            subtokens = self.tokens[start_idx:end_idx]\n            grp = grp_cls(subtokens)\n            self.tokens[start_idx:end_idx] = [grp]\n            grp.parent = self\n\n        for token in subtokens:\n            token.parent = grp\n\n        return grp\n\n    def insert_before(self, where, token):\n        \"\"\"Inserts *token* before *where*.\"\"\"\n        if not isinstance(where, int):\n            where = self.token_index(where)\n        token.parent = self\n        self.tokens.insert(where, token)\n\n    def insert_after(self, where, token, skip_ws=True):\n        \"\"\"Inserts *token* after *where*.\"\"\"\n        if not isinstance(where, int):\n            where = self.token_index(where)\n        nidx, next_ = self.token_next(where, skip_ws=skip_ws)\n        token.parent = self\n        if next_ is None:\n            self.tokens.append(token)\n        else:\n            self.tokens.insert(nidx, token)\n\n    def has_alias(self):\n        \"\"\"Returns ``True`` if an alias is present.\"\"\"\n        return self.get_alias() is not None\n\n    def get_alias(self):\n        \"\"\"Returns the alias for this identifier or ``None``.\"\"\"\n\n        # \"name AS alias\"\n        kw_idx, kw = self.token_next_by(m=(T.Keyword, 'AS'))\n        if kw is not None:\n            return self._get_first_name(kw_idx + 1, keywords=True)\n\n        # \"name alias\" or \"complicated column expression alias\"\n        _, ws = self.token_next_by(t=T.Whitespace)\n        if len(self.tokens) > 2 and ws is not None:\n            return self._get_first_name(reverse=True)\n\n    def get_name(self):\n        \"\"\"Returns the name of this identifier.\n\n        This is either it's alias or it's real name. The returned valued can\n        be considered as the name under which the object corresponding to\n        this identifier is known within the current statement.\n        \"\"\"\n        return self.get_alias() or self.get_real_name()\n\n    def get_real_name(self):\n        \"\"\"Returns the real name (object name) of this identifier.\"\"\"\n        # a.b\n        dot_idx, _ = self.token_next_by(m=(T.Punctuation, '.'))\n        return self._get_first_name(dot_idx)\n\n    def get_parent_name(self):\n        \"\"\"Return name of the parent object if any.\n\n        A parent object is identified by the first occuring dot.\n        \"\"\"\n        dot_idx, _ = self.token_next_by(m=(T.Punctuation, '.'))\n        _, prev_ = self.token_prev(dot_idx)\n        return remove_quotes(prev_.value) if prev_ is not None else None\n\n    def _get_first_name(self, idx=None, reverse=False, keywords=False):\n        \"\"\"Returns the name of the first token with a name\"\"\"\n\n        tokens = self.tokens[idx:] if idx else self.tokens\n        tokens = reversed(tokens) if reverse else tokens\n        types = [T.Name, T.Wildcard, T.String.Symbol]\n\n        if keywords:\n            types.append(T.Keyword)\n\n        for token in tokens:\n            if token.ttype in types:\n                return remove_quotes(token.value)\n            elif isinstance(token, (Identifier, Function)):\n                return token.get_name()\n\n\nclass Statement(TokenList):\n    \"\"\"Represents a SQL statement.\"\"\"\n\n    def get_type(self):\n        \"\"\"Returns the type of a statement.\n\n        The returned value is a string holding an upper-cased reprint of\n        the first DML or DDL keyword. If the first token in this group\n        isn't a DML or DDL keyword \"UNKNOWN\" is returned.\n\n        Whitespaces and comments at the beginning of the statement\n        are ignored.\n        \"\"\"\n        first_token = self.token_first(skip_cm=True)\n        if first_token is None:\n            # An \"empty\" statement that either has not tokens at all\n            # or only whitespace tokens.\n            return 'UNKNOWN'\n\n        elif first_token.ttype in (T.Keyword.DML, T.Keyword.DDL):\n            return first_token.normalized\n\n        elif first_token.ttype == T.Keyword.CTE:\n            # The WITH keyword should be followed by either an Identifier or\n            # an IdentifierList containing the CTE definitions;  the actual\n            # DML keyword (e.g. SELECT, INSERT) will follow next.\n            fidx = self.token_index(first_token)\n            tidx, token = self.token_next(fidx, skip_ws=True)\n            if isinstance(token, (Identifier, IdentifierList)):\n                _, dml_keyword = self.token_next(tidx, skip_ws=True)\n\n                if dml_keyword.ttype == T.Keyword.DML:\n                    return dml_keyword.normalized\n\n        # Hmm, probably invalid syntax, so return unknown.\n        return 'UNKNOWN'\n\n\nclass Identifier(TokenList):\n    \"\"\"Represents an identifier.\n\n    Identifiers may have aliases or typecasts.\n    \"\"\"\n\n    def is_wildcard(self):\n        \"\"\"Return ``True`` if this identifier contains a wildcard.\"\"\"\n        _, token = self.token_next_by(t=T.Wildcard)\n        return token is not None\n\n    def get_typecast(self):\n        \"\"\"Returns the typecast or ``None`` of this object as a string.\"\"\"\n        midx, marker = self.token_next_by(m=(T.Punctuation, '::'))\n        nidx, next_ = self.token_next(midx, skip_ws=False)\n        return next_.value if next_ else None\n\n    def get_ordering(self):\n        \"\"\"Returns the ordering or ``None`` as uppercase string.\"\"\"\n        _, ordering = self.token_next_by(t=T.Keyword.Order)\n        return ordering.normalized if ordering else None\n\n    def get_array_indices(self):\n        \"\"\"Returns an iterator of index token lists\"\"\"\n\n        for token in self.tokens:\n            if isinstance(token, SquareBrackets):\n                # Use [1:-1] index to discard the square brackets\n                yield token.tokens[1:-1]\n\n\nclass IdentifierList(TokenList):\n    \"\"\"A list of :class:`~sqlparse.sql.Identifier`\\'s.\"\"\"\n\n    def get_identifiers(self):\n        \"\"\"Returns the identifiers.\n\n        Whitespaces and punctuations are not included in this generator.\n        \"\"\"\n        for token in self.tokens:\n            if not (token.is_whitespace or token.match(T.Punctuation, ',')):\n                yield token\n\n\nclass Parenthesis(TokenList):\n    \"\"\"Tokens between parenthesis.\"\"\"\n    M_OPEN = T.Punctuation, '('\n    M_CLOSE = T.Punctuation, ')'\n\n    @property\n    def _groupable_tokens(self):\n        return self.tokens[1:-1]\n\n\nclass SquareBrackets(TokenList):\n    \"\"\"Tokens between square brackets\"\"\"\n    M_OPEN = T.Punctuation, '['\n    M_CLOSE = T.Punctuation, ']'\n\n    @property\n    def _groupable_tokens(self):\n        return self.tokens[1:-1]\n\n\nclass Assignment(TokenList):\n    \"\"\"An assignment like 'var := val;'\"\"\"\n\n\nclass If(TokenList):\n    \"\"\"An 'if' clause with possible 'else if' or 'else' parts.\"\"\"\n    M_OPEN = T.Keyword, 'IF'\n    M_CLOSE = T.Keyword, 'END IF'\n\n\nclass For(TokenList):\n    \"\"\"A 'FOR' loop.\"\"\"\n    M_OPEN = T.Keyword, ('FOR', 'FOREACH')\n    M_CLOSE = T.Keyword, 'END LOOP'\n\n\nclass Comparison(TokenList):\n    \"\"\"A comparison used for example in WHERE clauses.\"\"\"\n\n    @property\n    def left(self):\n        return self.tokens[0]\n\n    @property\n    def right(self):\n        return self.tokens[-1]\n\n\nclass Comment(TokenList):\n    \"\"\"A comment.\"\"\"\n\n    def is_multiline(self):\n        return self.tokens and self.tokens[0].ttype == T.Comment.Multiline\n\n\nclass Where(TokenList):\n    \"\"\"A WHERE clause.\"\"\"\n    M_OPEN = T.Keyword, 'WHERE'\n    M_CLOSE = T.Keyword, ('ORDER', 'GROUP', 'LIMIT', 'UNION', 'EXCEPT',\n                          'HAVING', 'RETURNING', 'INTO')\n\n\nclass Case(TokenList):\n    \"\"\"A CASE statement with one or more WHEN and possibly an ELSE part.\"\"\"\n    M_OPEN = T.Keyword, 'CASE'\n    M_CLOSE = T.Keyword, 'END'\n\n    def get_cases(self, skip_ws=False):\n        \"\"\"Returns a list of 2-tuples (condition, value).\n\n        If an ELSE exists condition is None.\n        \"\"\"\n        CONDITION = 1\n        VALUE = 2\n\n        ret = []\n        mode = CONDITION\n\n        for token in self.tokens:\n            # Set mode from the current statement\n            if token.match(T.Keyword, 'CASE'):\n                continue\n\n            elif skip_ws and token.ttype in T.Whitespace:\n                continue\n\n            elif token.match(T.Keyword, 'WHEN'):\n                ret.append(([], []))\n                mode = CONDITION\n\n            elif token.match(T.Keyword, 'THEN'):\n                mode = VALUE\n\n            elif token.match(T.Keyword, 'ELSE'):\n                ret.append((None, []))\n                mode = VALUE\n\n            elif token.match(T.Keyword, 'END'):\n                mode = None\n\n            # First condition without preceding WHEN\n            if mode and not ret:\n                ret.append(([], []))\n\n            # Append token depending of the current mode\n            if mode == CONDITION:\n                ret[-1][0].append(token)\n\n            elif mode == VALUE:\n                ret[-1][1].append(token)\n\n        # Return cases list\n        return ret\n\n\nclass Function(TokenList):\n    \"\"\"A function or procedure call.\"\"\"\n\n    def get_parameters(self):\n        \"\"\"Return a list of parameters.\"\"\"\n        parenthesis = self.tokens[-1]\n        for token in parenthesis.tokens:\n            if isinstance(token, IdentifierList):\n                return token.get_identifiers()\n            elif imt(token, i=(Function, Identifier), t=T.Literal):\n                return [token, ]\n        return []\n\n\nclass Begin(TokenList):\n    \"\"\"A BEGIN/END block.\"\"\"\n    M_OPEN = T.Keyword, 'BEGIN'\n    M_CLOSE = T.Keyword, 'END'\n\n\nclass Operation(TokenList):\n    \"\"\"Grouping of operations\"\"\"\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/tokens.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n#\n# The Token implementation is based on pygment's token system written\n# by Georg Brandl.\n# http://pygments.org/\n\n\"\"\"Tokens\"\"\"\n\n\nclass _TokenType(tuple):\n    parent = None\n\n    def __contains__(self, item):\n        return item is not None and (self is item or item[:len(self)] == self)\n\n    def __getattr__(self, name):\n        new = _TokenType(self + (name,))\n        setattr(self, name, new)\n        new.parent = self\n        return new\n\n    def __repr__(self):\n        # self can be False only if its the `root` ie. Token itself\n        return 'Token' + ('.' if self else '') + '.'.join(self)\n\n\nToken = _TokenType()\n\n# Special token types\nText = Token.Text\nWhitespace = Text.Whitespace\nNewline = Whitespace.Newline\nError = Token.Error\n# Text that doesn't belong to this lexer (e.g. HTML in PHP)\nOther = Token.Other\n\n# Common token types for source code\nKeyword = Token.Keyword\nName = Token.Name\nLiteral = Token.Literal\nString = Literal.String\nNumber = Literal.Number\nPunctuation = Token.Punctuation\nOperator = Token.Operator\nComparison = Operator.Comparison\nWildcard = Token.Wildcard\nComment = Token.Comment\nAssignment = Token.Assignment\n\n# Generic types for non-source code\nGeneric = Token.Generic\n\n# String and some others are not direct childs of Token.\n# alias them:\nToken.Token = Token\nToken.String = String\nToken.Number = Number\n\n# SQL specific tokens\nDML = Keyword.DML\nDDL = Keyword.DDL\nCTE = Keyword.CTE\nCommand = Keyword.Command\n"
  },
  {
    "path": "SQLToolsAPI/lib/sqlparse/utils.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com\n#\n# This module is part of python-sqlparse and is released under\n# the BSD License: https://opensource.org/licenses/BSD-3-Clause\n\nimport itertools\nimport re\nfrom collections import deque\nfrom contextlib import contextmanager\nfrom sqlparse.compat import text_type\n\n# This regular expression replaces the home-cooked parser that was here before.\n# It is much faster, but requires an extra post-processing step to get the\n# desired results (that are compatible with what you would expect from the\n# str.splitlines() method).\n#\n# It matches groups of characters: newlines, quoted strings, or unquoted text,\n# and splits on that basis. The post-processing step puts those back together\n# into the actual lines of SQL.\nSPLIT_REGEX = re.compile(r\"\"\"\n(\n (?:                     # Start of non-capturing group\n  (?:\\r\\n|\\r|\\n)      |  # Match any single newline, or\n  [^\\r\\n'\"]+          |  # Match any character series without quotes or\n                         # newlines, or\n  \"(?:[^\"\\\\]|\\\\.)*\"   |  # Match double-quoted strings, or\n  '(?:[^'\\\\]|\\\\.)*'      # Match single quoted strings\n )\n)\n\"\"\", re.VERBOSE)\n\nLINE_MATCH = re.compile(r'(\\r\\n|\\r|\\n)')\n\n\ndef split_unquoted_newlines(stmt):\n    \"\"\"Split a string on all unquoted newlines.\n\n    Unlike str.splitlines(), this will ignore CR/LF/CR+LF if the requisite\n    character is inside of a string.\"\"\"\n    text = text_type(stmt)\n    lines = SPLIT_REGEX.split(text)\n    outputlines = ['']\n    for line in lines:\n        if not line:\n            continue\n        elif LINE_MATCH.match(line):\n            outputlines.append('')\n        else:\n            outputlines[-1] += line\n    return outputlines\n\n\ndef remove_quotes(val):\n    \"\"\"Helper that removes surrounding quotes from strings.\"\"\"\n    if val is None:\n        return\n    if val[0] in ('\"', \"'\") and val[0] == val[-1]:\n        val = val[1:-1]\n    return val\n\n\ndef recurse(*cls):\n    \"\"\"Function decorator to help with recursion\n\n    :param cls: Classes to not recurse over\n    :return: function\n    \"\"\"\n    def wrap(f):\n        def wrapped_f(tlist):\n            for sgroup in tlist.get_sublists():\n                if not isinstance(sgroup, cls):\n                    wrapped_f(sgroup)\n            f(tlist)\n\n        return wrapped_f\n\n    return wrap\n\n\ndef imt(token, i=None, m=None, t=None):\n    \"\"\"Helper function to simplify comparisons Instance, Match and TokenType\n    :param token:\n    :param i: Class or Tuple/List of Classes\n    :param m: Tuple of TokenType & Value. Can be list of Tuple for multiple\n    :param t: TokenType or Tuple/List of TokenTypes\n    :return:  bool\n    \"\"\"\n    clss = i\n    types = [t, ] if t and not isinstance(t, list) else t\n    mpatterns = [m, ] if m and not isinstance(m, list) else m\n\n    if token is None:\n        return False\n    elif clss and isinstance(token, clss):\n        return True\n    elif mpatterns and any((token.match(*pattern) for pattern in mpatterns)):\n        return True\n    elif types and any([token.ttype in ttype for ttype in types]):\n        return True\n    else:\n        return False\n\n\ndef consume(iterator, n):\n    \"\"\"Advance the iterator n-steps ahead. If n is none, consume entirely.\"\"\"\n    deque(itertools.islice(iterator, n), maxlen=0)\n\n\n@contextmanager\ndef offset(filter_, n=0):\n    filter_.offset += n\n    yield\n    filter_.offset -= n\n\n\n@contextmanager\ndef indent(filter_, n=1):\n    filter_.indent += n\n    yield\n    filter_.indent -= n\n"
  },
  {
    "path": "SQLToolsConnections.sublime-settings",
    "content": "{\n  \"connections\": {\n  /*\n    \"Generic Template\": {      // Connection name, used in menu (Display name)\n      // connection properties set to \"null\" will prompt for value when connecting\n      \"type\"     : \"pgsql\",    // DB type: (mysql, pgsql, oracle, vertica, sqlite, firebird, sqsh)\n      \"host\"     : \"HOSTNAME\", // DB host to connect to\n      \"port\"     :  PORT,      // DB port\n      \"database\" : \"DATABASE\", // DB name (for SQLite this is the path to DB file)\n      \"username\" : \"USERNAME\", // DB username\n      \"password\" : \"PASSWORD\", // DB password (see RDMBS specific comments below)\n      \"encoding\" : \"utf-8\"     // DB encoding. Default: utf-8\n    },\n    \"Connection MySQL\": {\n      \"type\"    : \"mysql\",\n      \"host\"    : \"127.0.0.1\",\n      \"port\"    :  3306,\n      \"database\": \"dbname\",\n      \"username\": \"user\",\n      // use of password for MySQL is not recommended (use \"defaults-extra-file\" or \"login-path\")\n      \"password\": \"password\",  // you will get a security warning in the output\n      // \"defaults-extra-file\": \"/path/to/defaults_file_with_password\",  // use [client] or [mysql] section\n      // \"login-path\": \"your_login_path\",  // login path in your \".mylogin.cnf\"\n      \"default-character-set\": \"utf8\",\n      \"encoding\": \"utf-8\"\n    },\n    \"Connection PostgreSQL\": {\n      \"type\"    : \"pgsql\",\n      \"host\"    : \"127.0.0.1\",\n      \"port\"    :  5432,\n      \"database\": \"dbname\",\n      \"username\": \"anotheruser\",\n      // password is optional (setup \"pgpass.conf\" file instead)\n      \"password\": \"password\",\n      \"encoding\": \"utf-8\"\n    },\n    \"Connection Oracle\": {\n      \"type\"    : \"oracle\",\n      \"host\"    : \"127.0.0.1\",\n      \"port\"    :  1521,\n      \"database\": \"dbname\",\n      \"username\": \"anotheruser\",\n      \"password\": \"password\",\n      \"service\" : \"servicename\",\n      // nls_lang is optional\n      \"nls_lang\": \"american_america.al32utf8\",\n      \"encoding\": \"utf-8\"\n    },\n    \"Connection MSSQL\": {\n      \"type\"    : \"mssql\",\n      // use either (\"host\", \"port\") and remove \"instance\"\n      // or (\"host\", \"instance\") and remove \"port\"\n      \"host\"    : \"localhost\",\n      \"instance\": \"SQLEXPRESS\",\n      // \"port\"    :  1433,\n      // \"username\" and \"password\" are optional (remove if not needed)\n      \"username\": \"sa\",\n      \"password\": \"password\",\n      \"database\": \"sample\",\n      \"encoding\": \"utf-8\"\n    },\n    \"Connection SQLite\": {\n      \"type\"    : \"sqlite\",\n      // note the forward slashes in path\n      \"database\": \"c:/sqlite/sample_db/chinook.db\",\n      \"encoding\": \"utf-8\"\n    },\n    \"Connection Vertica\": {\n      \"type\"    : \"vertica\",\n      \"host\"    : \"localhost\",\n      \"port\"    :  5433,\n      \"username\": \"anotheruser\",\n      \"password\": \"password\",\n      \"database\": \"dbname\",\n      \"encoding\": \"utf-8\"\n    },\n    \"Connection Firebird\": {\n      \"type\"    : \"firebird\",\n      \"host\"    : \"localhost\",\n      \"port\"    :  3050,\n      \"username\": \"sysdba\",\n      \"password\": \"password\",\n      // note the forward slashes (if path is used)\n      \"database\": \"c:/firebird/examples/empbuild/employee.fdb\",\n      \"encoding\": \"utf-8\"\n    },\n    \"Connection Snowflake\": {\n      \"type\"    : \"snowsql\",\n      \"database\": \"database\",\n      // for possible authentication configurations see\n      // https://docs.snowflake.net/manuals/user-guide/snowsql-start.html#authenticator\n      \"user\"    : \"user@example.com\",\n      \"account\" : \"account_name\",\n      \"auth\":   : \"snowflake | externalbrowser | <okta-url>\",\n      // if using \"auth\": \"snowflake\", provide a password\n      // you can alternatively set SNOWSQL_PWD in you environment instead\n      // if using \"auth\": \"externalbrowser\" or \"<okta-url>\", no password needed\n      \"password\": \"pwd\"\n    }\n  */\n  },\n  \"default\": null\n}\n"
  },
  {
    "path": "SQLToolsSavedQueries.sublime-settings",
    "content": "{\n}\n"
  },
  {
    "path": "messages/install.md",
    "content": "# SQLTools\n===============\n\nYour swiss knife SQL for Sublime Text.\n\nWrite your SQL with smart completions and handy table and function definitions, execute SQL and explain queries, format your queries and save them in history.\n\nProject website: https://code.mteixeira.dev/SublimeText-SQLTools/\n\n## Features\n\n* Works with PostgreSQL, MySQL, Oracle, MSSQL, SQLite, Vertica, Firebird and Snowflake\n* Smart completions (except SQLite)\n* Run SQL Queries  `CTRL+e, CTRL+e`\n* View table description  `CTRL+e, CTRL+d`\n* Show table records  `CTRL+e, CTRL+s`\n* Show explain plan for queries  `CTRL+e, CTRL+x`\n* Formatting SQL Queries  `CTRL+e, CTRL+b`\n* View Queries history  `CTRL+e, CTRL+h`\n* Save queries  `CTRL+e, CTRL+q`\n* List and Run saved queries  `CTRL+e, CTRL+l`\n* Remove saved queries  `CTRL+e, CTRL+r`\n* Threading support to prevent lockups\n* Query timeout (kill thread if query takes too long)\n\n## Configuration \n\nDocumentation: https://code.mteixeira.dev/SublimeText-SQLTools/\n"
  },
  {
    "path": "messages/v0.1.6.md",
    "content": "# SQLTools\n===============\n\nYour swiss knife SQL for Sublime Text.\n\n\n## v0.1.6 Changelog\n\n### Improvements\n* History sorted reversed (newer queries first)\n* Some package improvements (auto reload)\n\n### Fixes\n\n* Issue #5 - Command window is now hidden\n* Issue #9 - Fixed buildArgs\n"
  },
  {
    "path": "messages/v0.2.0.md",
    "content": "## v0.2.0 Changelog\n\nNow you can open your saved queries using `CTRL+E CTRL+O`!\n\n### Improvements\n* Added opening support for saved queries (Issue #12)\n```javascript\n// new hotkeys setting\n{\n    \"keys\": [\"ctrl+e\", \"ctrl+o\"], \n    \"command\": \"st_list_queries\", \n    \"args\": {\n        \"mode\" : \"open\"\n    }\n}\n```\n\n### Fixes\n\nNo fixes for this version\n"
  },
  {
    "path": "messages/v0.3.0.md",
    "content": "## v0.3.0 Changelog\n\n### Features\n\n* Describe user functions `CTRL+E CTRL+F` for PostgreSQL!\n* PostgreSQL user functions added to auto complete.\n\n\n### Improvements\n\n* Window result shown always in the same tab\n"
  },
  {
    "path": "messages/v0.8.2.md",
    "content": "## v0.8.2 Notes\n\n### Features\n\n* New smarter completions that will suggest tables, columns,\n  aliases, columns for table aliases and join conditions.\n  Demo of new functionality:\n  https://github.com/mtxr/SQLTools/issues/67#issuecomment-297849135\n  \n  **NOTE**: It is highly recommended that you review your SQLTools\n  settings file (Users/SQLTools.sublime-settings) and leave only\n  those settings that you altered specifically to your needs and\n  remove all other settings. This way the updated queries listed\n  in default settings file would be used, for new smarter\n  completions to work correctly.\n\n\n### Improvements\n\n* Plain Text syntax is used in the output panel when executing\n  queries (for performance reasons and to prevent weird highlighting)\n"
  },
  {
    "path": "messages/v0.9.0.md",
    "content": "## v0.9.0 Notes\n\n### Features\n\n* Added support for query result streaming [#19](https://github.com/mtxr/SQLTools/issues/19)\n"
  },
  {
    "path": "messages/v0.9.1.md",
    "content": "## v0.9.1 Notes\n\n### Improvements\n\n* Display errors inline instead of appending them at the bottom [#92](https://github.com/mtxr/SQLTools/issues/92)\n\n\n### Fixes\n\n* Thread timeout is always triggered when streaming results output (MacOS) [#90](https://github.com/mtxr/SQLTools/issues/90)\n* stderr output is ignored when streaming results output [#91](https://github.com/mtxr/SQLTools/issues/91)\n"
  },
  {
    "path": "messages/v0.9.10.md",
    "content": "## v0.9.10 Notes\n\n### Fixes\n\n* Added `focus_result` setting closing issue [#183]\n"
  },
  {
    "path": "messages/v0.9.11.md",
    "content": "## v0.9.11 Notes\n\n### Fixes\n\n* New command `ST: Format SQL All File` (internal name `st_format_all`) to format the entire file [#182]\n"
  },
  {
    "path": "messages/v0.9.12.md",
    "content": "## v0.9.12 Notes\n\n### Improvements\n\n* Snowflake (`snowsql`) support\n* Added support for prompting of the connection parameters\n* Table/view/function selection quick panel is pre-populated with the text of the current selection\n* New command `ST: Refresh Connection Data` (internal name `st_refresh_connection_data`) to reload the list of database objects\n* Improve performance (completions and connection listing)\n* Add a configurable setting to enable/disable completion for certain selectors (`autocomplete_selectors_ignore`, `autocomplete_selectors_active`)\n\n\n### Fixes\n\n* Fix PostgreSQL v11 compatibility issue (functions were not listed)\n* Do not create an empty settings file [#144]\n* Bump timeout to 60 seconds for internal commands\n* Use python core logging for logs\n"
  },
  {
    "path": "messages/v0.9.2.md",
    "content": "## v0.9.2 Notes\n\n### Improvements\n\n* Support PostgreSQL \"password\" setting in Connections file [#106](https://github.com/mtxr/SQLTools/issues/106)\n* Improved performance of smart completions\n* If configured, use stream output for saved and history queries\n* [MySQL] Add support for `Describe Function`\n\n\n### Fixes\n\n* Fix Query History [#96](https://github.com/mtxr/SQLTools/issues/96)\n* Fix functionality of \"clear_output\" for pannel output [#102](https://github.com/mtxr/SQLTools/issues/102)\n"
  },
  {
    "path": "messages/v0.9.3.md",
    "content": "## v0.9.3 Notes\n\n### Improvements\n\n* [Oracle] Get identifiers (tables, columns)  in all schemas [#112](https://github.com/mtxr/SQLTools/issues/112)\n\n\nPlease restart Sublime Text after installing this update.\n"
  },
  {
    "path": "messages/v0.9.4.md",
    "content": "## v0.9.4 Notes\n\n### Improvements\n\n* Execute All File [#114]\n  https://github.com/mtxr/SQLTools/issues/114\n* Configurable top/bottom `show_query` placement\n  https://github.com/mtxr/SQLTools/pull/116\n* [Oracle] In addition to tables views are listed as well (Describe Table works with views) [#115]\n  https://github.com/mtxr/SQLTools/pull/115\n"
  },
  {
    "path": "messages/v0.9.5.md",
    "content": "## v0.9.5 Notes\n\n### Improvements\n\n* New Feature: List and Insert Saved Queries (ctrl+e ctrl+i) [#126]\n* Better error messages if setting json file could not be parsed\n\n### Fixes\n\n* Display completions for upper case aliases [#142]\n* Fix the display of status bar message when query is executed [#130]\n* Open Saved Queries executed the query if not connected to a database prior [#125]\n"
  },
  {
    "path": "messages/v0.9.6.md",
    "content": "## v0.9.6 Notes\n\n### Fixes\n\n* [MySQL] Added basic backtick escaping of identifiers [#147]\n"
  },
  {
    "path": "messages/v0.9.7.md",
    "content": "## v0.9.7 Notes\n\n### Fixes\n\n* Completions not working with identifiers containing $ symbol [#152]\n"
  },
  {
    "path": "messages/v0.9.8.md",
    "content": "## v0.9.8 Notes\n\n### Improvements\n\n* Add MSSQL support via native `sqlcmd` CLI\n* Add more options for expanding the empty selection. Instead of config option `expand_to_paragraph`, introduce new option called `expand_to`, which can be configured to expand empty selection to: `line`, `paragraph` or `file`\n* General review/improvement of each DB config\n* Use the `encoding` option supplied in connection settings when writing to standard input and reading from standard output of CLI command\n* Changes how top level and per-query `options` apply to CLI invocations\n* Changes how `before` and `after` applied (top level and per-query)\n* Introduction of new `execute` named query section which is used when executing statements with `ST: Execute` and friends\n* Now all named query formatting is done via `str.format()`, therefore all instances of `%s` in template strings got replaced with `{0}`, with back-patch support (i.e. `%s` should still work for those users who have it on their own user config)\n* Improve the way the output is shown - the output panel is not shown until the first output from DB CLI arrives\n* Add sample connections for `Vertica` and `Firebird`\n* [PostgreSQL] Connection options `host`, `port`, `username` are now optional (can be set via environment vars and other means)\n* [MySQL] Add configurable connection option `default-character-set`\n* [MySQL] Add `--no-auto-rehash` and `--compress` to improve MySQL startup time and improve latency on slow networks\n* [MySQL] Connection options `host`, `port`, `username` are now optional (can be set via `--defaults-extra-file` and `--login-path`)\n* [MySQL] Supply password via environment variable `MYSQL_PWD` to avoid security warning\n* [Oracle] Add ability to configure `NSL_LANG` to match the server encoding\n* [Oracle] Add support for quoted table and column names\n* [Oracle] Add support for functions & procedures completions as well as getting and functions & procedures definitions (both top level and those in packages)\n* [Vertica] Add support for quoted identifiers\n* Other minor improvements\n\n### Fixes\n\n* Remove unused settings option `unescape_quotes` from config\n"
  },
  {
    "path": "messages/v0.9.9.md",
    "content": "## v0.9.9 Notes\n\n### Improvements\n\n* Use `utf-8` encoding if Connection `encoding` is not a valid python encoding\n\n\n### Fixes\n\n* Exception when Connection `encoding` is set to null [#177]\n"
  },
  {
    "path": "messages.json",
    "content": "{\n    \"install\": \"messages/install.md\",\n    \"0.1.6\": \"messages/v0.1.6.md\",\n    \"0.2.0\": \"messages/v0.2.0.md\",\n    \"0.3.0\": \"messages/v0.3.0.md\",\n    \"0.3.1\": \"messages/v0.3.0.md\",\n    \"0.8.2\": \"messages/v0.8.2.md\",\n    \"0.9.0\": \"messages/v0.9.0.md\",\n    \"0.9.1\": \"messages/v0.9.1.md\",\n    \"0.9.2\": \"messages/v0.9.2.md\",\n    \"0.9.3\": \"messages/v0.9.3.md\",\n    \"0.9.4\": \"messages/v0.9.4.md\",\n    \"0.9.5\": \"messages/v0.9.5.md\",\n    \"0.9.6\": \"messages/v0.9.6.md\",\n    \"0.9.7\": \"messages/v0.9.7.md\",\n    \"0.9.8\": \"messages/v0.9.8.md\",\n    \"0.9.9\": \"messages/v0.9.9.md\",\n    \"0.9.10\": \"messages/v0.9.10.md\",\n    \"0.9.11\": \"messages/v0.9.11.md\",\n    \"0.9.12\": \"messages/v0.9.12.md\"\n}\n"
  }
]