diff --git a/COPYRIGHT b/COPYRIGHT
deleted file mode 100644
index c320eccac08f7..0000000000000
--- a/COPYRIGHT
+++ /dev/null
@@ -1,23 +0,0 @@
-PostgreSQL Database Management System
-(formerly known as Postgres, then as Postgres95)
-
-Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
-
-Portions Copyright (c) 1994, The Regents of the University of California
-
-Permission to use, copy, modify, and distribute this software and its
-documentation for any purpose, without fee, and without a written agreement
-is hereby granted, provided that the above copyright notice and this
-paragraph and the following two paragraphs appear in all copies.
-
-IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
-DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
-LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
-DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGE.
-
-THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
-INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
-AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
-ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO
-PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100644
index 0000000000000..9cecc1d4669ee
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ {one line to give the program's name and a brief idea of what it does.}
+ Copyright (C) {year} {name of author}
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ {project} Copyright (C) {year} {fullname}
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/README b/README
index 12de3f1d73cc9..e12b7c3a27ed5 100644
--- a/README
+++ b/README
@@ -1,27 +1,33 @@
-PostgreSQL Database Management System
-=====================================
+**NOTE**: This branch is maintained as a personal effort and is not
+sponsored / supported by my Employer or any other third-party. This
+is not officially supported / endorsed by any Commercial interest in
+any way.
+
+PsqlForks
+=========
This directory contains the source code distribution of the PostgreSQL
-database management system.
+database management system, along with modifications required for
+PsqlForks.
-PostgreSQL is an advanced object-relational database management system
-that supports an extended subset of the SQL standard, including
-transactions, foreign keys, subqueries, triggers, user-defined types
-and functions. This distribution also contains C language bindings.
+PsqlForks ( http://psqlforks.com ) is a psql variant that tries to
+accommodate as many PostgrSQL variants (or software that speak the
+PostgreSQL protocol to an extent).
-PostgreSQL has many language interfaces, many of which are listed here:
+The current status of support for different PostgreSQL derived databases
+can be seen here:
- https://www.postgresql.org/download
+https://github.com/robins/postgres/blob/forks/src/bin/psql/README.md
See the file INSTALL for instructions on how to build and install
PostgreSQL. That file also lists supported operating systems and
hardware platforms and contains information regarding any other
software packages that are required to build or run the PostgreSQL
system. Copyright and license information can be found in the
-file COPYRIGHT. A comprehensive documentation set is included in this
+file LICENSE.txt. A comprehensive documentation set is included in this
distribution; it can be read as described in the installation
instructions.
The latest version of this software may be obtained at
-https://www.postgresql.org/download/. For more information look at our
-web site located at https://www.postgresql.org/.
+https://github.com/robins/postgres/tree/forks . For more information look
+at the web site located at http://www.thatguyfromdelhi.com/search/label/psql .
diff --git a/README.git b/README.git
index 52cb7223dfb12..9fe75023653be 100644
--- a/README.git
+++ b/README.git
@@ -1,3 +1,5 @@
+NOTE: This branch is maintained as a personal effort and is not sponsored / supported by my Employer or any other third-party. This is not officially supported / endorsed by Amazon in any way.
+
(This file does not appear in release tarballs.)
In a release or snapshot tarball of PostgreSQL, a documentation file named
diff --git a/doc/src/sgml/ref/pg_dump.sgml b/doc/src/sgml/ref/pg_dump.sgml
index 7ccbee4855c05..ce49bf2507f12 100644
--- a/doc/src/sgml/ref/pg_dump.sgml
+++ b/doc/src/sgml/ref/pg_dump.sgml
@@ -791,6 +791,15 @@ PostgreSQL documentation
+
+
+
+
+ Do not dump comments.
+
+
+
+
diff --git a/doc/src/sgml/ref/pg_dumpall.sgml b/doc/src/sgml/ref/pg_dumpall.sgml
index 1dba702ad95b2..f9de4b24e73dd 100644
--- a/doc/src/sgml/ref/pg_dumpall.sgml
+++ b/doc/src/sgml/ref/pg_dumpall.sgml
@@ -345,6 +345,15 @@ PostgreSQL documentation
+
+
+
+
+ Do not dump comments.
+
+
+
+
diff --git a/src/bin/pg_dump/pg_backup.h b/src/bin/pg_dump/pg_backup.h
index ce3100f09d65a..9f08be68dbf5f 100644
--- a/src/bin/pg_dump/pg_backup.h
+++ b/src/bin/pg_dump/pg_backup.h
@@ -146,6 +146,7 @@ typedef struct _dumpOptions
int dump_inserts;
int column_inserts;
int if_exists;
+ int no_comments;
int no_security_labels;
int no_publications;
int no_subscriptions;
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index e34c83acd2a6c..a247c94566551 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -355,6 +355,7 @@ main(int argc, char **argv)
{"snapshot", required_argument, NULL, 6},
{"strict-names", no_argument, &strict_names, 1},
{"use-set-session-authorization", no_argument, &dopt.use_setsessauth, 1},
+ {"no-comments", no_argument, &dopt.no_comments, 1},
{"no-publications", no_argument, &dopt.no_publications, 1},
{"no-security-labels", no_argument, &dopt.no_security_labels, 1},
{"no-synchronized-snapshots", no_argument, &dopt.no_synchronized_snapshots, 1},
@@ -956,6 +957,7 @@ help(const char *progname)
printf(_(" --exclude-table-data=TABLE do NOT dump data for the named table(s)\n"));
printf(_(" --if-exists use IF EXISTS when dropping objects\n"));
printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
+ printf(_(" --no-comments do not dump comments\n"));
printf(_(" --no-publications do not dump publications\n"));
printf(_(" --no-security-labels do not dump security label assignments\n"));
printf(_(" --no-subscriptions do not dump subscriptions\n"));
@@ -2785,8 +2787,9 @@ dumpDatabase(Archive *fout)
destroyPQExpBuffer(loOutQry);
}
- /* Dump DB comment if any */
- if (fout->remoteVersion >= 80200)
+
+ /* Dump DB comment if any, and if --no-comments is not supplied */
+ if (fout->remoteVersion >= 80200 && !dopt->no_comments)
{
/*
* 8.2 keeps comments on shared objects in a shared table, so we
@@ -9178,6 +9181,10 @@ dumpComment(Archive *fout, const char *target,
return;
}
+ /* do nothing, if --no-comments is supplied */
+ if (dopt->no_comments)
+ return;
+
/* Search for comments associated with catalogId, using table */
ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
&comments);
@@ -9236,6 +9243,10 @@ dumpTableComment(Archive *fout, TableInfo *tbinfo,
if (dopt->dataOnly)
return;
+ /* do nothing, if --no-comments is supplied */
+ if (dopt->no_comments)
+ return;
+
/* Search for comments associated with relation, using table */
ncomments = findComments(fout,
tbinfo->dobj.catId.tableoid,
@@ -10892,6 +10903,10 @@ dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
int i_attname;
int i_attnum;
+ /* do nothing, if --no-comments is supplied */
+ if (fout->dopt->no_comments)
+ return;
+
query = createPQExpBuffer();
appendPQExpBuffer(query,
diff --git a/src/bin/pg_dump/pg_dumpall.c b/src/bin/pg_dump/pg_dumpall.c
index 41c5ff89b7587..9ac43295ea7e6 100644
--- a/src/bin/pg_dump/pg_dumpall.c
+++ b/src/bin/pg_dump/pg_dumpall.c
@@ -74,6 +74,7 @@ static int if_exists = 0;
static int inserts = 0;
static int no_tablespaces = 0;
static int use_setsessauth = 0;
+static int no_comments = 0;
static int no_publications = 0;
static int no_security_labels = 0;
static int no_subscriptions = 0;
@@ -133,6 +134,7 @@ main(int argc, char *argv[])
{"load-via-partition-root", no_argument, &load_via_partition_root, 1},
{"role", required_argument, NULL, 3},
{"use-set-session-authorization", no_argument, &use_setsessauth, 1},
+ {"no-comments", no_argument, &no_comments, 1},
{"no-publications", no_argument, &no_publications, 1},
{"no-role-passwords", no_argument, &no_role_passwords, 1},
{"no-security-labels", no_argument, &no_security_labels, 1},
@@ -399,6 +401,8 @@ main(int argc, char *argv[])
appendPQExpBufferStr(pgdumpopts, " --load-via-partition-root");
if (use_setsessauth)
appendPQExpBufferStr(pgdumpopts, " --use-set-session-authorization");
+ if (no_comments)
+ appendPQExpBufferStr(pgdumpopts, " --no-comments");
if (no_publications)
appendPQExpBufferStr(pgdumpopts, " --no-publications");
if (no_security_labels)
@@ -624,6 +628,7 @@ help(void)
printf(_(" --disable-triggers disable triggers during data-only restore\n"));
printf(_(" --if-exists use IF EXISTS when dropping objects\n"));
printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
+ printf(_(" --no-comments do not dump comments\n"));
printf(_(" --no-publications do not dump publications\n"));
printf(_(" --no-role-passwords do not dump passwords for roles\n"));
printf(_(" --no-security-labels do not dump security label assignments\n"));
@@ -932,7 +937,7 @@ dumpRoles(PGconn *conn)
appendPQExpBufferStr(buf, ";\n");
- if (!PQgetisnull(res, i, i_rolcomment))
+ if (!no_comments && !PQgetisnull(res, i, i_rolcomment))
{
appendPQExpBuffer(buf, "COMMENT ON ROLE %s IS ", fmtId(rolename));
appendStringLiteralConn(buf, PQgetvalue(res, i, i_rolcomment), conn);
@@ -1238,7 +1243,7 @@ dumpTablespaces(PGconn *conn)
exit_nicely(1);
}
- if (spccomment && strlen(spccomment))
+ if (!no_comments && spccomment && strlen(spccomment))
{
appendPQExpBuffer(buf, "COMMENT ON TABLESPACE %s IS ", fspcname);
appendStringLiteralConn(buf, spccomment, conn);
diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl
index c492fbdc24d62..fca0baefb8714 100644
--- a/src/bin/pg_dump/t/002_pg_dump.pl
+++ b/src/bin/pg_dump/t/002_pg_dump.pl
@@ -183,11 +183,21 @@
dump_cmd => [
'pg_dumpall', '--no-sync',
"--file=$tempdir/pg_dumpall_dbprivs.sql", ], },
+ pg_dumpall_no_comments => {
+ dump_cmd => [
+ 'pg_dumpall', '--no-sync',
+ "--file=$tempdir/pg_dumpall_no_comments.sql",
+ '--no-comments', ], },
no_blobs => {
dump_cmd => [
'pg_dump', '--no-sync',
"--file=$tempdir/no_blobs.sql", '-B',
'postgres', ], },
+ no_comments => {
+ dump_cmd => [
+ 'pg_dump', '--no-sync',
+ "--file=$tempdir/no_comments.sql",
+ '--no-comments', 'postgres', ], },
no_privs => {
dump_cmd => [
'pg_dump', '--no-sync',
@@ -321,9 +331,11 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_post_data => 1,
test_schema_plus_blobs => 1,
@@ -361,8 +373,10 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_owner => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_post_data => 1,
with_oids => 1, },
@@ -404,8 +418,10 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_owner => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_post_data => 1,
with_oids => 1, },
@@ -432,7 +448,8 @@
like => {
pg_dumpall_dbprivs => 1,
pg_dumpall_globals => 1,
- pg_dumpall_globals_clean => 1, },
+ pg_dumpall_globals_clean => 1,
+ pg_dumpall_no_comments => 1, },
unlike => {
binary_upgrade => 1,
clean => 1,
@@ -445,6 +462,7 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
@@ -623,9 +641,11 @@
exclude_test_table_data => 1,
no_blobs => 1,
no_owner => 1,
+ no_comments => 1,
no_privs => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -681,9 +701,11 @@
exclude_dump_test_schema => 1,
exclude_test_table => 1,
exclude_test_table_data => 1,
+ no_comments => 1,
no_privs => 1,
no_blobs => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_post_data => 1,
with_oids => 1, },
@@ -714,8 +736,10 @@
exclude_dump_test_schema => 1,
exclude_test_table => 1,
exclude_test_table_data => 1,
+ no_comments => 1,
no_privs => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
with_oids => 1, },
@@ -819,11 +843,13 @@
defaults => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
only_dump_test_table => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -854,9 +880,11 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
role => 1,
schema_only => 1,
section_pre_data => 1,
@@ -1057,6 +1085,7 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
pg_dumpall_dbprivs => 1,
@@ -1068,6 +1097,7 @@
only_dump_test_table => 1,
pg_dumpall_globals => 1,
pg_dumpall_globals_clean => 1,
+ pg_dumpall_no_comments => 1,
section_post_data => 1,
test_schema_plus_blobs => 1,
column_inserts => 1,
@@ -1125,10 +1155,12 @@
defaults => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
only_dump_test_schema => 1,
only_dump_test_table => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -1421,7 +1453,9 @@
all_runs => 0, # catch-all
regexp =>
qr/^ALTER (?!EVENT TRIGGER|LARGE OBJECT|PUBLICATION|SUBSCRIPTION)(.*) OWNER TO .*;/m,
- like => {}, # use more-specific options above
+ like => { # use more-specific options above
+ no_comments => 1,
+ pg_dumpall_no_comments => 1, },
unlike => {
column_inserts => 1,
data_only => 1,
@@ -1435,7 +1469,9 @@
'ALTER TABLE ... commands' => {
all_runs => 0, # catch-all
regexp => qr/^ALTER TABLE .* (?!OWNER TO)(.*);/m,
- like => {}, # use more-specific options above
+ like => { # use more-specific options above
+ no_comments => 1,
+ pg_dumpall_no_comments => 1, },
unlike => {
column_inserts => 1,
pg_dumpall_globals => 1,
@@ -1459,9 +1495,11 @@
exclude_dump_test_schema => 1,
exclude_test_table => 1,
exclude_test_table_data => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
with_oids => 1, },
@@ -1495,8 +1533,10 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_owner => 1,
+ no_comments => 1,
no_privs => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
section_data => 1,
test_schema_plus_blobs => 1,
with_oids => 1, },
@@ -1837,10 +1877,12 @@
with_oids => 1, },
unlike => {
no_blobs => 1,
+ no_comments => 1,
only_dump_test_schema => 1,
only_dump_test_table => 1,
pg_dumpall_globals => 1,
pg_dumpall_globals_clean => 1,
+ pg_dumpall_no_comments => 1,
role => 1,
schema_only => 1,
section_data => 1,
@@ -1872,10 +1914,12 @@
unlike => {
column_inserts => 1,
data_only => 1,
+ no_comments => 1,
only_dump_test_table => 1,
only_dump_test_schema => 1,
pg_dumpall_globals => 1,
pg_dumpall_globals_clean => 1,
+ pg_dumpall_no_comments => 1,
role => 1,
section_data => 1,
section_pre_data => 1,
@@ -1907,10 +1951,12 @@
unlike => {
column_inserts => 1,
data_only => 1,
+ no_comments => 1,
only_dump_test_table => 1,
only_dump_test_schema => 1,
pg_dumpall_globals => 1,
pg_dumpall_globals_clean => 1,
+ pg_dumpall_no_comments => 1,
role => 1,
section_data => 1,
section_pre_data => 1,
@@ -2185,8 +2231,10 @@
regexp => qr/^COMMENT ON /m,
like => {}, # use more-specific options above
unlike => {
+ no_comments => 1,
pg_dumpall_globals => 1,
pg_dumpall_globals_clean => 1,
+ pg_dumpall_no_comments => 1,
section_data => 1, }, },
'COPY test_table' => {
@@ -2453,7 +2501,9 @@
'COPY ... commands' => { # catch-all for COPY
all_runs => 0, # catch-all
regexp => qr/^COPY /m,
- like => {}, # use more-specific options above
+ like => { # use more-specific options above
+ no_comments => 1,
+ pg_dumpall_no_comments => 1, },
unlike => {
binary_upgrade => 1,
column_inserts => 1,
@@ -2529,11 +2579,13 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
pg_dumpall_dbprivs => 1,
pg_dumpall_globals => 1,
pg_dumpall_globals_clean => 1,
+ pg_dumpall_no_comments => 1,
section_data => 1,
only_dump_test_schema => 1,
only_dump_test_table => 1,
@@ -2553,7 +2605,8 @@
like => {
pg_dumpall_dbprivs => 1,
pg_dumpall_globals => 1,
- pg_dumpall_globals_clean => 1, },
+ pg_dumpall_globals_clean => 1,
+ pg_dumpall_no_comments => 1, },
unlike => {
binary_upgrade => 1,
clean => 1,
@@ -2566,6 +2619,7 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
@@ -2694,6 +2748,7 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
@@ -2701,6 +2756,7 @@
pg_dumpall_dbprivs => 1,
pg_dumpall_globals => 1,
pg_dumpall_globals_clean => 1,
+ pg_dumpall_no_comments => 1,
role => 1,
schema_only => 1,
section_pre_data => 1,
@@ -2716,7 +2772,9 @@
regexp => qr/^
\QCREATE DATABASE dump_test WITH TEMPLATE = template0 \E
.*;/xm,
- like => { pg_dumpall_dbprivs => 1, },
+ like => {
+ pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1, },
unlike => {
binary_upgrade => 1,
clean => 1,
@@ -2729,6 +2787,7 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
@@ -2757,9 +2816,11 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
with_oids => 1, },
@@ -2802,10 +2863,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -2837,10 +2900,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -2880,10 +2945,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -2921,10 +2988,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -2961,10 +3030,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3001,10 +3072,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3037,10 +3110,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3089,10 +3164,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3129,9 +3206,11 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_post_data => 1,
with_oids => 1, },
@@ -3167,11 +3246,13 @@
defaults => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
only_dump_test_table => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_post_data => 1,
test_schema_plus_blobs => 1,
@@ -3206,10 +3287,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3248,10 +3331,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3284,10 +3369,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3317,10 +3404,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3353,10 +3442,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3442,10 +3533,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3478,10 +3571,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3518,10 +3613,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3555,10 +3652,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3594,10 +3693,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3633,10 +3734,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3681,10 +3784,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3722,10 +3827,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3755,10 +3862,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3789,9 +3898,11 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
with_oids => 1, },
@@ -3822,9 +3933,11 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
with_oids => 1, },
@@ -3864,10 +3977,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
test_schema_plus_blobs => 1,
@@ -3900,9 +4015,11 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
with_oids => 1, },
@@ -3935,9 +4052,11 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_pre_data => 1,
with_oids => 1, },
@@ -4470,9 +4589,11 @@
defaults => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_post_data => 1,
with_oids => 1, },
@@ -4504,9 +4625,11 @@
defaults => 1,
exclude_test_table => 1,
exclude_test_table_data => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
schema_only => 1,
section_post_data => 1, },
unlike => {
@@ -5236,7 +5359,9 @@
'CREATE ... commands' => { # catch-all for CREATE
all_runs => 0, # catch-all
regexp => qr/^CREATE /m,
- like => {}, # use more-specific options above
+ like => { # use more-specific options above
+ no_comments => 1,
+ pg_dumpall_no_comments => 1, },
unlike => {
column_inserts => 1,
data_only => 1,
@@ -5465,12 +5590,14 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
only_dump_test_table => 1,
pg_dumpall_dbprivs => 1,
pg_dumpall_globals => 1,
+ pg_dumpall_no_comments => 1,
role => 1,
schema_only => 1,
section_data => 1,
@@ -6137,6 +6264,7 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_owner => 1,
pg_dumpall_dbprivs => 1,
schema_only => 1,
@@ -6144,6 +6272,7 @@
only_dump_test_schema => 1,
only_dump_test_table => 1,
pg_dumpall_globals_clean => 1,
+ pg_dumpall_no_comments => 1,
role => 1,
section_data => 1,
section_post_data => 1,
@@ -6152,7 +6281,9 @@
'GRANT commands' => { # catch-all for GRANT commands
all_runs => 0, # catch-all
regexp => qr/^GRANT /m,
- like => {}, # use more-specific options above
+ like => { # use more-specific options above
+ no_comments => 1,
+ pg_dumpall_no_comments => 1, },
unlike => {
no_privs => 1,
pg_dumpall_globals_clean => 1,
@@ -6170,10 +6301,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
test_schema_plus_blobs => 1,
section_post_data => 1,
with_oids => 1, },
@@ -6205,10 +6338,12 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
pg_dumpall_dbprivs => 1,
+ pg_dumpall_no_comments => 1,
test_schema_plus_blobs => 1,
section_post_data => 1,
with_oids => 1, },
@@ -6243,6 +6378,7 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
@@ -6250,6 +6386,7 @@
pg_dumpall_dbprivs => 1,
pg_dumpall_globals => 1,
pg_dumpall_globals_clean => 1,
+ pg_dumpall_no_comments => 1,
role => 1,
schema_only => 1,
section_data => 1,
@@ -6276,6 +6413,7 @@
exclude_test_table => 1,
exclude_test_table_data => 1,
no_blobs => 1,
+ no_comments => 1,
no_privs => 1,
no_owner => 1,
only_dump_test_schema => 1,
@@ -6283,6 +6421,7 @@
pg_dumpall_dbprivs => 1,
pg_dumpall_globals => 1,
pg_dumpall_globals_clean => 1,
+ pg_dumpall_no_comments => 1,
role => 1,
schema_only => 1,
section_data => 1,
@@ -6454,7 +6593,9 @@
'REVOKE commands' => { # catch-all for REVOKE commands
all_runs => 0, # catch-all
regexp => qr/^REVOKE /m,
- like => {}, # use more-specific options above
+ like => { # use more-specific options above
+ no_comments => 1,
+ pg_dumpall_no_comments => 1, },
unlike => {
column_inserts => 1,
data_only => 1,
diff --git a/src/bin/psql/Makefile b/src/bin/psql/Makefile
index cabfe15f97f75..5849f03f12aad 100644
--- a/src/bin/psql/Makefile
+++ b/src/bin/psql/Makefile
@@ -22,9 +22,10 @@ override CPPFLAGS := -I. -I$(srcdir) -I$(libpq_srcdir) $(CPPFLAGS)
override LDFLAGS := -L$(top_builddir)/src/fe_utils -lpgfeutils $(libpq_pgport) $(LDFLAGS)
OBJS= command.o common.o conditional.o copy.o crosstabview.o \
- describe.o help.o input.o large_obj.o mainloop.o \
+ describe.o help.o input.o jsmn.o large_obj.o mainloop.o \
prompt.o psqlscanslash.o sql_help.o startup.o stringutils.o \
- tab-complete.o variables.o \
+ tab-complete.o tab-complete-cockroachdb.o tab-complete-pipelinedb.o \
+ tab-complete-redshift.o variables.o \
$(WIN32RES)
diff --git a/src/bin/psql/README.md b/src/bin/psql/README.md
new file mode 100644
index 0000000000000..c53a127c025f5
--- /dev/null
+++ b/src/bin/psql/README.md
@@ -0,0 +1,10 @@
+This documents the current state of PsqlFork's support for various server side software that speaks (to an extent) Postgres.
+
+**NOTE**: This branch is maintained as a personal effort and is not sponsored / supported by my Employer or any other third-party. This is not officially supported / endorsed by any Commercial interest in any way.
+
+Postgres Forks | Support Level | Description
+:-------------:| :-----------: | :----------
+Amazon Redshift | [Status](https://github.com/robins/postgres/blob/forks/src/bin/psql/README_redshift.md) | Amazon Redshift was spin off of PostgreSQL (version 8.0.2)
+CockroachDB | [Status](https://github.com/robins/postgres/blob/forks/src/bin/psql/README_cockroachdb.md) | Compatible with PostgreSQL (version 9.5.0)
+PipelineDB | [Status](https://github.com/robins/postgres/blob/forks/src/bin/psql/README_pipelinedb.md) | Compatible with PostgreSQL (version 9.5)
+PgBouncer | Supported | \* (Backslash) is not supported, and gives appropriate error message
\ No newline at end of file
diff --git a/src/bin/psql/README_cockroachdb.md b/src/bin/psql/README_cockroachdb.md
new file mode 100644
index 0000000000000..adc4e1f20b2b5
--- /dev/null
+++ b/src/bin/psql/README_cockroachdb.md
@@ -0,0 +1,152 @@
+**Note**: Tab Completion requires quote_ident() that is NOT yet supported by the CockroachDB engine. There is a pending request towards this ( https://github.com/cockroachdb/cockroach/issues/15006 ) however, without this tab-completion is not going to work in its current state.
+
+We could remove quote_ident() requirement from psql, but this would be a pretty big security issue, considering that this is effectively SQL injection in the making.
+
+So by design, tab-completion is going to silently fail (no errors), and intentionally so, until CockroachDB starts support quote_ident(). This issue is logged in #21 and would be addressed if the Dependency is resolved.
+
+=============================================
+
+This document shows the current state of psql's auto-complete support for CockroachDB.
+
+Reference: https://www.cockroachlabs.com/docs/stable/sql-statements.html
+
+See Support level of all Postgres forks: [Here](https://github.com/robins/postgres/blob/forks/src/bin/psql/README.md)
+
+
+psql Commands | Supported State | Description
+:------------ |:--------------:|:------------
+\a | Native
+\C | Native
+\cd | Untested
+\conninfo | Native
+\copy | Untested
+\copyright | Native
+\crosstabview | Untested
+\dS[+] | **Yes**
+\da[S] | Untested
+\dA[+] | Dependency Unsupported|The server (version 9.5) does not support access methods.
+\db[+] | Untested
+\dc[S+] | Untested
+\dC[+] | Untested
+\dd[S] | Untested
+\dD[S+] | Untested
+\ddp | Untested
+\dE[S+] | Untested
+\di[S+] | **Yes**
+\dm[S+] | Untested
+\ds[S+] | Untested
+\dt[S+] | **Yes**
+\dv[S+] | **Yes**
+\des[+] | Untested
+\det[+] | Untested
+\deu[+] | Untested
+\dew[+] | Untested
+\df[antwS+] | **Yes**
+\dF[+] | Dependency Unsupported
+\dFd[+] | Untested
+\dFp[+] | Untested
+\dFt[+] | Untested
+\dg[S+] | **Yes**
+\dl | Dependency Unsupported | pg_largeobject_metadata not supported in Engine
+\dL[S+] | Untested
+\dn[S+] | **Yes**
+\do[S+] | Untested
+\dO[S+] | Untested
+\dp | Untested
+\drds | Untested
+\dRp[+] | Untested
+\dRs[+] | Untested
+\dT[S+] | Untested
+\du[S+] | Partial
+\dx[+] | Dependency Unsupported | Issue cockroachdb/cockroach#13436 didn't add supported for OID column
+\dy[+] | Dependency Unsupported | Functions not supported in Engine
+\e | Native
+\echo | Native
+\ef | Dependency Unsupported | Functions not supported in Engine
+\encoding | Untested
+\errverbose | Untested
+\ev | Dependency Unsupported | Issue #24 is logged towards this
+\f | Native
+\g | Untested
+\gdesc | Untested
+\gexec | Untested
+\gset | Untested
+\gx | Untested
+\h | Native
+\H | Native
+\i | Untested
+\if | Untested
+\elif | Untested
+\else | Untested
+\endif | Untested
+\ir | Untested
+\l[+] | **Yes**
+\lo_export | Untested
+\lo_import | Untested
+\lo_list | Untested
+\lo_unlink | Untested
+\o | Native
+\p | Untested
+\password | Untested
+\prompt | Untested
+\pset | Untested
+\q | Native
+\qecho | Native
+\r | Untested
+\s | Untested
+\set | Untested
+\setenv | Untested
+\sf[+] | Dependency Unsupported
+\sv[+] | Dependency Unsupported | Issue #24 is logged towards this
+\t | Native
+\T | Native
+\timing | Untested
+\unset | Untested
+\w | Untested
+\watch | Native
+\x | Native
+\z | Untested
+\! | Untested
+\? | Untested
+\; | Native
+
+
+SQL Commands | Supported State
+:----------- |:--------------:
+ADD COLUMN | Dependency Unsupported
+ADD CONSTRAINT | Dependency Unsupported
+ALTER COLUMN | Dependency Unsupported
+ALTER TABLE | Dependency Unsupported
+ALTER VIEW | Dependency Unsupported
+CREATE DATABASE | Dependency Unsupported
+CREATE INDEX | Dependency Unsupported
+CREATE TABLE | Dependency Unsupported
+CREATE TABLE AS | Dependency Unsupported
+CREATE VIEW | Dependency Unsupported
+DROP COLUMN | Dependency Unsupported
+DROP CONSTRAINT | Dependency Unsupported
+DROP DATABASE | Dependency Unsupported
+DROP INDEX | Dependency Unsupported
+DROP TABLE | Dependency Unsupported
+DROP VIEW | Dependency Unsupported
+RENAME COLUMN | Dependency Unsupported
+RENAME DATABASE | Dependency Unsupported
+RENAME INDEX | Dependency Unsupported
+RENAME TABLE | Dependency Unsupported
+SHOW COLUMNS | Dependency Unsupported
+SHOW CONSTRAINTS | Dependency Unsupported
+SHOW CREATE TABLE | Dependency Unsupported
+SHOW CREATE VIEW | Dependency Unsupported
+SHOW DATABASES | Dependency Unsupported
+SHOW INDEX | Dependency Unsupported
+SHOW TABLES | Dependency Unsupported
+
+
+Support Legend | Description
+:-------------:| -----------
+Native | All combinations supported by Native psql
+Unsupported | Not (yet) supported by PsqlForks
+Dependency Unsupported | Engine does not support a dependency
+Partial | Only some combinations supported
+**Yes** | Supported by (only) this branch (not Native)
+Complete | All combinations supported
\ No newline at end of file
diff --git a/src/bin/psql/README_pipelinedb.md b/src/bin/psql/README_pipelinedb.md
new file mode 100644
index 0000000000000..2f494649f06bb
--- /dev/null
+++ b/src/bin/psql/README_pipelinedb.md
@@ -0,0 +1,23 @@
+This document shows the current state of psql's auto-complete support for PipelineDB.
+
+Reference: http://docs.pipelinedb.com/
+
+See Support level of all Postgres forks: [Here](https://github.com/robins/postgres/blob/forks/src/bin/psql/README.md)
+
+SQL Commands | Supported State
+:----------- |:--------------:
+ALTER STREAM | Partial
+CREATE CONTINUOUS TRANSFORM | Partial
+CREATE CONTINUOUS VIEW | Partial
+CREATE STREAM | Partial
+DROP CONTINUOUS TRANSFORM | Partial
+DROP CONTINUOUS VIEW | Partial
+DROP STREAM | Partial
+
+Support Legend | Description
+:-------------:| -----------
+Native | All combinations supported by Native psql
+Unsupported | Not (yet)supported
+Partial | Only some combinations supported
+**Yes** | Supported by (only) this branch (not Native)
+Complete | All combinations supported
\ No newline at end of file
diff --git a/src/bin/psql/README_redshift.md b/src/bin/psql/README_redshift.md
new file mode 100644
index 0000000000000..3b292e2716b28
--- /dev/null
+++ b/src/bin/psql/README_redshift.md
@@ -0,0 +1,145 @@
+This document shows the current state of psql's auto-complete support for Amazon Redshift
+
+NOTE: This branch is maintained as a personal effort and is not sponsored / supported by my Employer or any other third-party. This is not officially supported / endorsed by Amazon in any way.
+
+See Support level of all Postgres forks: [Here](https://github.com/robins/postgres/blob/forks/src/bin/psql/README.md)
+
+Parameters | Supported State
+:---------:|:--------------:
+analyze_threshold_percent | Unsupported
+datestyle | Native
+enable_user_activity_logging | Unsupported
+extra_float_digits | Native
+query_group | Unsupported
+require_ssl | Unsupported
+search_path | Native
+statement_timeout | Native
+wlm_json_configuration | Unsupported
+
+
+
+SQL Commands | Supported State
+:----------- |:--------------:
+ABORT | Native
+ALTER DATABASE | Native
+ALTER DEFAULT PRIVILEGES | Native
+ALTER GROUP | Native
+ALTER SCHEMA | Native
+ALTER TABLE | Partial
+ALTER TABLE ADD COLUMN | **Yes**
+ALTER TABLE SET LOCATION | **Yes**
+ALTER TABLE SET FILE FORMAT | **Yes**
+ALTER TABLE SET TABLE PROPERTIES | **Yes**
+ALTER TABLE PARTITION | **Yes**
+ALTER TABLE ADD PARTITION | **Yes**
+ALTER TABLE DROP PARTITION | **Yes**
+ALTER TABLE (Similarly Many Variants) | Unsupported
+ALTER TABLE APPEND | **Yes**
+ALTER USER | Complete
+ALTER USER [NO]CREATEUSER | **Yes**
+ANALYZE | Complete
+ANALYZE VERBOSE | **Yes**
+ANALYSE PREDICATE COLUMNS | **Yes**
+ANALYZE ALL COLUMNS | **Yes**
+ANALYZE COMPRESSION | **Yes**
+BEGIN | Native
+CANCEL | **Yes**
+CLOSE | **Yes**
+COMMENT | Native
+COMMIT | Native
+COPY | Partial
+COPY .. REGION (aws-regions) | **Yes**
+COPY (Many Variants) | Unsupported
+CREATE DATABASE | Complete
+CREATE DATABASE CONNECTION LIMIT UNLIMITED | **Yes**
+CREATE DATABASE WITH | **Yes**
+CREATE DATABASE WITH OWNER | **Yes**
+CREATE DATABASE OWNER | **Yes**
+CREATE EXTERNAL SCHEMA | **Yes**
+CREATE EXTERNAL TABLE | **Yes**
+CREATE FUNCTION | Complete
+CREATE OR REPLACE FUNCTION | **Yes**
+CREATE GROUP | Native
+CREATE LIBRARY | **Yes**
+CREATE OR REPLACE LIBRARY | **Yes**
+CREATE SCHEMA | Complete
+CREATE SCHEMA AUTHORIZATION | **Yes**
+CREATE SCHEMA IF NOT EXISTS | **Yes**
+CREATE TABLE | Partial
+CREATE LOCAL TABLE | **Yes**
+CREATE TABLE IF | **Yes**
+CREATE TABLE BACKUP | **Yes**
+CREATE TABLE DISTSTYLE | **Yes**
+CREATE TABLE DISTKEY | **Yes**
+CREATE TABLE INTERLEAVED SORTKEY | **Yes**
+CREATE TABLE COMPOUND SORTKEY | **Yes**
+CREATE TABLE SORTKEY | **Yes**
+CREATE TABLE (similarly many variants) | Unsupported
+CREATE TABLE AS | **Yes**
+CREATE USER | Complete
+CREATE USER [NO]CREATEUSER | **Yes**
+CREATE VIEW | Partial
+CREATE OR REPLACE VIEW | **Yes**
+DEALLOCATE | Complete
+DEALLOCATE PREPARE | **Yes**
+DECLARE | Native
+DELETE | Complete
+DELETE FROM USING WHERE | **Yes**
+DROP DATABASE | Native
+DROP FUNCTION | Native
+DROP GROUP | Native
+DROP LIBRARY | **Yes**
+DROP SCHEMA | Complete
+DROP SCHEMA IF EXISTS | **Yes**
+DROP TABLE | Complete
+DROP TABLE IF EXISTS | **Yes**
+DROP USER | Complete
+DROP USER IF EXISTS | **Yes**
+DROP VIEW | Complete
+DROP VIEW IF EXISTS | **Yes**
+END | Native
+EXECUTE | Native
+EXPLAIN | Native
+FETCH | Complete
+FETCH NEXT | **Yes**
+FETCH ALL | **Yes**
+GRANT | Partial
+GRANT (similarly many variants) | Unsupported
+INSERT | Native
+LOCK | Native
+PREPARE | Native
+RESET | Native
+REVOKE | Partial
+REVOKE GRANT | **Yes**
+REVOKE (similarly many variants) | Unsupported
+ROLLBACK | Native
+SELECT | Partial
+SELECT TOP | **Yes**
+SELECT ALL | **Yes**
+SELECT DISTINCT | **Yes**
+SELECT (similarly many variants) | Unsupported
+SELECT INTO | **WIP**
+SET | Complete
+SET SEED TO | **Yes**
+SHOW | Native
+START TRANSACTION | Native
+TRUNCATE | Complete
+TRUNCATE TABLE | **Yes**
+UNLOAD | **Yes**
+UPDATE | Complete
+UPDATE SET FROM | **Yes**
+UPDATE SET WHERE | **Yes**
+VACUUM | Complete
+VACUUM SORT | **Yes**
+VACUUM DELETE | **Yes**
+VACUUM REINDEX | **Yes**
+VACUUM TO | **Yes**
+
+
+Support Legend | Description
+:-------------:| -----------
+Native | All combinations supported by Native psql
+Unsupported | Not (yet)supported
+Partial | Only some combinations supported
+**Yes** | Supported by (only) this branch (not Native)
+Complete | All combinations supported
\ No newline at end of file
diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c
index 041b5e0c87746..0bc60023457ab 100644
--- a/src/bin/psql/command.c
+++ b/src/bin/psql/command.c
@@ -43,6 +43,14 @@
#include "settings.h"
#include "variables.h"
+/* Macro to easily identify which Engine (type) are we speaking with
+ Any change here should probably be replicated elsewhere since
+ #define for various SQLs (in this script) employ there own string-compare */
+ #define IS_COCKROACHDB (strncmp(pset.sengine, "cockroachdb", 11) == 0)
+ #define IS_PGBOUNCER (strncmp(pset.sengine, "pgbouncer", 9) == 0)
+ #define IS_PIPELINEDB (strncmp(pset.sengine, "pipelinedb", 10) == 0)
+ #define IS_REDSHIFT (strncmp(pset.sengine, "redshift", 8) == 0)
+
/*
* Editable database object types.
*/
@@ -162,6 +170,10 @@ static void printSSLInfo(void);
static bool printPsetInfo(const char *param, struct printQueryOpt *popt);
static char *pset_value_string(const char *param, struct printQueryOpt *popt);
+static PGresult *exec_query(const char *query);
+static char *escape_string(const char *text);
+static char *get_guctype(const char *varname);
+
#ifdef WIN32
static void checkWin32Codepage(void);
#endif
@@ -279,6 +291,14 @@ exec_command(const char *cmd,
backslashResult status;
bool active_branch = conditional_active(cstack);
+ /* PgBouncer supports no \* commands and so we skip if we're speaking with PgBouncer */
+ if (IS_PGBOUNCER)
+ {
+ psql_error("\\%s command ignored - PgBouncer doesn't support ( \\* ) backslash commands.\n",
+ cmd);
+ return PSQL_CMD_ERROR;
+ }
+
/*
* In interactive mode, warn when we're ignoring a command within a false
* \if-branch. But we continue on, so as to parse and discard the right
@@ -856,7 +876,10 @@ exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
switch (cmd[2])
{
case 's':
- success = listForeignServers(pattern, show_verbose);
+ if (IS_REDSHIFT)
+ success = listExternalSchemasInRedshift(pattern, show_verbose);
+ else
+ success = listForeignServers(pattern, show_verbose);
break;
case 'u':
success = listUserMappings(pattern, show_verbose);
@@ -865,7 +888,10 @@ exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
success = listForeignDataWrappers(pattern, show_verbose);
break;
case 't':
- success = listForeignTables(pattern, show_verbose);
+ if (IS_REDSHIFT)
+ success = listExternalTablesInRedshift(pattern, show_verbose);
+ else
+ success = listForeignTables(pattern, show_verbose);
break;
default:
status = PSQL_CMD_UNKNOWN;
@@ -2873,6 +2899,7 @@ do_connect(enum trivalue reuse_previous_specification,
PGconn *o_conn = pset.db,
*n_conn;
char *password = NULL;
+ char *new_password = NULL;
bool keep_password;
bool has_connection_string;
bool reuse_previous;
@@ -2960,7 +2987,23 @@ do_connect(enum trivalue reuse_previous_specification,
*/
if (pset.getPassword == TRI_YES)
{
- password = prompt_for_password(user);
+ if (pset.credential_source == AWS_IAM_REDSHIFT)
+ {
+ if (request_password_from_external_source(&user, &new_password, host))
+ password = pg_strdup(new_password);
+ else
+ {
+ psql_error("Unable to fetch new Username / Password from IAM\n");
+ password = NULL;
+ }
+ }
+ else if (pset.credential_source == DEFAULT)
+ password = prompt_for_password(user);
+ else
+ {
+ fprintf(stderr, _("getPassword enabled but Source unclear. Exiting.\n"));
+ exit(EXIT_FAILURE);
+ }
}
else if (o_conn && keep_password)
{
@@ -3114,6 +3157,7 @@ connection_warnings(bool in_startup)
/* Try to get full text form, might include "devel" etc */
server_version = PQparameterStatus(pset.db, "server_version");
+
/* Otherwise fall back on pset.sversion */
if (!server_version)
{
@@ -3122,8 +3166,8 @@ connection_warnings(bool in_startup)
server_version = sverbuf;
}
- printf(_("%s (%s, server %s)\n"),
- pset.progname, PG_VERSION, server_version);
+ printf(_("%s (client-version:%s, server-version:%s, engine:%s)\n"),
+ pset.progname, PG_VERSION, server_version, pset.sengine);
}
/* For version match, only print psql banner on startup. */
else if (in_startup)
@@ -3211,18 +3255,14 @@ SyncVariables(void)
{
char vbuf[32];
const char *server_version;
+ const char *server_engine;
+ char *guctype;
/* get stuff from connection */
pset.encoding = PQclientEncoding(pset.db);
pset.popt.topt.encoding = pset.encoding;
pset.sversion = PQserverVersion(pset.db);
- SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
- SetVariable(pset.vars, "USER", PQuser(pset.db));
- SetVariable(pset.vars, "HOST", PQhost(pset.db));
- SetVariable(pset.vars, "PORT", PQport(pset.db));
- SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
-
/* this bit should match connection_warnings(): */
/* Try to get full text form of version, might include "devel" etc */
server_version = PQparameterStatus(pset.db, "server_version");
@@ -3232,7 +3272,50 @@ SyncVariables(void)
formatPGVersionNumber(pset.sversion, true, vbuf, sizeof(vbuf));
server_version = vbuf;
}
+
+ /* Check whether a given GUC exists */
+ guctype = get_guctype("continuous_queries_enabled");
+ if (guctype != NULL)
+ server_engine = "pipelinedb";
+ else
+ {
+ guctype = get_guctype("wlm_query_slot_count");
+ if (guctype != NULL)
+ server_engine = "redshift";
+ else
+ {
+ guctype = get_guctype("node_id");
+ if (guctype != NULL)
+ server_engine = "cockroachdb";
+ else
+ {
+ guctype = get_guctype("rds.extensions");
+ if (guctype != NULL)
+ server_engine = "rdspostgres";
+ else
+ {
+ if (strstr(server_version, "bouncer") != NULL)
+ server_engine = "pgbouncer";
+ else
+ server_engine = "postgres";
+ }
+ }
+ }
+ }
+
+ if (guctype)
+ free(guctype);
+
+ pset.sengine = server_engine;
+
+ SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
+ SetVariable(pset.vars, "USER", PQuser(pset.db));
+ SetVariable(pset.vars, "HOST", PQhost(pset.db));
+ SetVariable(pset.vars, "PORT", PQport(pset.db));
+ SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
+
SetVariable(pset.vars, "SERVER_VERSION_NAME", server_version);
+ SetVariable(pset.vars, "SERVER_ENGINE", server_engine);
snprintf(vbuf, sizeof(vbuf), "%d", pset.sversion);
SetVariable(pset.vars, "SERVER_VERSION_NUM", vbuf);
@@ -3242,6 +3325,87 @@ SyncVariables(void)
PQsetErrorContextVisibility(pset.db, pset.show_context);
}
+// XXX: Ideally the following 3 functions should be included from common definitions
+/*
+ * Execute a query and report any errors. This should be the preferred way of
+ * talking to the database in this file.
+ */
+ static PGresult *
+ exec_query(const char *query)
+ {
+ PGresult *result;
+
+ if (query == NULL || !pset.db || PQstatus(pset.db) != CONNECTION_OK)
+ return NULL;
+
+ result = PQexec(pset.db, query);
+
+ if (PQresultStatus(result) != PGRES_TUPLES_OK)
+ {
+ #ifdef NOT_USED
+ psql_error("tab completion query failed: %s\nQuery was:\n%s\n",
+ PQerrorMessage(pset.db), query);
+ #endif
+ PQclear(result);
+ result = NULL;
+ }
+
+ return result;
+ }
+
+/*
+ * escape_string - Escape argument for use as string literal.
+ *
+ * The returned value has to be freed.
+ */
+ static char *
+ escape_string(const char *text)
+ {
+ size_t text_length;
+ char *result;
+
+ text_length = strlen(text);
+
+ result = pg_malloc(text_length * 2 + 1);
+ PQescapeStringConn(pset.db, result, text, text_length, NULL);
+
+ return result;
+ }
+
+/*
+ * Look up the type for the GUC variable with the passed name.
+ *
+ * Returns NULL if the variable is unknown. Otherwise the returned string,
+ * containing the type, has to be freed.
+ */
+ static char *
+ get_guctype(const char *varname)
+ {
+ PQExpBufferData query_buffer;
+ char *e_varname;
+ PGresult *result;
+ char *guctype = NULL;
+
+ e_varname = escape_string(varname);
+
+ initPQExpBuffer(&query_buffer);
+ appendPQExpBuffer(&query_buffer,
+ "SELECT vartype FROM pg_catalog.pg_settings "
+ "WHERE pg_catalog.lower(name) = pg_catalog.lower('%s')",
+ e_varname);
+
+ result = exec_query(query_buffer.data);
+ termPQExpBuffer(&query_buffer);
+ free(e_varname);
+
+ if (PQresultStatus(result) == PGRES_TUPLES_OK && PQntuples(result) > 0)
+ guctype = pg_strdup(PQgetvalue(result, 0, 0));
+
+ PQclear(result);
+
+ return guctype;
+ }
+
/*
* UnsyncVariables
*
@@ -4408,7 +4572,10 @@ lookup_object_oid(EditableObjectType obj_type, const char *desc,
*/
appendPQExpBufferStr(query, "SELECT ");
appendStringLiteralConn(query, desc, pset.db);
- appendPQExpBuffer(query, "::pg_catalog.regclass::pg_catalog.oid");
+ if (IS_COCKROACHDB)
+ appendPQExpBuffer(query, "::regclass::OID");
+ else
+ appendPQExpBuffer(query, "::pg_catalog.regclass::pg_catalog.oid");
break;
}
diff --git a/src/bin/psql/common.c b/src/bin/psql/common.c
index 9b59ee840b91a..3a69fe6424cd1 100644
--- a/src/bin/psql/common.c
+++ b/src/bin/psql/common.c
@@ -28,12 +28,20 @@
#include "crosstabview.h"
#include "fe_utils/mbprint.h"
+#include "jsmn.h"
static bool DescribeQuery(const char *query, double *elapsed_msec);
static bool ExecQueryUsingCursor(const char *query, double *elapsed_msec);
static bool command_no_begin(const char *query);
static bool is_select_command(const char *query);
+static int jsoneq(const char *json, jsmntok_t *tok, const char *s) {
+ if (tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start &&
+ strncmp(json + tok->start, s, tok->end - tok->start) == 0) {
+ return 0;
+ }
+ return -1;
+}
/*
* openQueryOutputFile --- attempt to open a query output file
@@ -110,6 +118,140 @@ setQFout(const char *fname)
return true;
}
+char *
+stripIAMFromUsernameIfExists(const char *username)
+{
+ char *new_username = NULL;
+
+ if (strncmp(username, "IAMA", 4) == 0)
+ {
+ new_username = pg_malloc(strnlen(username, 60) - 4);
+ strlcpy(new_username, username+5, strnlen(username, 60) - 4);
+ }
+ else if (strncmp(username, "IAM", 3) == 0)
+ {
+ new_username = pg_malloc(strnlen(username, 60) - 3);
+ strlcpy(new_username, username+4, strnlen(username, 60) - 3);
+ }
+ else
+ new_username = pg_strdup(username);
+
+ return new_username;
+}
+
+char *
+stripSubDomainFromHost(const char *host)
+{
+ int len;
+ char *stripped_host = strstr(host, ".");
+
+ if (stripped_host)
+ {
+ len = stripped_host - host;
+ stripped_host = pg_malloc(len+1);
+
+ if (stripped_host != NULL)
+ strlcpy(stripped_host, host, len+1);
+ }
+ else
+ stripped_host = pg_strdup(host);
+
+ return stripped_host;
+}
+
+/*
+ * request_password_from_external_source
+ *
+ * Generalized function to fetch usernames and passwords from external source.
+ */
+bool
+request_password_from_external_source(char **username, char **password, const char *host)
+{
+ FILE *fp;
+ char linebuffer[1035];
+ char filebuffer[2000];
+ char *aws_command;
+ char *new_username = NULL;
+ char *stripped_host = NULL;
+ int i;
+ int r;
+ char *new_password = NULL;
+ bool found_password = false;
+ bool found_username = false;
+ jsmn_parser p;
+ jsmntok_t t[128]; /* We expect no more than 128 tokens */
+
+ strcpy(filebuffer, " ");
+ /* Open the command for reading. */
+
+ new_username = stripIAMFromUsernameIfExists(*username);
+ stripped_host = stripSubDomainFromHost(host);
+
+ aws_command = psprintf("aws redshift get-cluster-credentials --auto-create --db-user %s --cluster-identifier %s", new_username, stripped_host);
+ printf("\nCLI Command (Just FYI): %s\n", aws_command);
+ fp = popen(aws_command, "r");
+ free(aws_command);
+
+ //fp = popen("cat /home/pi/projects/postgres/src/bin/psql/cluster.txt", "r");
+ if (fp == NULL)
+ {
+ psql_error("Unable to run AWS CLI to fetch IAM authentication.\n");
+ exit(1);
+ }
+ else
+ {
+ /* Read the output a line at a time - output it. */
+ while (fgets(linebuffer, sizeof(linebuffer)-1, fp) != NULL)
+ {
+ strncat(filebuffer, linebuffer, sizeof(linebuffer));
+ }
+
+ pclose (fp);
+ }
+
+ jsmn_init(&p);
+ r = jsmn_parse(&p, filebuffer, strlen(filebuffer), t, sizeof(t)/sizeof(t[0]));
+ if (r < 0) {
+ psql_error("Unable to parse CLI JSON Response: %d\n", r);
+ return false;
+ }
+
+ /* Assume the top-level element is an object */
+ if (r < 1 || t[0].type != JSMN_OBJECT) {
+ psql_error("CLI Response not a JSON object\n");
+ return false;
+ }
+
+ /* Loop over all keys of the root object */
+ for (i = 1; i < r; i++) {
+ if (jsoneq(filebuffer, &t[i], "DbUser") == 0) {
+ new_username = pg_malloc(t[i+1].end-t[i+1].start + 2);
+ StrNCpy(new_username, filebuffer + t[i+1].start, t[i+1].end-t[i+1].start + 1);
+ found_username = true;
+ i++;
+ } else if (jsoneq(filebuffer, &t[i], "DbPassword") == 0) {
+ new_password = pg_malloc(t[i+1].end-t[i+1].start + 2);
+ StrNCpy(new_password, filebuffer + t[i+1].start, t[i+1].end-t[i+1].start + 1);
+ found_password = true;
+ i++;
+ } else if (jsoneq(filebuffer, &t[i], "Expiration") == 0) {
+ // XXX: Need to cross check current time vs Expiration.
+ i++;
+ } else {
+ psql_error("Unexpected key: %.*s\n", t[i].end-t[i].start,
+ filebuffer + t[i].start);
+ }
+ }
+
+ if (found_username && found_password)
+ {
+ *username = pg_strdup(new_username);
+ *password = pg_strdup(new_password);
+ return true;
+ }
+ return false;
+}
+
/*
* Variable-fetching callback for flex lexer
diff --git a/src/bin/psql/common.h b/src/bin/psql/common.h
index f34868b54e4e6..0f965cc2dce62 100644
--- a/src/bin/psql/common.h
+++ b/src/bin/psql/common.h
@@ -46,4 +46,8 @@ extern void expand_tilde(char **filename);
extern bool recognized_connection_string(const char *connstr);
+extern bool request_password_from_external_source(char **username, char **password, const char *host);
+extern char *stripIAMFromUsernameIfExists(const char *username);
+extern char *stripSubDomainFromHost(const char *host);
+
#endif /* COMMON_H */
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index 06885715a61cd..a6df5fe701bd6 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -26,6 +26,11 @@
#include "settings.h"
#include "variables.h"
+/* Macro to easily identify which Engine (type) are we speaking with */
+#define IS_COCKROACHDB (strncmp(pset.sengine, "cockroachdb", 11) == 0)
+#define IS_PGBOUNCER (strncmp(pset.sengine, "pgbouncer", 9) == 0)
+#define IS_PIPELINEDB (strncmp(pset.sengine, "pipelinedb", 10) == 0)
+#define IS_REDSHIFT (strncmp(pset.sengine, "redshift", 8) == 0)
static bool describeOneTableDetails(const char *schemaname,
const char *relationname,
@@ -112,8 +117,8 @@ describeAggregates(const char *pattern, bool verbose, bool showSystem)
" AND n.nspname <> 'information_schema'\n");
processSQLNamePattern(pset.db, &buf, pattern, true, false,
- "n.nspname", "p.proname", NULL,
- "pg_catalog.pg_function_is_visible(p.oid)");
+ "n.nspname", "p.proname", NULL,
+ (!IS_COCKROACHDB?"pg_catalog.pg_function_is_visible(p.oid)":NULL));
appendPQExpBufferStr(&buf, "ORDER BY 1, 2, 4;");
@@ -345,8 +350,23 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
" p.proname as \"%s\",\n",
gettext_noop("Schema"),
gettext_noop("Name"));
-
- if (pset.sversion >= 80400)
+ if (IS_COCKROACHDB)
+ appendPQExpBuffer(&buf,
+ " 'Not Supported Yet' as \"%s\",\n"
+ " 'Not Supported Yet' as \"%s\",\n"
+ " CASE\n"
+ " WHEN p.proisagg THEN '%s'\n"
+ " WHEN p.proiswindow THEN '%s'\n"
+ " ELSE '%s'\n"
+ " END as \"%s\"",
+ gettext_noop("Result data type"),
+ gettext_noop("Argument data types"),
+ /* translator: "agg" is short for "aggregate" */
+ gettext_noop("agg"),
+ gettext_noop("window"),
+ gettext_noop("normal"),
+ gettext_noop("Type"));
+ else if (pset.sversion >= 80400)
appendPQExpBuffer(&buf,
" pg_catalog.pg_get_function_result(p.oid) as \"%s\",\n"
" pg_catalog.pg_get_function_arguments(p.oid) as \"%s\",\n"
@@ -459,11 +479,11 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
gettext_noop("Security"));
appendPQExpBufferStr(&buf, ",\n ");
printACLColumn(&buf, "p.proacl");
+ if (!IS_COCKROACHDB)
+ appendPQExpBuffer(&buf, ",\n l.lanname as \"%s\"", gettext_noop("Language"));
appendPQExpBuffer(&buf,
- ",\n l.lanname as \"%s\""
- ",\n p.prosrc as \"%s\""
+ ",\n p.prosrc as \"%s\""
",\n pg_catalog.obj_description(p.oid, 'pg_proc') as \"%s\"",
- gettext_noop("Language"),
gettext_noop("Source code"),
gettext_noop("Description"));
}
@@ -472,7 +492,7 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
"\nFROM pg_catalog.pg_proc p"
"\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n");
- if (verbose)
+ if (verbose && !IS_COCKROACHDB)
appendPQExpBufferStr(&buf,
" LEFT JOIN pg_catalog.pg_language l ON l.oid = p.prolang\n");
@@ -494,7 +514,7 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
}
appendPQExpBufferStr(&buf, "NOT p.proisagg\n");
}
- if (!showTrigger)
+ if (!showTrigger && !IS_COCKROACHDB)
{
if (have_where)
appendPQExpBufferStr(&buf, " AND ");
@@ -529,7 +549,7 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
appendPQExpBufferStr(&buf, "p.proisagg\n");
needs_or = true;
}
- if (showTrigger)
+ if (showTrigger && !IS_COCKROACHDB)
{
if (needs_or)
appendPQExpBufferStr(&buf, " OR ");
@@ -544,12 +564,14 @@ describeFunctions(const char *functypes, const char *pattern, bool verbose, bool
appendPQExpBufferStr(&buf, "p.proiswindow\n");
needs_or = true;
}
+ if (!needs_or)
+ appendPQExpBufferStr(&buf, " TRUE ");
appendPQExpBufferStr(&buf, " )\n");
}
processSQLNamePattern(pset.db, &buf, pattern, have_where, false,
"n.nspname", "p.proname", NULL,
- "pg_catalog.pg_function_is_visible(p.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_function_is_visible(p.oid)":NULL));
if (!showSystem && !pattern)
appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n"
@@ -680,7 +702,7 @@ describeTypes(const char *pattern, bool verbose, bool showSystem)
processSQLNamePattern(pset.db, &buf, pattern, true, false,
"n.nspname", "t.typname",
"pg_catalog.format_type(t.oid, NULL)",
- "pg_catalog.pg_type_is_visible(t.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_type_is_visible(t.oid)":NULL));
appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
@@ -756,7 +778,7 @@ describeOperators(const char *pattern, bool verbose, bool showSystem)
processSQLNamePattern(pset.db, &buf, pattern, !showSystem && !pattern, true,
"n.nspname", "o.oprname", NULL,
- "pg_catalog.pg_operator_is_visible(o.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_operator_is_visible(o.oid)":NULL));
appendPQExpBufferStr(&buf, "ORDER BY 1, 2, 3, 4;");
@@ -790,13 +812,22 @@ listAllDbs(const char *pattern, bool verbose)
initPQExpBuffer(&buf);
- printfPQExpBuffer(&buf,
- "SELECT d.datname as \"%s\",\n"
- " pg_catalog.pg_get_userbyid(d.datdba) as \"%s\",\n"
- " pg_catalog.pg_encoding_to_char(d.encoding) as \"%s\",\n",
- gettext_noop("Name"),
- gettext_noop("Owner"),
- gettext_noop("Encoding"));
+ if (IS_COCKROACHDB)
+ printfPQExpBuffer(&buf,
+ "SELECT d.datname as \"%s\",\n"
+ " pg_catalog.pg_get_userbyid(d.datdba) as \"%s\",\n"
+ " 'Not Supported Yet' as \"%s\",\n",
+ gettext_noop("Name"),
+ gettext_noop("Owner"),
+ gettext_noop("Encoding"));
+ else
+ printfPQExpBuffer(&buf,
+ "SELECT d.datname as \"%s\",\n"
+ " pg_catalog.pg_get_userbyid(d.datdba) as \"%s\",\n"
+ " pg_catalog.pg_encoding_to_char(d.encoding) as \"%s\",\n",
+ gettext_noop("Name"),
+ gettext_noop("Owner"),
+ gettext_noop("Encoding"));
if (pset.sversion >= 80400)
appendPQExpBuffer(&buf,
" d.datcollate as \"%s\",\n"
@@ -805,14 +836,14 @@ listAllDbs(const char *pattern, bool verbose)
gettext_noop("Ctype"));
appendPQExpBufferStr(&buf, " ");
printACLColumn(&buf, "d.datacl");
- if (verbose && pset.sversion >= 80200)
+ if (verbose && pset.sversion >= 80200 && !IS_COCKROACHDB)
appendPQExpBuffer(&buf,
",\n CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT')\n"
" THEN pg_catalog.pg_size_pretty(pg_catalog.pg_database_size(d.datname))\n"
" ELSE 'No Access'\n"
" END as \"%s\"",
gettext_noop("Size"));
- if (verbose && pset.sversion >= 80000)
+ if (verbose && pset.sversion >= 80000 && !IS_COCKROACHDB)
appendPQExpBuffer(&buf,
",\n t.spcname as \"%s\"",
gettext_noop("Tablespace"));
@@ -822,7 +853,7 @@ listAllDbs(const char *pattern, bool verbose)
gettext_noop("Description"));
appendPQExpBufferStr(&buf,
"\nFROM pg_catalog.pg_database d\n");
- if (verbose && pset.sversion >= 80000)
+ if (verbose && pset.sversion >= 80000 && !IS_COCKROACHDB)
appendPQExpBufferStr(&buf,
" JOIN pg_catalog.pg_tablespace t on d.dattablespace = t.oid\n");
@@ -978,9 +1009,14 @@ permissionsList(const char *pattern)
* point of view. You can see 'em by explicit request though, eg with \z
* pg_catalog.*
*/
- processSQLNamePattern(pset.db, &buf, pattern, true, false,
- "n.nspname", "c.relname", NULL,
- "n.nspname !~ '^pg_' AND pg_catalog.pg_table_is_visible(c.oid)");
+ if (IS_COCKROACHDB)
+ processSQLNamePattern(pset.db, &buf, pattern, true, false,
+ "n.nspname", "c.relname", NULL,
+ "n.nspname !~ '^pg_' AND");
+ else
+ processSQLNamePattern(pset.db, &buf, pattern, true, false,
+ "n.nspname", "c.relname", NULL,
+ "n.nspname !~ '^pg_' AND pg_catalog.pg_table_is_visible(c.oid)");
appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
@@ -1019,7 +1055,7 @@ listDefaultACLs(const char *pattern)
printQueryOpt myopt = pset.popt;
static const bool translate_columns[] = {false, false, true, false};
- if (pset.sversion < 90000)
+ if (pset.sversion < 90000 && !IS_REDSHIFT)
{
char sverbuf[32];
@@ -1031,12 +1067,17 @@ listDefaultACLs(const char *pattern)
initPQExpBuffer(&buf);
- printfPQExpBuffer(&buf,
- "SELECT pg_catalog.pg_get_userbyid(d.defaclrole) AS \"%s\",\n"
- " n.nspname AS \"%s\",\n"
+ if (IS_REDSHIFT)
+ printfPQExpBuffer(&buf,
+ "SELECT pg_catalog.pg_get_userbyid(d.defacluser) AS \"%s\",\n", gettext_noop("Owner"));
+ else
+ printfPQExpBuffer(&buf,
+ "SELECT pg_catalog.pg_get_userbyid(d.defaclrole) AS \"%s\",\n", gettext_noop("Owner"));
+
+ appendPQExpBuffer(&buf,
+ " n.nspname AS \"%s\",\n"
" CASE d.defaclobjtype WHEN '%c' THEN '%s' WHEN '%c' THEN '%s' WHEN '%c' THEN '%s' WHEN '%c' THEN '%s' WHEN '%c' THEN '%s' END AS \"%s\",\n"
" ",
- gettext_noop("Owner"),
gettext_noop("Schema"),
DEFACLOBJ_RELATION,
gettext_noop("table"),
@@ -1133,7 +1174,7 @@ objectDescription(const char *pattern, bool showSystem)
processSQLNamePattern(pset.db, &buf, pattern, !showSystem && !pattern,
false, "n.nspname", "pgc.conname", NULL,
- "pg_catalog.pg_table_is_visible(c.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_table_is_visible(c.oid)":NULL));
/* Domain constraint descriptions */
appendPQExpBuffer(&buf,
@@ -1155,7 +1196,7 @@ objectDescription(const char *pattern, bool showSystem)
processSQLNamePattern(pset.db, &buf, pattern, !showSystem && !pattern,
false, "n.nspname", "pgc.conname", NULL,
- "pg_catalog.pg_type_is_visible(t.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_type_is_visible(t.oid)":NULL));
/*
@@ -1183,7 +1224,7 @@ objectDescription(const char *pattern, bool showSystem)
processSQLNamePattern(pset.db, &buf, pattern, true, false,
"n.nspname", "o.opcname", NULL,
- "pg_catalog.pg_opclass_is_visible(o.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_opclass_is_visible(o.oid)":NULL));
}
/*
@@ -1212,7 +1253,7 @@ objectDescription(const char *pattern, bool showSystem)
processSQLNamePattern(pset.db, &buf, pattern, true, false,
"n.nspname", "opf.opfname", NULL,
- "pg_catalog.pg_opfamily_is_visible(opf.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_opfamily_is_visible(opf.oid)":NULL));
}
/* Rule descriptions (ignore rules for views) */
@@ -1254,7 +1295,7 @@ objectDescription(const char *pattern, bool showSystem)
processSQLNamePattern(pset.db, &buf, pattern, !showSystem && !pattern, false,
"n.nspname", "t.tgname", NULL,
- "pg_catalog.pg_table_is_visible(c.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_table_is_visible(c.oid)":NULL));
appendPQExpBufferStr(&buf,
") AS tt\n"
@@ -1310,7 +1351,7 @@ describeTableDetails(const char *pattern, bool verbose, bool showSystem)
processSQLNamePattern(pset.db, &buf, pattern, !showSystem && !pattern, false,
"n.nspname", "c.relname", NULL,
- "pg_catalog.pg_table_is_visible(c.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_table_is_visible(c.oid)":NULL));
appendPQExpBufferStr(&buf, "ORDER BY 2, 3;");
@@ -1379,7 +1420,9 @@ describeOneTableDetails(const char *schemaname,
bool printTableInitialized = false;
int i;
char *view_def = NULL;
- char *headers[11];
+ char *headers[18];
+ char **seq_values = NULL;
+ char **ptr;
PQExpBufferData title;
PQExpBufferData tmpbuf;
int cols;
@@ -1399,6 +1442,7 @@ describeOneTableDetails(const char *schemaname,
char *reloftype;
char relpersistence;
char relreplident;
+ char hassortkey;
} tableinfo;
bool show_column_details = false;
bool retval;
@@ -1414,7 +1458,22 @@ describeOneTableDetails(const char *schemaname,
initPQExpBuffer(&tmpbuf);
/* Get general table info */
- if (pset.sversion >= 90500)
+ if (IS_COCKROACHDB)
+ {
+ printfPQExpBuffer(&buf,
+ "SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, "
+ "c.relhastriggers, 'Not Supported Yet' AS relrowsecurity, 'Not Supported Yet' AS relforcerowsecurity, "
+ "c.relhasoids, %s, c.reltablespace, "
+ "'', 'Not Supported Yet' AS relpersistence, 'Not Supported Yet' AS relreplident\n"
+ "FROM pg_catalog.pg_class c\n "
+ "LEFT JOIN pg_catalog.pg_class tc ON (c.reltoastrelid = tc.oid)\n"
+ "WHERE c.oid = '%s'::OID;",
+ (verbose ?
+ "'Not Supported Yet'\n"
+ : "''"),
+ oid);
+ }
+ else if (pset.sversion >= 90500)
{
printfPQExpBuffer(&buf,
"SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, "
@@ -1509,12 +1568,26 @@ describeOneTableDetails(const char *schemaname,
}
else if (pset.sversion >= 80000)
{
+
+ if (IS_REDSHIFT) {
+ printfPQExpBuffer(&buf,
+ "SELECT relchecks, relkind, relhasindex, relhasrules, "
+ "reltriggers <> 0, false, false, relhasoids, "
+ "%s, reltablespace, (SELECT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = oid AND attsortkeyord <> 0)) as relhassortkey \n"
+ "FROM pg_catalog.pg_class WHERE oid = '%s';",
+ (verbose ?
+ "pg_catalog.array_to_string(reloptions, E', ')" : "''"),
+ oid);
+ }
+ else
+ {
printfPQExpBuffer(&buf,
"SELECT relchecks, relkind, relhasindex, relhasrules, "
"reltriggers <> 0, false, false, relhasoids, "
"'', reltablespace\n"
"FROM pg_catalog.pg_class WHERE oid = '%s';",
oid);
+ }
}
else
{
@@ -1550,6 +1623,8 @@ describeOneTableDetails(const char *schemaname,
pg_strdup(PQgetvalue(res, 0, 8)) : NULL;
tableinfo.tablespace = (pset.sversion >= 80000) ?
atooid(PQgetvalue(res, 0, 9)) : 0;
+ tableinfo.hassortkey = (IS_REDSHIFT)?
+ (strcmp(PQgetvalue(res, 0, 10), "t") == 0) : '0';
tableinfo.reloftype = (pset.sversion >= 90000 &&
strcmp(PQgetvalue(res, 0, 10), "") != 0) ?
pg_strdup(PQgetvalue(res, 0, 10)) : NULL;
@@ -1689,30 +1764,58 @@ describeOneTableDetails(const char *schemaname,
* you are adding column(s) preceding to verbose-only columns.
*/
printfPQExpBuffer(&buf, "SELECT a.attname,");
- appendPQExpBufferStr(&buf, "\n pg_catalog.format_type(a.atttypid, a.atttypmod),"
- "\n (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)"
- "\n FROM pg_catalog.pg_attrdef d"
- "\n WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef),"
+ if (IS_COCKROACHDB)
+ appendPQExpBufferStr(&buf, "\n pg_catalog.format_type(a.atttypid, a.atttypmod),"
+ "\n 'Not Supported Yet'," // (Subquery not fully supported in CockroachDB)
"\n a.attnotnull, a.attnum,");
- if (pset.sversion >= 90100)
+ else
+ appendPQExpBufferStr(&buf, "\n pg_catalog.format_type(a.atttypid, a.atttypmod),"
+ "\n (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)"
+ "\n FROM pg_catalog.pg_attrdef d"
+ "\n WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef),"
+ "\n a.attnotnull, a.attnum,");
+ if (IS_COCKROACHDB)
+ appendPQExpBufferStr(&buf, "\n 'Not Supported Yet' AS attcollation");
+ else if (pset.sversion >= 90100)
appendPQExpBufferStr(&buf, "\n (SELECT c.collname FROM pg_catalog.pg_collation c, pg_catalog.pg_type t\n"
" WHERE c.oid = a.attcollation AND t.oid = a.atttypid AND a.attcollation <> t.typcollation) AS attcollation");
else
appendPQExpBufferStr(&buf, "\n NULL AS attcollation");
- if (pset.sversion >= 100000)
+ if (IS_COCKROACHDB)
+ appendPQExpBufferStr(&buf, ",\n 'Not Supported Yet' AS attidentity");
+ else if (pset.sversion >= 100000)
appendPQExpBufferStr(&buf, ",\n a.attidentity");
else
appendPQExpBufferStr(&buf, ",\n ''::pg_catalog.char AS attidentity");
- if (tableinfo.relkind == RELKIND_INDEX)
+ if ((tableinfo.relkind == RELKIND_INDEX && !IS_COCKROACHDB))
appendPQExpBufferStr(&buf, ",\n pg_catalog.pg_get_indexdef(a.attrelid, a.attnum, TRUE) AS indexdef");
else
appendPQExpBufferStr(&buf, ",\n NULL AS indexdef");
- if (tableinfo.relkind == RELKIND_FOREIGN_TABLE && pset.sversion >= 90200)
+ if ((tableinfo.relkind == RELKIND_FOREIGN_TABLE && pset.sversion >= 90200 && IS_COCKROACHDB))
appendPQExpBufferStr(&buf, ",\n CASE WHEN attfdwoptions IS NULL THEN '' ELSE "
" '(' || pg_catalog.array_to_string(ARRAY(SELECT pg_catalog.quote_ident(option_name) || ' ' || pg_catalog.quote_literal(option_value) FROM "
" pg_catalog.pg_options_to_table(attfdwoptions)), ', ') || ')' END AS attfdwoptions");
else
appendPQExpBufferStr(&buf, ",\n NULL AS attfdwoptions");
+ if (IS_REDSHIFT) {
+ appendPQExpBufferStr(&buf, ",\n (SELECT format_encoding(attencodingtype) FROM pg_catalog.pg_attribute att \n"
+ " WHERE att.attrelid = a.attrelid AND att.attnum = a.attnum) AS attcompression");
+ appendPQExpBufferStr(&buf, ",\n (SELECT attisdistkey FROM pg_catalog.pg_attribute att \n"
+ " WHERE att.attrelid = a.attrelid AND att.attnum = a.attnum) AS attisdistkey");
+ appendPQExpBufferStr(&buf, ",\n (SELECT ABS(attsortkeyord) FROM pg_catalog.pg_attribute att \n"
+ " WHERE att.attrelid = a.attrelid AND att.attnum = a.attnum) AS attsortkeyord");
+ appendPQExpBufferStr(&buf, ",\n (SELECT attispreloaded FROM pg_catalog.pg_attribute att \n"
+ " WHERE att.attrelid = a.attrelid AND att.attnum = a.attnum) AS attispreloaded");
+ appendPQExpBufferStr(&buf, ",\n (SELECT CASE WHEN attencrypttype = 0 THEN 'none' ELSE attencrypttype::TEXT END FROM pg_catalog.pg_attribute att \n"
+ " WHERE att.attrelid = a.attrelid AND att.attnum = a.attnum) AS attencrypttype");
+ } else {
+ appendPQExpBufferStr(&buf, ",\n NULL AS attcompression");
+ appendPQExpBufferStr(&buf, ",\n NULL AS attisdistkey");
+ appendPQExpBufferStr(&buf, ",\n NULL AS attsortkeyord");
+ appendPQExpBufferStr(&buf, ",\n NULL AS attispreloaded");
+ appendPQExpBufferStr(&buf, ",\n NULL AS attencrypttype");
+ }
+
if (verbose)
{
appendPQExpBufferStr(&buf, ",\n a.attstorage");
@@ -1732,7 +1835,10 @@ describeOneTableDetails(const char *schemaname,
}
appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_attribute a");
- appendPQExpBuffer(&buf, "\nWHERE a.attrelid = '%s' AND a.attnum > 0 AND NOT a.attisdropped", oid);
+ if (IS_COCKROACHDB)
+ appendPQExpBuffer(&buf, "\nWHERE a.attrelid = '%s'::OID AND a.attnum > 0 AND NOT a.attisdropped", oid);
+ else
+ appendPQExpBuffer(&buf, "\nWHERE a.attrelid = '%s' AND a.attnum > 0 AND NOT a.attisdropped", oid);
appendPQExpBufferStr(&buf, "\nORDER BY a.attnum;");
res = PSQLexec(buf.data);
@@ -1808,6 +1914,14 @@ describeOneTableDetails(const char *schemaname,
headers[1] = gettext_noop("Type");
cols = 2;
+ if (IS_REDSHIFT && tableinfo.relkind == RELKIND_RELATION) {
+ headers[cols++] = gettext_noop("Encoding");
+ headers[cols++] = gettext_noop("DistKey");
+ headers[cols++] = gettext_noop("SortKey");
+ headers[cols++] = gettext_noop("Preload");
+ headers[cols++] = gettext_noop("Encryption");
+ }
+
if (tableinfo.relkind == RELKIND_RELATION ||
tableinfo.relkind == RELKIND_VIEW ||
tableinfo.relkind == RELKIND_MATVIEW ||
@@ -1853,8 +1967,8 @@ describeOneTableDetails(const char *schemaname,
printTableAddHeader(&cont, headers[i], true, 'l');
/* Get view_def if table is a view or materialized view */
- if ((tableinfo.relkind == RELKIND_VIEW ||
- tableinfo.relkind == RELKIND_MATVIEW) && verbose)
+ if (!IS_COCKROACHDB && ((tableinfo.relkind == RELKIND_VIEW ||
+ tableinfo.relkind == RELKIND_MATVIEW) && verbose))
{
PGresult *result;
@@ -1886,6 +2000,15 @@ describeOneTableDetails(const char *schemaname,
char *identity;
char *default_str = "";
+ /* Column-Compression Type (For engines that support Column-Compression) */
+ if (IS_REDSHIFT && tableinfo.relkind == RELKIND_RELATION) {
+ printTableAddCell(&cont, PQgetvalue(res, i, 9), false, false);
+ printTableAddCell(&cont, PQgetvalue(res, i, 10), false, false);
+ printTableAddCell(&cont, PQgetvalue(res, i, 11), false, false);
+ printTableAddCell(&cont, PQgetvalue(res, i, 12), false, false);
+ printTableAddCell(&cont, PQgetvalue(res, i, 13), false, false);
+ }
+
printTableAddCell(&cont, PQgetvalue(res, i, 5), false, false);
printTableAddCell(&cont, strcmp(PQgetvalue(res, i, 3), "t") == 0 ? "not null" : "", false, false);
@@ -1914,7 +2037,7 @@ describeOneTableDetails(const char *schemaname,
/* Storage and Description */
if (verbose)
{
- int firstvcol = 9;
+ int firstvcol = 14;
char *storage = PQgetvalue(res, i, firstvcol);
/* these strings are literal in our syntax, so not translated. */
@@ -1922,7 +2045,7 @@ describeOneTableDetails(const char *schemaname,
(storage[0] == 'm' ? "main" :
(storage[0] == 'x' ? "extended" :
(storage[0] == 'e' ? "external" :
- "???")))),
+ "Not Supported Yet")))),
false, false);
/* Statistics target, if the relkind supports this feature */
@@ -2128,16 +2251,20 @@ describeOneTableDetails(const char *schemaname,
int tuples = 0;
/* print indexes */
- if (tableinfo.hasindex)
+ if ((tableinfo.hasindex) || (tableinfo.hassortkey))
{
+ if (tableinfo.hasindex) {
printfPQExpBuffer(&buf,
"SELECT c2.relname, i.indisprimary, i.indisunique, i.indisclustered, ");
if (pset.sversion >= 80200)
appendPQExpBufferStr(&buf, "i.indisvalid, ");
else
appendPQExpBufferStr(&buf, "true as indisvalid, ");
- appendPQExpBufferStr(&buf, "pg_catalog.pg_get_indexdef(i.indexrelid, 0, true),\n ");
- if (pset.sversion >= 90000)
+ if (IS_COCKROACHDB)
+ appendPQExpBufferStr(&buf, "' USING (Not Supported Yet)' AS pg_get_indexdef,\n ");
+ else
+ appendPQExpBufferStr(&buf, "pg_catalog.pg_get_indexdef(i.indexrelid, 0, true),\n ");
+ if (pset.sversion >= 90000 && !IS_COCKROACHDB)
appendPQExpBufferStr(&buf,
"pg_catalog.pg_get_constraintdef(con.oid, true), "
"contype, condeferrable, condeferred");
@@ -2150,16 +2277,64 @@ describeOneTableDetails(const char *schemaname,
else
appendPQExpBufferStr(&buf, ", false AS indisreplident");
if (pset.sversion >= 80000)
- appendPQExpBufferStr(&buf, ", c2.reltablespace");
+ appendPQExpBufferStr(&buf, ", c2.reltablespace,");
+
+ /* Redshift specific Columns */
+ appendPQExpBufferStr(&buf, "FALSE as indisinterleaved, ");
+ appendPQExpBufferStr(&buf, "FALSE as indiscompound ");
+
appendPQExpBufferStr(&buf,
"\nFROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i\n");
if (pset.sversion >= 90000)
appendPQExpBufferStr(&buf,
" LEFT JOIN pg_catalog.pg_constraint con ON (conrelid = i.indrelid AND conindid = i.indexrelid AND contype IN ('p','u','x'))\n");
+ if (IS_COCKROACHDB)
+ appendPQExpBuffer(&buf,
+ "WHERE c.oid = '%s'::OID AND c.oid = i.indrelid AND i.indexrelid = c2.oid\n", oid);
+ else
+ appendPQExpBuffer(&buf,
+ "WHERE c.oid = '%s' AND c.oid = i.indrelid AND i.indexrelid = c2.oid\n", oid);
+ }
+
+ if (tableinfo.hasindex && tableinfo.hassortkey && IS_REDSHIFT) {
+ appendPQExpBufferStr(&buf, " UNION ALL ");
+ }
+
+ if (tableinfo.hassortkey && IS_REDSHIFT) {
+
+ appendPQExpBufferStr(&buf,
+ " SELECT "
+ " NULL AS relname, FALSE AS indisprimary, FALSE AS indisunique, FALSE AS indisclustered, TRUE AS indisvalid, "
+ " (WITH x AS "
+ " ( SELECT row_number() OVER () AS r, trim(attname) AS nm "
+ " FROM pg_attribute ");
appendPQExpBuffer(&buf,
- "WHERE c.oid = '%s' AND c.oid = i.indrelid AND i.indexrelid = c2.oid\n"
- "ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname;",
- oid);
+ " WHERE attrelid = '%s' AND attsortkeyord <> 0 ORDER BY ABS(attsortkeyord)) ", oid);
+ appendPQExpBufferStr(&buf,
+ " SELECT "
+ "'(' || MAX(CASE WHEN r = 1 THEN nm ELSE '' END) || "
+ " MAX(CASE WHEN r = 2 THEN (',' || nm) ELSE '' END) || "
+ " MAX(CASE WHEN r = 3 THEN (',' || nm) ELSE '' END) || "
+ " MAX(CASE WHEN r = 4 THEN (',' || nm) ELSE '' END) || "
+ " MAX(CASE WHEN r = 5 THEN (',' || nm) ELSE '' END) || "
+ " MAX(CASE WHEN r = 6 THEN (',' || nm) ELSE '' END) || "
+ " MAX(CASE WHEN r = 7 THEN (',' || nm) ELSE '' END) || "
+ " MAX(CASE WHEN r = 8 THEN (',' || nm) ELSE '' END) || "
+ " MAX(CASE WHEN r = 9 THEN (',' || nm) ELSE '' END) || "
+ " MAX(CASE WHEN r =10 THEN (',' || nm) ELSE '' END) || ')' AS t "
+ " FROM x), "
+ " NULL AS constraintdef, NULL AS contype, FALSE AS condeferrable, FALSE AS condeferred, "
+ " FALSE AS indisreplident, NULL AS reltablespace, ");
+ appendPQExpBuffer(&buf,
+ " ((SELECT MIN(attsortkeyord) FROM pg_attribute WHERE attrelid = '%s') < 0)::BOOLEAN AS indisinterleaved, ", oid);
+ appendPQExpBuffer(&buf,
+ " ((SELECT MIN(attsortkeyord) FROM pg_attribute WHERE attrelid = '%s' AND attsortkeyord > 0) > 0)::BOOLEAN AS indiscompound ", oid);
+
+ appendPQExpBuffer(&buf,
+ " FROM (SELECT '%s' AS oid) c ", oid);
+ }
+
+ appendPQExpBufferStr(&buf, "ORDER BY indisprimary DESC, indisunique DESC, relname;");
result = PSQLexec(buf.data);
if (!result)
goto error_return;
@@ -2172,8 +2347,11 @@ describeOneTableDetails(const char *schemaname,
for (i = 0; i < tuples; i++)
{
/* untranslated index name */
- printfPQExpBuffer(&buf, " \"%s\"",
- PQgetvalue(result, i, 0));
+ if (!IS_REDSHIFT)
+ printfPQExpBuffer(&buf, " \"%s\"",
+ PQgetvalue(result, i, 0));
+ else
+ resetPQExpBuffer(&buf);
/* If exclusion constraint, print the constraintdef */
if (strcmp(PQgetvalue(result, i, 7), "x") == 0)
@@ -2187,7 +2365,7 @@ describeOneTableDetails(const char *schemaname,
const char *usingpos;
/* Label as primary key or unique (but not both) */
- if (strcmp(PQgetvalue(result, i, 1), "t") == 0)
+ if (strcmp(PQgetvalue(result, i, 1), "t") == 0)
appendPQExpBufferStr(&buf, " PRIMARY KEY,");
else if (strcmp(PQgetvalue(result, i, 2), "t") == 0)
{
@@ -2196,6 +2374,19 @@ describeOneTableDetails(const char *schemaname,
else
appendPQExpBufferStr(&buf, " UNIQUE,");
}
+ else if (IS_REDSHIFT)
+ {
+ if (strcmp(PQgetvalue(result, i, 12), "t") == 0)
+ appendPQExpBufferStr(&buf, " INTERLEAVED SORTKEY");
+ else if (strcmp(PQgetvalue(result, i, 13), "t") == 0)
+ appendPQExpBufferStr(&buf, " COMPOUND SORTKEY");
+ else
+ {
+ //psql_error("\nUnable to ascertain Redshift SORTKEY type (%d)\n", *PQgetvalue(result, i, 12));
+ psql_error("\nUnable to ascertain Redshift SORTKEY type\n");
+ goto error_return;
+ }
+ }
/* Everything after "USING" is echoed verbatim */
indexdef = PQgetvalue(result, i, 5);
@@ -2329,7 +2520,7 @@ describeOneTableDetails(const char *schemaname,
}
/* print any row-level policies */
- if (pset.sversion >= 90500)
+ if (pset.sversion >= 90500 && !IS_COCKROACHDB)
{
printfPQExpBuffer(&buf, "SELECT pol.polname,");
if (pset.sversion >= 100000)
@@ -2609,8 +2800,13 @@ describeOneTableDetails(const char *schemaname,
PGresult *result = NULL;
/* Footer information about a view */
- printTableAddFooter(&cont, _("View definition:"));
- printTableAddFooter(&cont, view_def);
+ if (IS_COCKROACHDB)
+ printTableAddFooter(&cont, _("View definition: Not Supported Yet"));
+ else
+ {
+ printTableAddFooter(&cont, _("View definition:"));
+ printTableAddFooter(&cont, view_def);
+ }
/* print rules */
if (tableinfo.hasrules)
@@ -2833,6 +3029,8 @@ describeOneTableDetails(const char *schemaname,
}
/* print inherited tables (exclude, if parent is a partitioned table) */
+ if (!IS_COCKROACHDB)
+ {
printfPQExpBuffer(&buf,
"SELECT c.oid::pg_catalog.regclass"
" FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i"
@@ -2866,9 +3064,16 @@ describeOneTableDetails(const char *schemaname,
PQclear(result);
}
+ }
/* print child tables (with additional info if partitions) */
- if (pset.sversion >= 100000)
+ if (IS_COCKROACHDB)
+ printfPQExpBuffer(&buf,
+ "SELECT c.oid::regclass, 'Not Supported Yet' AS relpartbound"
+ " FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i"
+ " WHERE c.oid=i.inhrelid AND i.inhparent = '%s'::OID"
+ " ORDER BY c.oid::regclass::text;", oid);
+ else if (pset.sversion >= 100000)
printfPQExpBuffer(&buf,
"SELECT c.oid::pg_catalog.regclass, pg_catalog.pg_get_expr(c.relpartbound, c.oid)"
" FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i"
@@ -2965,7 +3170,7 @@ describeOneTableDetails(const char *schemaname,
s,
tableinfo.relreplident == 'f' ? "FULL" :
tableinfo.relreplident == 'n' ? "NOTHING" :
- "???");
+ "Not Supported Yet");
printTableAddFooter(&cont, buf.data);
}
@@ -3101,25 +3306,28 @@ describeRoles(const char *pattern, bool verbose, bool showSystem)
if (pset.sversion >= 80100)
{
printfPQExpBuffer(&buf,
- "SELECT r.rolname, r.rolsuper, r.rolinherit,\n"
- " r.rolcreaterole, r.rolcreatedb, r.rolcanlogin,\n"
- " r.rolconnlimit, r.rolvaliduntil,\n"
- " ARRAY(SELECT b.rolname\n"
- " FROM pg_catalog.pg_auth_members m\n"
- " JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid)\n"
- " WHERE m.member = r.oid) as memberof");
+ "SELECT r.rolname, r.rolsuper, r.rolinherit,\n"
+ " r.rolcreaterole, r.rolcreatedb, r.rolcanlogin,\n"
+ " r.rolconnlimit, r.rolvaliduntil\n");
+ if (IS_COCKROACHDB)
+ appendPQExpBufferStr(&buf, " ,'NA' as memberof \n");
+ else
+ appendPQExpBufferStr(&buf, " ,ARRAY(SELECT b.rolname\n"
+ " FROM pg_catalog.pg_auth_members m\n"
+ " JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid)\n"
+ " WHERE m.member = r.oid) as memberof");
if (verbose && pset.sversion >= 80200)
{
appendPQExpBufferStr(&buf, "\n, pg_catalog.shobj_description(r.oid, 'pg_authid') AS description");
ncols++;
}
- if (pset.sversion >= 90100)
+ if (pset.sversion >= 90100 && !IS_COCKROACHDB)
{
appendPQExpBufferStr(&buf, "\n, r.rolreplication");
}
- if (pset.sversion >= 90500)
+ if (pset.sversion >= 90500 && !IS_COCKROACHDB)
{
appendPQExpBufferStr(&buf, "\n, r.rolbypassrls");
}
@@ -3186,11 +3394,11 @@ describeRoles(const char *pattern, bool verbose, bool showSystem)
if (strcmp(PQgetvalue(res, i, 5), "t") != 0)
add_role_attribute(&buf, _("Cannot login"));
- if (pset.sversion >= 90100)
+ if (pset.sversion >= 90100 && !IS_COCKROACHDB)
if (strcmp(PQgetvalue(res, i, (verbose ? 10 : 9)), "t") == 0)
add_role_attribute(&buf, _("Replication"));
- if (pset.sversion >= 90500)
+ if (pset.sversion >= 90500 && !IS_COCKROACHDB)
if (strcmp(PQgetvalue(res, i, (verbose ? 11 : 10)), "t") == 0)
add_role_attribute(&buf, _("Bypass RLS"));
@@ -3398,7 +3606,11 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys
* As of PostgreSQL 9.0, use pg_table_size() to show a more accurate
* size of a table, including FSM, VM and TOAST tables.
*/
- if (pset.sversion >= 90000)
+ if (IS_COCKROACHDB)
+ appendPQExpBuffer(&buf,
+ ",\n 'Not Supported Yet' as \"%s\"",
+ gettext_noop("Size"));
+ else if (pset.sversion >= 90000)
appendPQExpBuffer(&buf,
",\n pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid)) as \"%s\"",
gettext_noop("Size"));
@@ -3455,7 +3667,7 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys
processSQLNamePattern(pset.db, &buf, pattern, true, false,
"n.nspname", "c.relname", NULL,
- "pg_catalog.pg_table_is_visible(c.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_table_is_visible(c.oid)":NULL));
appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
@@ -3635,7 +3847,7 @@ listDomains(const char *pattern, bool verbose, bool showSystem)
processSQLNamePattern(pset.db, &buf, pattern, true, false,
"n.nspname", "t.typname", NULL,
- "pg_catalog.pg_type_is_visible(t.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_type_is_visible(t.oid)":NULL));
appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
@@ -3709,7 +3921,7 @@ listConversions(const char *pattern, bool verbose, bool showSystem)
processSQLNamePattern(pset.db, &buf, pattern, true, false,
"n.nspname", "c.conname", NULL,
- "pg_catalog.pg_conversion_is_visible(c.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_conversion_is_visible(c.oid)":NULL));
appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
@@ -3867,14 +4079,14 @@ listCasts(const char *pattern, bool verbose)
processSQLNamePattern(pset.db, &buf, pattern, true, false,
"ns.nspname", "ts.typname",
"pg_catalog.format_type(ts.oid, NULL)",
- "pg_catalog.pg_type_is_visible(ts.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_type_is_visible(ts.oid)":NULL));
appendPQExpBufferStr(&buf, ") OR (true");
processSQLNamePattern(pset.db, &buf, pattern, true, false,
"nt.nspname", "tt.typname",
"pg_catalog.format_type(tt.oid, NULL)",
- "pg_catalog.pg_type_is_visible(tt.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_type_is_visible(tt.oid)":NULL));
appendPQExpBufferStr(&buf, ") )\nORDER BY 1, 2;");
@@ -3958,7 +4170,7 @@ listCollations(const char *pattern, bool verbose, bool showSystem)
processSQLNamePattern(pset.db, &buf, pattern, true, false,
"n.nspname", "c.collname", NULL,
- "pg_catalog.pg_collation_is_visible(c.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_collation_is_visible(c.oid)":NULL));
appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
@@ -4077,7 +4289,7 @@ listTSParsers(const char *pattern, bool verbose)
processSQLNamePattern(pset.db, &buf, pattern, false, false,
"n.nspname", "p.prsname", NULL,
- "pg_catalog.pg_ts_parser_is_visible(p.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_ts_parser_is_visible(p.oid)":NULL));
appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
@@ -4118,7 +4330,7 @@ listTSParsersVerbose(const char *pattern)
processSQLNamePattern(pset.db, &buf, pattern, false, false,
"n.nspname", "p.prsname", NULL,
- "pg_catalog.pg_ts_parser_is_visible(p.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_ts_parser_is_visible(p.oid)":NULL));
appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
@@ -4335,7 +4547,7 @@ listTSDictionaries(const char *pattern, bool verbose)
processSQLNamePattern(pset.db, &buf, pattern, false, false,
"n.nspname", "d.dictname", NULL,
- "pg_catalog.pg_ts_dict_is_visible(d.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_ts_dict_is_visible(d.oid)":NULL));
appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
@@ -4406,7 +4618,7 @@ listTSTemplates(const char *pattern, bool verbose)
processSQLNamePattern(pset.db, &buf, pattern, false, false,
"n.nspname", "t.tmplname", NULL,
- "pg_catalog.pg_ts_template_is_visible(t.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_ts_template_is_visible(t.oid)":NULL));
appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
@@ -4466,7 +4678,7 @@ listTSConfigs(const char *pattern, bool verbose)
processSQLNamePattern(pset.db, &buf, pattern, false, false,
"n.nspname", "c.cfgname", NULL,
- "pg_catalog.pg_ts_config_is_visible(c.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_ts_config_is_visible(c.oid)":NULL));
appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
@@ -4508,7 +4720,7 @@ listTSConfigsVerbose(const char *pattern)
processSQLNamePattern(pset.db, &buf, pattern, true, false,
"n.nspname", "c.cfgname", NULL,
- "pg_catalog.pg_ts_config_is_visible(c.oid)");
+ (!IS_COCKROACHDB?"pg_catalog.pg_ts_config_is_visible(c.oid)":NULL));
appendPQExpBufferStr(&buf, "ORDER BY 3, 2;");
@@ -4731,53 +4943,53 @@ listForeignServers(const char *pattern, bool verbose)
char sverbuf[32];
psql_error("The server (version %s) does not support foreign servers.\n",
- formatPGVersionNumber(pset.sversion, false,
- sverbuf, sizeof(sverbuf)));
+ formatPGVersionNumber(pset.sversion, false,
+ sverbuf, sizeof(sverbuf)));
return true;
}
initPQExpBuffer(&buf);
printfPQExpBuffer(&buf,
- "SELECT s.srvname AS \"%s\",\n"
- " pg_catalog.pg_get_userbyid(s.srvowner) AS \"%s\",\n"
- " f.fdwname AS \"%s\"",
- gettext_noop("Name"),
- gettext_noop("Owner"),
- gettext_noop("Foreign-data wrapper"));
+ "SELECT s.srvname AS \"%s\",\n"
+ " pg_catalog.pg_get_userbyid(s.srvowner) AS \"%s\",\n"
+ " f.fdwname AS \"%s\"",
+ gettext_noop("Name"),
+ gettext_noop("Owner"),
+ gettext_noop("Foreign-data wrapper"));
if (verbose)
{
appendPQExpBufferStr(&buf, ",\n ");
printACLColumn(&buf, "s.srvacl");
appendPQExpBuffer(&buf,
- ",\n"
- " s.srvtype AS \"%s\",\n"
- " s.srvversion AS \"%s\",\n"
- " CASE WHEN srvoptions IS NULL THEN '' ELSE "
- " '(' || pg_catalog.array_to_string(ARRAY(SELECT "
- " pg_catalog.quote_ident(option_name) || ' ' || "
- " pg_catalog.quote_literal(option_value) FROM "
- " pg_catalog.pg_options_to_table(srvoptions)), ', ') || ')' "
- " END AS \"%s\",\n"
- " d.description AS \"%s\"",
- gettext_noop("Type"),
- gettext_noop("Version"),
- gettext_noop("FDW options"),
- gettext_noop("Description"));
+ ",\n"
+ " s.srvtype AS \"%s\",\n"
+ " s.srvversion AS \"%s\",\n"
+ " CASE WHEN srvoptions IS NULL THEN '' ELSE "
+ " '(' || pg_catalog.array_to_string(ARRAY(SELECT "
+ " pg_catalog.quote_ident(option_name) || ' ' || "
+ " pg_catalog.quote_literal(option_value) FROM "
+ " pg_catalog.pg_options_to_table(srvoptions)), ', ') || ')' "
+ " END AS \"%s\",\n"
+ " d.description AS \"%s\"",
+ gettext_noop("Type"),
+ gettext_noop("Version"),
+ gettext_noop("FDW options"),
+ gettext_noop("Description"));
}
appendPQExpBufferStr(&buf,
- "\nFROM pg_catalog.pg_foreign_server s\n"
- " JOIN pg_catalog.pg_foreign_data_wrapper f ON f.oid=s.srvfdw\n");
+ "\nFROM pg_catalog.pg_foreign_server s\n"
+ " JOIN pg_catalog.pg_foreign_data_wrapper f ON f.oid=s.srvfdw\n");
if (verbose)
appendPQExpBufferStr(&buf,
- "LEFT JOIN pg_catalog.pg_description d\n "
- "ON d.classoid = s.tableoid AND d.objoid = s.oid "
- "AND d.objsubid = 0\n");
+ "LEFT JOIN pg_catalog.pg_description d\n "
+ "ON d.classoid = s.tableoid AND d.objoid = s.oid "
+ "AND d.objsubid = 0\n");
processSQLNamePattern(pset.db, &buf, pattern, false, false,
- NULL, "s.srvname", NULL, NULL);
+ NULL, "s.srvname", NULL, NULL);
appendPQExpBufferStr(&buf, "ORDER BY 1;");
@@ -4796,6 +5008,50 @@ listForeignServers(const char *pattern, bool verbose)
return true;
}
+/*
+ * \des
+ *
+ * Describes external schemas (in Redshift).
+ */
+ bool
+ listExternalSchemasInRedshift(const char *pattern, bool verbose)
+ {
+ PQExpBufferData buf;
+ PGresult *res;
+ printQueryOpt myopt = pset.popt;
+
+ initPQExpBuffer(&buf);
+ printfPQExpBuffer(&buf,
+ "SELECT trim(schemaname) AS \"%s\",\n"
+ " trim(pg_catalog.pg_get_userbyid(esowner)) AS \"%s\",\n"
+ " trim(databasename) AS \"%s\"\n",
+ gettext_noop("Schema"),
+ gettext_noop("Owner"),
+ gettext_noop("External Database"));
+
+ appendPQExpBufferStr(&buf,
+ "\nFROM SVV_EXTERNAL_SCHEMAS\n");
+
+ processSQLNamePattern(pset.db, &buf, pattern, false, false,
+ NULL, NULL, "tablename", NULL);
+
+ appendPQExpBufferStr(&buf, "ORDER BY 2;");
+
+ res = PSQLexec(buf.data);
+ termPQExpBuffer(&buf);
+ if (!res)
+ return false;
+
+ myopt.nullPrint = NULL;
+ myopt.title = _("List of external schemas");
+ myopt.translate_header = true;
+
+ printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
+
+ PQclear(res);
+ return true;
+ }
+
/*
* \deu
*
@@ -4862,78 +5118,127 @@ listUserMappings(const char *pattern, bool verbose)
*
* Describes foreign tables.
*/
-bool
-listForeignTables(const char *pattern, bool verbose)
-{
- PQExpBufferData buf;
- PGresult *res;
- printQueryOpt myopt = pset.popt;
-
- if (pset.sversion < 90100)
- {
- char sverbuf[32];
-
- psql_error("The server (version %s) does not support foreign tables.\n",
- formatPGVersionNumber(pset.sversion, false,
- sverbuf, sizeof(sverbuf)));
- return true;
- }
-
- initPQExpBuffer(&buf);
- printfPQExpBuffer(&buf,
- "SELECT n.nspname AS \"%s\",\n"
- " c.relname AS \"%s\",\n"
- " s.srvname AS \"%s\"",
- gettext_noop("Schema"),
- gettext_noop("Table"),
- gettext_noop("Server"));
-
- if (verbose)
- appendPQExpBuffer(&buf,
- ",\n CASE WHEN ftoptions IS NULL THEN '' ELSE "
- " '(' || pg_catalog.array_to_string(ARRAY(SELECT "
- " pg_catalog.quote_ident(option_name) || ' ' || "
- " pg_catalog.quote_literal(option_value) FROM "
- " pg_catalog.pg_options_to_table(ftoptions)), ', ') || ')' "
- " END AS \"%s\",\n"
- " d.description AS \"%s\"",
- gettext_noop("FDW options"),
- gettext_noop("Description"));
-
- appendPQExpBufferStr(&buf,
- "\nFROM pg_catalog.pg_foreign_table ft\n"
- " INNER JOIN pg_catalog.pg_class c"
- " ON c.oid = ft.ftrelid\n"
- " INNER JOIN pg_catalog.pg_namespace n"
- " ON n.oid = c.relnamespace\n"
- " INNER JOIN pg_catalog.pg_foreign_server s"
- " ON s.oid = ft.ftserver\n");
- if (verbose)
- appendPQExpBufferStr(&buf,
- " LEFT JOIN pg_catalog.pg_description d\n"
- " ON d.classoid = c.tableoid AND "
- "d.objoid = c.oid AND d.objsubid = 0\n");
-
- processSQLNamePattern(pset.db, &buf, pattern, false, false,
- "n.nspname", "c.relname", NULL,
- "pg_catalog.pg_table_is_visible(c.oid)");
-
- appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
-
- res = PSQLexec(buf.data);
- termPQExpBuffer(&buf);
- if (!res)
- return false;
-
- myopt.nullPrint = NULL;
- myopt.title = _("List of foreign tables");
- myopt.translate_header = true;
-
- printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
-
- PQclear(res);
- return true;
-}
+ bool
+ listForeignTables(const char *pattern, bool verbose)
+ {
+ PQExpBufferData buf;
+ PGresult *res;
+ printQueryOpt myopt = pset.popt;
+
+ if (pset.sversion < 90100)
+ {
+ char sverbuf[32];
+
+ psql_error("The server (version %s) does not support foreign tables.\n",
+ formatPGVersionNumber(pset.sversion, false,
+ sverbuf, sizeof(sverbuf)));
+ return true;
+ }
+
+ initPQExpBuffer(&buf);
+ printfPQExpBuffer(&buf,
+ "SELECT n.nspname AS \"%s\",\n"
+ " c.relname AS \"%s\",\n"
+ " s.srvname AS \"%s\"",
+ gettext_noop("Schema"),
+ gettext_noop("Table"),
+ gettext_noop("Server"));
+
+ if (verbose)
+ appendPQExpBuffer(&buf,
+ ",\n CASE WHEN ftoptions IS NULL THEN '' ELSE "
+ " '(' || pg_catalog.array_to_string(ARRAY(SELECT "
+ " pg_catalog.quote_ident(option_name) || ' ' || "
+ " pg_catalog.quote_literal(option_value) FROM "
+ " pg_catalog.pg_options_to_table(ftoptions)), ', ') || ')' "
+ " END AS \"%s\",\n"
+ " d.description AS \"%s\"",
+ gettext_noop("FDW options"),
+ gettext_noop("Description"));
+
+ appendPQExpBufferStr(&buf,
+ "\nFROM pg_catalog.pg_foreign_table ft\n"
+ " INNER JOIN pg_catalog.pg_class c"
+ " ON c.oid = ft.ftrelid\n"
+ " INNER JOIN pg_catalog.pg_namespace n"
+ " ON n.oid = c.relnamespace\n"
+ " INNER JOIN pg_catalog.pg_foreign_server s"
+ " ON s.oid = ft.ftserver\n");
+ if (verbose)
+ appendPQExpBufferStr(&buf,
+ " LEFT JOIN pg_catalog.pg_description d\n"
+ " ON d.classoid = c.tableoid AND "
+ "d.objoid = c.oid AND d.objsubid = 0\n");
+
+ processSQLNamePattern(pset.db, &buf, pattern, false, false,
+ "n.nspname", "c.relname", NULL,
+ (!IS_COCKROACHDB?"pg_catalog.pg_table_is_visible(c.oid)":NULL));
+
+ appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
+
+ res = PSQLexec(buf.data);
+ termPQExpBuffer(&buf);
+ if (!res)
+ return false;
+
+ myopt.nullPrint = NULL;
+ myopt.title = _("List of foreign tables");
+ myopt.translate_header = true;
+
+ printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
+
+ PQclear(res);
+ return true;
+ }
+
+/*
+ * \det
+ *
+ * Describes external tables (in Redshift).
+ */
+ bool
+ listExternalTablesInRedshift(const char *pattern, bool verbose)
+ {
+ PQExpBufferData buf;
+ PGresult *res;
+ printQueryOpt myopt = pset.popt;
+
+ initPQExpBuffer(&buf);
+ printfPQExpBuffer(&buf,
+ "SELECT trim(et.schemaname) AS \"%s\",\n"
+ " trim(et.tablename) AS \"%s\",\n"
+ " '%s' AS \"%s\","
+ " (SELECT trim(usename) FROM pg_user where usesysid = es.esowner) AS \"%s\"",
+ gettext_noop("Schema"),
+ gettext_noop("Table"),
+ gettext_noop("External Table"),
+ gettext_noop("Type"),
+ gettext_noop("Owner"));
+
+ appendPQExpBufferStr(&buf,
+ "\nFROM SVV_EXTERNAL_TABLES et\n"
+ " JOIN SVV_EXTERNAL_SCHEMAS es\n"
+ " ON es.schemaname = et.schemaname\n");
+
+ processSQLNamePattern(pset.db, &buf, pattern, false, false,
+ "schemaname", "tablename", NULL, NULL);
+
+ appendPQExpBufferStr(&buf, " ORDER BY 1, 2;");
+
+ res = PSQLexec(buf.data);
+ termPQExpBuffer(&buf);
+ if (!res)
+ return false;
+
+ myopt.nullPrint = NULL;
+ myopt.title = _("List of external tables");
+ myopt.translate_header = true;
+
+ printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
+
+ PQclear(res);
+ return true;
+ }
/*
* \dx
@@ -4964,11 +5269,12 @@ listExtensions(const char *pattern)
"FROM pg_catalog.pg_extension e "
"LEFT JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace "
"LEFT JOIN pg_catalog.pg_description c ON c.objoid = e.oid "
- "AND c.classoid = 'pg_catalog.pg_extension'::pg_catalog.regclass\n",
+ "AND c.classoid = 'pg_catalog.pg_extension'::%s\n",
gettext_noop("Name"),
gettext_noop("Version"),
gettext_noop("Schema"),
- gettext_noop("Description"));
+ gettext_noop("Description"),
+ gettext_noop((IS_COCKROACHDB?"regclass":"pg_catalog.regclass")));
processSQLNamePattern(pset.db, &buf, pattern,
false, false,
@@ -5398,10 +5704,13 @@ describeSubscriptions(const char *pattern, bool verbose)
static void
printACLColumn(PQExpBuffer buf, const char *colname)
{
- if (pset.sversion >= 80100)
+ if (IS_COCKROACHDB)
appendPQExpBuffer(buf,
- "pg_catalog.array_to_string(%s, E'\\n') AS \"%s\"",
- colname, gettext_noop("Access privileges"));
+ "'Not Supported Yet' AS \"%s\"", gettext_noop("Access privileges"));
+ else if (pset.sversion >= 80100)
+ appendPQExpBuffer(buf,
+ "pg_catalog.array_to_string(%s, E'\\n') AS \"%s\"",
+ colname, gettext_noop("Access privileges"));
else
appendPQExpBuffer(buf,
"pg_catalog.array_to_string(%s, '\\n') AS \"%s\"",
diff --git a/src/bin/psql/describe.h b/src/bin/psql/describe.h
index 14a5667f3e2c3..6339bc76ca304 100644
--- a/src/bin/psql/describe.h
+++ b/src/bin/psql/describe.h
@@ -84,12 +84,18 @@ extern bool listForeignDataWrappers(const char *pattern, bool verbose);
/* \des */
extern bool listForeignServers(const char *pattern, bool verbose);
+/* \des in Redshift*/
+extern bool listExternalSchemasInRedshift(const char *pattern, bool verbose);
+
/* \deu */
extern bool listUserMappings(const char *pattern, bool verbose);
/* \det */
extern bool listForeignTables(const char *pattern, bool verbose);
+/* \det in Redshift*/
+extern bool listExternalTablesInRedshift(const char *pattern, bool verbose);
+
/* \dL */
extern bool listLanguages(const char *pattern, bool verbose, bool showSystem);
diff --git a/src/bin/psql/help.c b/src/bin/psql/help.c
index a926c40b9b88b..ee6d06fcdd072 100644
--- a/src/bin/psql/help.c
+++ b/src/bin/psql/help.c
@@ -128,6 +128,7 @@ usage(unsigned short int pager)
env = getenv("PGHOST");
fprintf(output, _(" -h, --host=HOSTNAME database server host or socket directory (default: \"%s\")\n"),
env ? env : _("local socket"));
+ fprintf(output, _(" -I, --aws-iam-redshift use temporary database credentials from AWS IAM Service\n"));
/* Display default port */
env = getenv("PGPORT");
fprintf(output, _(" -p, --port=PORT database server port (default: \"%s\")\n"),
diff --git a/src/bin/psql/input.c b/src/bin/psql/input.c
index 62f5f7738391e..5fd6d3d599076 100644
--- a/src/bin/psql/input.c
+++ b/src/bin/psql/input.c
@@ -16,6 +16,9 @@
#include "input.h"
#include "settings.h"
#include "tab-complete.h"
+#include "tab-complete-redshift.h"
+#include "tab-complete-pipelinedb.h"
+#include "tab-complete-cockroachdb.h"
#include "common.h"
#ifndef WIN32
@@ -34,7 +37,6 @@ static char *psql_history;
static int history_lines_added;
-
/*
* Preserve newlines in saved queries by mapping '\n' to NL_IN_HISTORY
*
@@ -354,7 +356,15 @@ initializeInput(int flags)
useReadline = true;
/* these two things must be done in this order: */
- initialize_readline();
+
+ if (strncmp(pset.sengine, "redshift", 8) == 0)
+ initialize_readline_redshift();
+ else if (strncmp(pset.sengine, "pipelinedb", 10) == 0)
+ initialize_readline_pipelinedb();
+ else if (strncmp(pset.sengine, "cockroachdb", 11) == 0)
+ initialize_readline_cockroachdb();
+ else
+ initialize_readline();
rl_initialize();
useHistory = true;
diff --git a/src/bin/psql/jsmn.c b/src/bin/psql/jsmn.c
new file mode 100755
index 0000000000000..bcd6392a069ca
--- /dev/null
+++ b/src/bin/psql/jsmn.c
@@ -0,0 +1,314 @@
+#include "jsmn.h"
+
+/**
+ * Allocates a fresh unused token from the token pull.
+ */
+static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser,
+ jsmntok_t *tokens, size_t num_tokens) {
+ jsmntok_t *tok;
+ if (parser->toknext >= num_tokens) {
+ return NULL;
+ }
+ tok = &tokens[parser->toknext++];
+ tok->start = tok->end = -1;
+ tok->size = 0;
+#ifdef JSMN_PARENT_LINKS
+ tok->parent = -1;
+#endif
+ return tok;
+}
+
+/**
+ * Fills token type and boundaries.
+ */
+static void jsmn_fill_token(jsmntok_t *token, jsmntype_t type,
+ int start, int end) {
+ token->type = type;
+ token->start = start;
+ token->end = end;
+ token->size = 0;
+}
+
+/**
+ * Fills next available token with JSON primitive.
+ */
+static int jsmn_parse_primitive(jsmn_parser *parser, const char *js,
+ size_t len, jsmntok_t *tokens, size_t num_tokens) {
+ jsmntok_t *token;
+ int start;
+
+ start = parser->pos;
+
+ for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
+ switch (js[parser->pos]) {
+#ifndef JSMN_STRICT
+ /* In strict mode primitive must be followed by "," or "}" or "]" */
+ case ':':
+#endif
+ case '\t' : case '\r' : case '\n' : case ' ' :
+ case ',' : case ']' : case '}' :
+ goto found;
+ }
+ if (js[parser->pos] < 32 || js[parser->pos] >= 127) {
+ parser->pos = start;
+ return JSMN_ERROR_INVAL;
+ }
+ }
+#ifdef JSMN_STRICT
+ /* In strict mode primitive must be followed by a comma/object/array */
+ parser->pos = start;
+ return JSMN_ERROR_PART;
+#endif
+
+found:
+ if (tokens == NULL) {
+ parser->pos--;
+ return 0;
+ }
+ token = jsmn_alloc_token(parser, tokens, num_tokens);
+ if (token == NULL) {
+ parser->pos = start;
+ return JSMN_ERROR_NOMEM;
+ }
+ jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos);
+#ifdef JSMN_PARENT_LINKS
+ token->parent = parser->toksuper;
+#endif
+ parser->pos--;
+ return 0;
+}
+
+/**
+ * Fills next token with JSON string.
+ */
+static int jsmn_parse_string(jsmn_parser *parser, const char *js,
+ size_t len, jsmntok_t *tokens, size_t num_tokens) {
+ jsmntok_t *token;
+
+ int start = parser->pos;
+
+ parser->pos++;
+
+ /* Skip starting quote */
+ for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
+ char c = js[parser->pos];
+
+ /* Quote: end of string */
+ if (c == '\"') {
+ if (tokens == NULL) {
+ return 0;
+ }
+ token = jsmn_alloc_token(parser, tokens, num_tokens);
+ if (token == NULL) {
+ parser->pos = start;
+ return JSMN_ERROR_NOMEM;
+ }
+ jsmn_fill_token(token, JSMN_STRING, start+1, parser->pos);
+#ifdef JSMN_PARENT_LINKS
+ token->parent = parser->toksuper;
+#endif
+ return 0;
+ }
+
+ /* Backslash: Quoted symbol expected */
+ if (c == '\\' && parser->pos + 1 < len) {
+ int i;
+ parser->pos++;
+ switch (js[parser->pos]) {
+ /* Allowed escaped symbols */
+ case '\"': case '/' : case '\\' : case 'b' :
+ case 'f' : case 'r' : case 'n' : case 't' :
+ break;
+ /* Allows escaped symbol \uXXXX */
+ case 'u':
+ parser->pos++;
+ for(i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0'; i++) {
+ /* If it isn't a hex character we have an error */
+ if(!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */
+ (js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */
+ (js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */
+ parser->pos = start;
+ return JSMN_ERROR_INVAL;
+ }
+ parser->pos++;
+ }
+ parser->pos--;
+ break;
+ /* Unexpected symbol */
+ default:
+ parser->pos = start;
+ return JSMN_ERROR_INVAL;
+ }
+ }
+ }
+ parser->pos = start;
+ return JSMN_ERROR_PART;
+}
+
+/**
+ * Parse JSON string and fill tokens.
+ */
+int jsmn_parse(jsmn_parser *parser, const char *js, size_t len,
+ jsmntok_t *tokens, unsigned int num_tokens) {
+ int r;
+ int i;
+ jsmntok_t *token;
+ int count = parser->toknext;
+
+ for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
+ char c;
+ jsmntype_t type;
+
+ c = js[parser->pos];
+ switch (c) {
+ case '{': case '[':
+ count++;
+ if (tokens == NULL) {
+ break;
+ }
+ token = jsmn_alloc_token(parser, tokens, num_tokens);
+ if (token == NULL)
+ return JSMN_ERROR_NOMEM;
+ if (parser->toksuper != -1) {
+ tokens[parser->toksuper].size++;
+#ifdef JSMN_PARENT_LINKS
+ token->parent = parser->toksuper;
+#endif
+ }
+ token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY);
+ token->start = parser->pos;
+ parser->toksuper = parser->toknext - 1;
+ break;
+ case '}': case ']':
+ if (tokens == NULL)
+ break;
+ type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY);
+#ifdef JSMN_PARENT_LINKS
+ if (parser->toknext < 1) {
+ return JSMN_ERROR_INVAL;
+ }
+ token = &tokens[parser->toknext - 1];
+ for (;;) {
+ if (token->start != -1 && token->end == -1) {
+ if (token->type != type) {
+ return JSMN_ERROR_INVAL;
+ }
+ token->end = parser->pos + 1;
+ parser->toksuper = token->parent;
+ break;
+ }
+ if (token->parent == -1) {
+ if(token->type != type || parser->toksuper == -1) {
+ return JSMN_ERROR_INVAL;
+ }
+ break;
+ }
+ token = &tokens[token->parent];
+ }
+#else
+ for (i = parser->toknext - 1; i >= 0; i--) {
+ token = &tokens[i];
+ if (token->start != -1 && token->end == -1) {
+ if (token->type != type) {
+ return JSMN_ERROR_INVAL;
+ }
+ parser->toksuper = -1;
+ token->end = parser->pos + 1;
+ break;
+ }
+ }
+ /* Error if unmatched closing bracket */
+ if (i == -1) return JSMN_ERROR_INVAL;
+ for (; i >= 0; i--) {
+ token = &tokens[i];
+ if (token->start != -1 && token->end == -1) {
+ parser->toksuper = i;
+ break;
+ }
+ }
+#endif
+ break;
+ case '\"':
+ r = jsmn_parse_string(parser, js, len, tokens, num_tokens);
+ if (r < 0) return r;
+ count++;
+ if (parser->toksuper != -1 && tokens != NULL)
+ tokens[parser->toksuper].size++;
+ break;
+ case '\t' : case '\r' : case '\n' : case ' ':
+ break;
+ case ':':
+ parser->toksuper = parser->toknext - 1;
+ break;
+ case ',':
+ if (tokens != NULL && parser->toksuper != -1 &&
+ tokens[parser->toksuper].type != JSMN_ARRAY &&
+ tokens[parser->toksuper].type != JSMN_OBJECT) {
+#ifdef JSMN_PARENT_LINKS
+ parser->toksuper = tokens[parser->toksuper].parent;
+#else
+ for (i = parser->toknext - 1; i >= 0; i--) {
+ if (tokens[i].type == JSMN_ARRAY || tokens[i].type == JSMN_OBJECT) {
+ if (tokens[i].start != -1 && tokens[i].end == -1) {
+ parser->toksuper = i;
+ break;
+ }
+ }
+ }
+#endif
+ }
+ break;
+#ifdef JSMN_STRICT
+ /* In strict mode primitives are: numbers and booleans */
+ case '-': case '0': case '1' : case '2': case '3' : case '4':
+ case '5': case '6': case '7' : case '8': case '9':
+ case 't': case 'f': case 'n' :
+ /* And they must not be keys of the object */
+ if (tokens != NULL && parser->toksuper != -1) {
+ jsmntok_t *t = &tokens[parser->toksuper];
+ if (t->type == JSMN_OBJECT ||
+ (t->type == JSMN_STRING && t->size != 0)) {
+ return JSMN_ERROR_INVAL;
+ }
+ }
+#else
+ /* In non-strict mode every unquoted value is a primitive */
+ default:
+#endif
+ r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens);
+ if (r < 0) return r;
+ count++;
+ if (parser->toksuper != -1 && tokens != NULL)
+ tokens[parser->toksuper].size++;
+ break;
+
+#ifdef JSMN_STRICT
+ /* Unexpected char in strict mode */
+ default:
+ return JSMN_ERROR_INVAL;
+#endif
+ }
+ }
+
+ if (tokens != NULL) {
+ for (i = parser->toknext - 1; i >= 0; i--) {
+ /* Unmatched opened object or array */
+ if (tokens[i].start != -1 && tokens[i].end == -1) {
+ return JSMN_ERROR_PART;
+ }
+ }
+ }
+
+ return count;
+}
+
+/**
+ * Creates a new parser based over a given buffer with an array of tokens
+ * available.
+ */
+void jsmn_init(jsmn_parser *parser) {
+ parser->pos = 0;
+ parser->toknext = 0;
+ parser->toksuper = -1;
+}
+
diff --git a/src/bin/psql/jsmn.h b/src/bin/psql/jsmn.h
new file mode 100755
index 0000000000000..5a5200ee2fb8a
--- /dev/null
+++ b/src/bin/psql/jsmn.h
@@ -0,0 +1,76 @@
+#ifndef __JSMN_H_
+#define __JSMN_H_
+
+#include
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * JSON type identifier. Basic types are:
+ * o Object
+ * o Array
+ * o String
+ * o Other primitive: number, boolean (true/false) or null
+ */
+typedef enum {
+ JSMN_UNDEFINED = 0,
+ JSMN_OBJECT = 1,
+ JSMN_ARRAY = 2,
+ JSMN_STRING = 3,
+ JSMN_PRIMITIVE = 4
+} jsmntype_t;
+
+enum jsmnerr {
+ /* Not enough tokens were provided */
+ JSMN_ERROR_NOMEM = -1,
+ /* Invalid character inside JSON string */
+ JSMN_ERROR_INVAL = -2,
+ /* The string is not a full JSON packet, more bytes expected */
+ JSMN_ERROR_PART = -3
+};
+
+/**
+ * JSON token description.
+ * type type (object, array, string etc.)
+ * start start position in JSON data string
+ * end end position in JSON data string
+ */
+typedef struct {
+ jsmntype_t type;
+ int start;
+ int end;
+ int size;
+#ifdef JSMN_PARENT_LINKS
+ int parent;
+#endif
+} jsmntok_t;
+
+/**
+ * JSON parser. Contains an array of token blocks available. Also stores
+ * the string being parsed now and current position in that string
+ */
+typedef struct {
+ unsigned int pos; /* offset in the JSON string */
+ unsigned int toknext; /* next token to allocate */
+ int toksuper; /* superior token node, e.g parent object or array */
+} jsmn_parser;
+
+/**
+ * Create JSON parser over an array of tokens
+ */
+void jsmn_init(jsmn_parser *parser);
+
+/**
+ * Run JSON parser. It parses a JSON data string into and array of tokens, each describing
+ * a single JSON object.
+ */
+int jsmn_parse(jsmn_parser *parser, const char *js, size_t len,
+ jsmntok_t *tokens, unsigned int num_tokens);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __JSMN_H_ */
diff --git a/src/bin/psql/nls.mk b/src/bin/psql/nls.mk
index e355f219b98f8..2eb34615666d1 100644
--- a/src/bin/psql/nls.mk
+++ b/src/bin/psql/nls.mk
@@ -1,10 +1,10 @@
# src/bin/psql/nls.mk
CATALOG_NAME = psql
AVAIL_LANGUAGES = cs de es fr he it ja ko pl pt_BR ru sv zh_CN zh_TW
-GETTEXT_FILES = command.c common.c copy.c crosstabview.c help.c input.c large_obj.c \
+GETTEXT_FILES = command.c common.c copy.c crosstabview.c help.c input.c jsmn.c large_obj.c \
mainloop.c psqlscanslash.c startup.c \
describe.c sql_help.h sql_help.c \
- tab-complete.c variables.c \
+ tab-complete.c tab-complete-cockroachdb.c tab-complete-pipelinedb.c tab-complete-redshift.c variables.c \
../../fe_utils/print.c ../../fe_utils/psqlscan.c \
../../common/exec.c ../../common/fe_memutils.c ../../common/username.c \
../../common/wait_error.c
diff --git a/src/bin/psql/settings.h b/src/bin/psql/settings.h
index 96338c31976a0..5f0e3be9dcec6 100644
--- a/src/bin/psql/settings.h
+++ b/src/bin/psql/settings.h
@@ -70,6 +70,12 @@ typedef enum
hctl_ignoreboth = hctl_ignorespace | hctl_ignoredups
} HistControl;
+enum credential_sources
+{
+ DEFAULT,
+ AWS_IAM_REDSHIFT
+};
+
enum trivalue
{
TRI_DEFAULT,
@@ -101,10 +107,12 @@ typedef struct _psqlSettings
bool notty; /* stdin or stdout is not a tty (as determined
* on startup) */
enum trivalue getPassword; /* prompt the user for a username and password */
+ enum credential_sources credential_source; /* source of database credentials */
FILE *cur_cmd_source; /* describe the status of the current main
* loop */
bool cur_cmd_interactive;
int sversion; /* backend server version */
+ const char *sengine; /* backend server engine */
const char *progname; /* in case you renamed psql */
char *inputfile; /* file being currently processed, if any */
uint64 lineno; /* also for error reporting */
diff --git a/src/bin/psql/startup.c b/src/bin/psql/startup.c
index 0dbd7841fb7f2..2626e61663a95 100644
--- a/src/bin/psql/startup.c
+++ b/src/bin/psql/startup.c
@@ -101,6 +101,7 @@ main(int argc, char *argv[])
int successResult;
bool have_password = false;
char password[100];
+ char *new_password = NULL;
char *password_prompt = NULL;
bool new_pass;
@@ -157,6 +158,7 @@ main(int argc, char *argv[])
pset.notty = (!isatty(fileno(stdin)) || !isatty(fileno(stdout)));
pset.getPassword = TRI_DEFAULT;
+ pset.credential_source = DEFAULT;
EstablishVariableSpace();
@@ -213,8 +215,30 @@ main(int argc, char *argv[])
if (pset.getPassword == TRI_YES)
{
- simple_prompt(password_prompt, password, sizeof(password), false);
- have_password = true;
+ if (pset.credential_source == AWS_IAM_REDSHIFT)
+ {
+ if (request_password_from_external_source(&(options.username), &new_password, options.host))
+ {
+ sprintf(password, "%s", new_password);
+ have_password = true;
+ }
+ else
+ {
+ psql_error("Unable to fetch Username / Password from IAM\n");
+ }
+ if (new_password)
+ free(new_password);
+ }
+ else if (pset.credential_source == DEFAULT)
+ {
+ simple_prompt(password_prompt, password, sizeof(password), false);
+ have_password = true;
+ }
+ else
+ {
+ fprintf(stderr, _("getPassword enabled but Source unclear. Exiting.\n"));
+ exit(EXIT_FAILURE);
+ }
}
/* loop until we have a password if requested by backend */
@@ -252,10 +276,29 @@ main(int argc, char *argv[])
!have_password &&
pset.getPassword != TRI_NO)
{
- PQfinish(pset.db);
- simple_prompt(password_prompt, password, sizeof(password), false);
- have_password = true;
- new_pass = true;
+ if (pset.credential_source == AWS_IAM_REDSHIFT)
+ {
+ PQfinish(pset.db);
+ if (request_password_from_external_source(&(options.username), &new_password, options.host))
+ {
+ sprintf(password, "%s", new_password);
+ have_password = true;
+ new_pass = true;
+ }
+ else
+ {
+ psql_error("Unable to fetch new Username / Password from IAM\n");
+ }
+ if (new_password)
+ free(new_password);
+ }
+ else
+ {
+ PQfinish(pset.db);
+ simple_prompt(password_prompt, password, sizeof(password), false);
+ have_password = true;
+ new_pass = true;
+ }
}
} while (new_pass);
@@ -424,6 +467,7 @@ parse_psql_options(int argc, char *argv[], struct adhoc_opts *options)
{
{"echo-all", no_argument, NULL, 'a'},
{"no-align", no_argument, NULL, 'A'},
+ {"aws-iam-redshift", no_argument, NULL, 'I'},
{"command", required_argument, NULL, 'c'},
{"dbname", required_argument, NULL, 'd'},
{"echo-queries", no_argument, NULL, 'e'},
@@ -465,7 +509,7 @@ parse_psql_options(int argc, char *argv[], struct adhoc_opts *options)
memset(options, 0, sizeof *options);
- while ((c = getopt_long(argc, argv, "aAbc:d:eEf:F:h:HlL:no:p:P:qR:sStT:U:v:VwWxXz?01",
+ while ((c = getopt_long(argc, argv, "aAbc:d:eEf:F:h:HIlL:no:p:P:qR:sStT:U:v:VwWxXz?01",
long_options, &optindex)) != -1)
{
switch (c)
@@ -513,6 +557,10 @@ parse_psql_options(int argc, char *argv[], struct adhoc_opts *options)
case 'H':
pset.popt.topt.format = PRINT_HTML;
break;
+ case 'I':
+ pset.credential_source = AWS_IAM_REDSHIFT;
+ pset.getPassword = TRI_YES;
+ break;
case 'l':
options->list_dbs = true;
break;
@@ -775,7 +823,7 @@ process_psqlrc_file(char *filename)
static void
showVersion(void)
{
- puts("psql (PostgreSQL) " PG_VERSION);
+ puts("psql (CockroachDB / PgBouncer / PipelineDB / PostgreSQL / Amazon Redshift) " PG_VERSION);
}
diff --git a/src/bin/psql/tab-complete-cockroachdb.c b/src/bin/psql/tab-complete-cockroachdb.c
new file mode 100644
index 0000000000000..146684238f93a
--- /dev/null
+++ b/src/bin/psql/tab-complete-cockroachdb.c
@@ -0,0 +1,4767 @@
+/*
+ * psql - the PostgreSQL interactive terminal
+ *
+ * Copyright (c) 2000-2017, PostgreSQL Global Development Group
+ *
+ * src/bin/psql/tab-complete-cockroachdb.c
+ */
+
+/*----------------------------------------------------------------------
+ * This file implements a somewhat more sophisticated readline "TAB
+ * completion" in psql. It is not intended to be AI, to replace
+ * learning SQL, or to relieve you from thinking about what you're
+ * doing. Also it does not always give you all the syntactically legal
+ * completions, only those that are the most common or the ones that
+ * the programmer felt most like implementing.
+ *
+ * CAVEAT: Tab completion causes queries to be sent to the backend.
+ * The number of tuples returned gets limited, in most default
+ * installations to 1000, but if you still don't like this prospect,
+ * you can turn off tab completion in your ~/.inputrc (or else
+ * ${INPUTRC}) file so:
+ *
+ * $if psql
+ * set disable-completion on
+ * $endif
+ *
+ * See `man 3 readline' or `info readline' for the full details.
+ *
+ * BUGS:
+ * - Quotes, parentheses, and other funny characters are not handled
+ * all that gracefully.
+ *----------------------------------------------------------------------
+ */
+
+#include "postgres_fe.h"
+#include "tab-complete.h"
+#include "tab-complete-cockroachdb.h"
+#include "input.h"
+
+/* If we don't have this, we might as well forget about the whole thing: */
+#ifdef USE_READLINE
+
+#include
+
+#include "catalog/pg_class.h"
+
+#include "libpq-fe.h"
+#include "pqexpbuffer.h"
+#include "common.h"
+#include "settings.h"
+#include "stringutils.h"
+
+#ifdef HAVE_RL_FILENAME_COMPLETION_FUNCTION
+#define filename_completion_function rl_filename_completion_function
+#else
+/* missing in some header files */
+extern char *filename_completion_function();
+#endif
+
+#ifdef HAVE_RL_COMPLETION_MATCHES
+#define completion_matches rl_completion_matches
+#endif
+
+/* word break characters */
+#define WORD_BREAKS "\t\n@$><=;|&{() "
+
+/*
+ * This struct is used to define "schema queries", which are custom-built
+ * to obtain possibly-schema-qualified names of database objects. There is
+ * enough similarity in the structure that we don't want to repeat it each
+ * time. So we put the components of each query into this struct and
+ * assemble them with the common boilerplate in _complete_from_query().
+ */
+typedef struct SchemaQuery
+{
+ /*
+ * Name of catalog or catalogs to be queried, with alias, eg.
+ * "pg_catalog.pg_class c". Note that "pg_namespace n" will be added.
+ */
+ const char *catname;
+
+ /*
+ * Selection condition --- only rows meeting this condition are candidates
+ * to display. If catname mentions multiple tables, include the necessary
+ * join condition here. For example, this might look like "c.relkind = "
+ * CppAsString2(RELKIND_RELATION). Write NULL (not an empty string) if
+ * not needed.
+ */
+ const char *selcondition;
+
+ /*
+ * Visibility condition --- which rows are visible without schema
+ * qualification? For example, "pg_catalog.pg_table_is_visible(c.oid)"
+ * However, in CockroachDB there are *no* xxx_is_visible() functions,
+ * so setting all viscondition values (in Macros) to true by default
+ */
+ const char *viscondition;
+
+ /*
+ * Namespace --- name of field to join to pg_namespace.oid. For example,
+ * "c.relnamespace".
+ */
+ const char *namespace;
+
+ /*
+ * Result --- the appropriately-quoted name to return, in the case of an
+ * unqualified name. For example, "pg_catalog.quote_ident(c.relname)".
+ */
+ const char *result;
+
+ /*
+ * In some cases a different result must be used for qualified names.
+ * Enter that here, or write NULL if result can be used.
+ */
+ const char *qualresult;
+} SchemaQuery;
+
+
+/* Store maximum number of records we want from database queries
+ * (implemented via SELECT ... LIMIT xx).
+ */
+static int completion_max_records;
+
+/*
+ * Communication variables set by COMPLETE_WITH_FOO macros and then used by
+ * the completion callback functions. Ugly but there is no better way.
+ */
+static const char *completion_charp; /* to pass a string */
+static const char *const *completion_charpp; /* to pass a list of strings */
+static const char *completion_info_charp; /* to pass a second string */
+static const char *completion_info_charp2; /* to pass a third string */
+static const SchemaQuery *completion_squery; /* to pass a SchemaQuery */
+static bool completion_case_sensitive; /* completion is case sensitive */
+
+/*
+ * A few macros to ease typing. You can use these to complete the given
+ * string with
+ * 1) The results from a query you pass it. (Perhaps one of those below?)
+ * 2) The results from a schema query you pass it.
+ * 3) The items from a null-pointer-terminated list (with or without
+ * case-sensitive comparison; see also COMPLETE_WITH_LISTn, below).
+ * 4) A string constant.
+ * 5) The list of attributes of the given table (possibly schema-qualified).
+ * 6/ The list of arguments to the given function (possibly schema-qualified).
+ */
+#define COMPLETE_WITH_QUERY(query) \
+do { \
+ completion_charp = query; \
+ matches = completion_matches(text, complete_from_query); \
+} while (0)
+
+#define COMPLETE_WITH_SCHEMA_QUERY(query, addon) \
+do { \
+ completion_squery = &(query); \
+ completion_charp = addon; \
+ matches = completion_matches(text, complete_from_schema_query); \
+} while (0)
+
+#define COMPLETE_WITH_LIST_CS(list) \
+do { \
+ completion_charpp = list; \
+ completion_case_sensitive = true; \
+ matches = completion_matches(text, complete_from_list); \
+} while (0)
+
+#define COMPLETE_WITH_LIST(list) \
+do { \
+ completion_charpp = list; \
+ completion_case_sensitive = false; \
+ matches = completion_matches(text, complete_from_list); \
+} while (0)
+
+#define COMPLETE_WITH_CONST(string) \
+do { \
+ completion_charp = string; \
+ completion_case_sensitive = false; \
+ matches = completion_matches(text, complete_from_const); \
+} while (0)
+
+#define COMPLETE_WITH_ATTR(relation, addon) \
+do { \
+ char *_completion_schema; \
+ char *_completion_table; \
+\
+ _completion_schema = strtokx(relation, " \t\n\r", ".", "\"", 0, \
+ false, false, pset.encoding); \
+ (void) strtokx(NULL, " \t\n\r", ".", "\"", 0, \
+ false, false, pset.encoding); \
+ _completion_table = strtokx(NULL, " \t\n\r", ".", "\"", 0, \
+ false, false, pset.encoding); \
+ if (_completion_table == NULL) \
+ { \
+ completion_charp = Query_for_list_of_attributes addon; \
+ completion_info_charp = relation; \
+ } \
+ else \
+ { \
+ completion_charp = Query_for_list_of_attributes_with_schema addon; \
+ completion_info_charp = _completion_table; \
+ completion_info_charp2 = _completion_schema; \
+ } \
+ matches = completion_matches(text, complete_from_query); \
+} while (0)
+
+#define COMPLETE_WITH_ENUM_VALUE(type) \
+do { \
+ char *_completion_schema; \
+ char *_completion_type; \
+\
+ _completion_schema = strtokx(type, " \t\n\r", ".", "\"", 0, \
+ false, false, pset.encoding); \
+ (void) strtokx(NULL, " \t\n\r", ".", "\"", 0, \
+ false, false, pset.encoding); \
+ _completion_type = strtokx(NULL, " \t\n\r", ".", "\"", 0, \
+ false, false, pset.encoding); \
+ if (_completion_type == NULL)\
+ { \
+ completion_charp = Query_for_list_of_enum_values; \
+ completion_info_charp = type; \
+ } \
+ else \
+ { \
+ completion_charp = Query_for_list_of_enum_values_with_schema; \
+ completion_info_charp = _completion_type; \
+ completion_info_charp2 = _completion_schema; \
+ } \
+ matches = completion_matches(text, complete_from_query); \
+} while (0)
+
+#define COMPLETE_WITH_FUNCTION_ARG(function) \
+do { \
+ char *_completion_schema; \
+ char *_completion_function; \
+\
+ _completion_schema = strtokx(function, " \t\n\r", ".", "\"", 0, \
+ false, false, pset.encoding); \
+ (void) strtokx(NULL, " \t\n\r", ".", "\"", 0, \
+ false, false, pset.encoding); \
+ _completion_function = strtokx(NULL, " \t\n\r", ".", "\"", 0, \
+ false, false, pset.encoding); \
+ if (_completion_function == NULL) \
+ { \
+ completion_charp = Query_for_list_of_arguments; \
+ completion_info_charp = function; \
+ } \
+ else \
+ { \
+ completion_charp = Query_for_list_of_arguments_with_schema; \
+ completion_info_charp = _completion_function; \
+ completion_info_charp2 = _completion_schema; \
+ } \
+ matches = completion_matches(text, complete_from_query); \
+} while (0)
+
+/*
+ * These macros simplify use of COMPLETE_WITH_LIST for short, fixed lists.
+ * There is no COMPLETE_WITH_LIST1; use COMPLETE_WITH_CONST for that case.
+ */
+#define COMPLETE_WITH_LIST2(s1, s2) \
+do { \
+ static const char *const list[] = { s1, s2, NULL }; \
+ COMPLETE_WITH_LIST(list); \
+} while (0)
+
+#define COMPLETE_WITH_LIST3(s1, s2, s3) \
+do { \
+ static const char *const list[] = { s1, s2, s3, NULL }; \
+ COMPLETE_WITH_LIST(list); \
+} while (0)
+
+#define COMPLETE_WITH_LIST4(s1, s2, s3, s4) \
+do { \
+ static const char *const list[] = { s1, s2, s3, s4, NULL }; \
+ COMPLETE_WITH_LIST(list); \
+} while (0)
+
+#define COMPLETE_WITH_LIST5(s1, s2, s3, s4, s5) \
+do { \
+ static const char *const list[] = { s1, s2, s3, s4, s5, NULL }; \
+ COMPLETE_WITH_LIST(list); \
+} while (0)
+
+#define COMPLETE_WITH_LIST6(s1, s2, s3, s4, s5, s6) \
+do { \
+ static const char *const list[] = { s1, s2, s3, s4, s5, s6, NULL }; \
+ COMPLETE_WITH_LIST(list); \
+} while (0)
+
+#define COMPLETE_WITH_LIST7(s1, s2, s3, s4, s5, s6, s7) \
+do { \
+ static const char *const list[] = { s1, s2, s3, s4, s5, s6, s7, NULL }; \
+ COMPLETE_WITH_LIST(list); \
+} while (0)
+
+#define COMPLETE_WITH_LIST8(s1, s2, s3, s4, s5, s6, s7, s8) \
+do { \
+ static const char *const list[] = { s1, s2, s3, s4, s5, s6, s7, s8, NULL }; \
+ COMPLETE_WITH_LIST(list); \
+} while (0)
+
+#define COMPLETE_WITH_LIST9(s1, s2, s3, s4, s5, s6, s7, s8, s9) \
+do { \
+ static const char *const list[] = { s1, s2, s3, s4, s5, s6, s7, s8, s9, NULL }; \
+ COMPLETE_WITH_LIST(list); \
+} while (0)
+
+#define COMPLETE_WITH_LIST10(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10) \
+do { \
+ static const char *const list[] = { s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, NULL }; \
+ COMPLETE_WITH_LIST(list); \
+} while (0)
+
+#define COMPLETE_WITH_LIST11(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11) \
+do { \
+ static const char *const list[] = { s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, NULL }; \
+ COMPLETE_WITH_LIST(list); \
+} while (0)
+
+#define COMPLETE_WITH_LIST12(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12) \
+do { \
+ static const char *const list[] = { s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, NULL }; \
+ COMPLETE_WITH_LIST(list); \
+} while (0)
+
+/*
+ * Likewise for COMPLETE_WITH_LIST_CS.
+ */
+#define COMPLETE_WITH_LIST_CS2(s1, s2) \
+do { \
+ static const char *const list[] = { s1, s2, NULL }; \
+ COMPLETE_WITH_LIST_CS(list); \
+} while (0)
+
+#define COMPLETE_WITH_LIST_CS3(s1, s2, s3) \
+do { \
+ static const char *const list[] = { s1, s2, s3, NULL }; \
+ COMPLETE_WITH_LIST_CS(list); \
+} while (0)
+
+#define COMPLETE_WITH_LIST_CS4(s1, s2, s3, s4) \
+do { \
+ static const char *const list[] = { s1, s2, s3, s4, NULL }; \
+ COMPLETE_WITH_LIST_CS(list); \
+} while (0)
+
+#define COMPLETE_WITH_LIST_CS5(s1, s2, s3, s4, s5) \
+do { \
+ static const char *const list[] = { s1, s2, s3, s4, s5, NULL }; \
+ COMPLETE_WITH_LIST_CS(list); \
+} while (0)
+
+/*
+ * Assembly instructions for schema queries
+ */
+
+static const SchemaQuery Query_for_list_of_aggregates = {
+ /* catname */
+ "pg_catalog.pg_proc p",
+ /* selcondition */
+ "p.proisagg",
+ /* viscondition */
+ "true",
+ /* namespace */
+ "p.pronamespace",
+ /* result */
+ "pg_catalog.quote_ident(p.proname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_datatypes = {
+ /* catname */
+ "pg_catalog.pg_type t",
+ /* selcondition --- ignore table rowtypes and array types */
+ "(t.typrelid = 0 "
+ " OR (SELECT c.relkind = " CppAsString2(RELKIND_COMPOSITE_TYPE)
+ " FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid)) "
+ "AND t.typname !~ '^_'",
+ /* viscondition */
+ "true",
+ /* namespace */
+ "t.typnamespace",
+ /* result */
+ "pg_catalog.format_type(t.oid, NULL)",
+ /* qualresult */
+ "pg_catalog.quote_ident(t.typname)"
+};
+
+static const SchemaQuery Query_for_list_of_domains = {
+ /* catname */
+ "pg_catalog.pg_type t",
+ /* selcondition */
+ "t.typtype = 'd'",
+ /* viscondition */
+ "true",
+ /* namespace */
+ "t.typnamespace",
+ /* result */
+ "pg_catalog.quote_ident(t.typname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_functions = {
+ /* catname */
+ "pg_catalog.pg_proc p",
+ /* selcondition */
+ NULL,
+ /* viscondition */
+ "true",
+ /* namespace */
+ "p.pronamespace",
+ /* result */
+ "pg_catalog.quote_ident(p.proname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_indexes = {
+ /* catname */
+ "pg_catalog.pg_class c",
+ /* selcondition */
+ "c.relkind IN (" CppAsString2(RELKIND_INDEX) ")",
+ /* viscondition */
+ "true",
+ /* namespace */
+ "c.relnamespace",
+ /* result */
+ "pg_catalog.quote_ident(c.relname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_sequences = {
+ /* catname */
+ "pg_catalog.pg_class c",
+ /* selcondition */
+ "c.relkind IN (" CppAsString2(RELKIND_SEQUENCE) ")",
+ /* viscondition */
+ "true",
+ /* namespace */
+ "c.relnamespace",
+ /* result */
+ "pg_catalog.quote_ident(c.relname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_foreign_tables = {
+ /* catname */
+ "pg_catalog.pg_class c",
+ /* selcondition */
+ "c.relkind IN (" CppAsString2(RELKIND_FOREIGN_TABLE) ")",
+ /* viscondition */
+ "true",
+ /* namespace */
+ "c.relnamespace",
+ /* result */
+ "pg_catalog.quote_ident(c.relname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_tables = {
+ /* catname */
+ "pg_catalog.pg_class c",
+ /* selcondition */
+ "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
+ CppAsString2(RELKIND_PARTITIONED_TABLE) ")",
+ /* viscondition */
+ "true",
+ /* namespace */
+ "c.relnamespace",
+ /* result */
+ "pg_catalog.quote_ident(c.relname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_partitioned_tables = {
+ /* catname */
+ "pg_catalog.pg_class c",
+ /* selcondition */
+ "c.relkind IN (" CppAsString2(RELKIND_PARTITIONED_TABLE) ")",
+ /* viscondition */
+ "true",
+ /* namespace */
+ "c.relnamespace",
+ /* result */
+ "pg_catalog.quote_ident(c.relname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_constraints_with_schema = {
+ /* catname */
+ "pg_catalog.pg_constraint c",
+ /* selcondition */
+ "c.conrelid <> 0",
+ /* viscondition */
+ "true",
+ /* namespace */
+ "c.connamespace",
+ /* result */
+ "pg_catalog.quote_ident(c.conname)",
+ /* qualresult */
+ NULL
+};
+
+/* Relations supporting INSERT, UPDATE or DELETE */
+static const SchemaQuery Query_for_list_of_updatables = {
+ /* catname */
+ "pg_catalog.pg_class c",
+ /* selcondition */
+ "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
+ CppAsString2(RELKIND_FOREIGN_TABLE) ", "
+ CppAsString2(RELKIND_VIEW) ", "
+ CppAsString2(RELKIND_PARTITIONED_TABLE) ")",
+ /* viscondition */
+ "true",
+ /* namespace */
+ "c.relnamespace",
+ /* result */
+ "pg_catalog.quote_ident(c.relname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_relations = {
+ /* catname */
+ "pg_catalog.pg_class c",
+ /* selcondition */
+ NULL,
+ /* viscondition */
+ "true",
+ /* namespace */
+ "c.relnamespace",
+ /* result */
+ "pg_catalog.quote_ident(c.relname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_tsvmf = {
+ /* catname */
+ "pg_catalog.pg_class c",
+ /* selcondition */
+ "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
+ CppAsString2(RELKIND_SEQUENCE) ", "
+ CppAsString2(RELKIND_VIEW) ", "
+ CppAsString2(RELKIND_MATVIEW) ", "
+ CppAsString2(RELKIND_FOREIGN_TABLE) ", "
+ CppAsString2(RELKIND_PARTITIONED_TABLE) ")",
+ /* viscondition */
+ "true",
+ /* namespace */
+ "c.relnamespace",
+ /* result */
+ "pg_catalog.quote_ident(c.relname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_tmf = {
+ /* catname */
+ "pg_catalog.pg_class c",
+ /* selcondition */
+ "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
+ CppAsString2(RELKIND_MATVIEW) ", "
+ CppAsString2(RELKIND_FOREIGN_TABLE) ")",
+ /* viscondition */
+ "true",
+ /* namespace */
+ "c.relnamespace",
+ /* result */
+ "pg_catalog.quote_ident(c.relname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_tm = {
+ /* catname */
+ "pg_catalog.pg_class c",
+ /* selcondition */
+ "c.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
+ CppAsString2(RELKIND_MATVIEW) ")",
+ /* viscondition */
+ "true",
+ /* namespace */
+ "c.relnamespace",
+ /* result */
+ "pg_catalog.quote_ident(c.relname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_views = {
+ /* catname */
+ "pg_catalog.pg_class c",
+ /* selcondition */
+ "c.relkind IN (" CppAsString2(RELKIND_VIEW) ")",
+ /* viscondition */
+ "true",
+ /* namespace */
+ "c.relnamespace",
+ /* result */
+ "pg_catalog.quote_ident(c.relname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_matviews = {
+ /* catname */
+ "pg_catalog.pg_class c",
+ /* selcondition */
+ "c.relkind IN (" CppAsString2(RELKIND_MATVIEW) ")",
+ /* viscondition */
+ "true",
+ /* namespace */
+ "c.relnamespace",
+ /* result */
+ "pg_catalog.quote_ident(c.relname)",
+ /* qualresult */
+ NULL
+};
+
+static const SchemaQuery Query_for_list_of_statistics = {
+ /* catname */
+ "pg_catalog.pg_statistic_ext s",
+ /* selcondition */
+ NULL,
+ /* viscondition */
+ "true",
+ /* namespace */
+ "s.stxnamespace",
+ /* result */
+ "pg_catalog.quote_ident(s.stxname)",
+ /* qualresult */
+ NULL
+};
+
+
+/*
+ * Queries to get lists of names of various kinds of things, possibly
+ * restricted to names matching a partially entered name. In these queries,
+ * the first %s will be replaced by the text entered so far (suitably escaped
+ * to become a SQL literal string). %d will be replaced by the length of the
+ * string (in unescaped form). A second and third %s, if present, will be
+ * replaced by a suitably-escaped version of the string provided in
+ * completion_info_charp. A fourth and fifth %s are similarly replaced by
+ * completion_info_charp2.
+ *
+ * Beware that the allowed sequences of %s and %d are determined by
+ * _complete_from_query().
+ */
+
+#define Query_for_list_of_attributes \
+"SELECT pg_catalog.quote_ident(attname) "\
+" FROM pg_catalog.pg_attribute a, pg_catalog.pg_class c "\
+" WHERE c.oid = a.attrelid "\
+" AND a.attnum > 0 "\
+" AND NOT a.attisdropped "\
+" AND substring(pg_catalog.quote_ident(attname),1,%d)='%s' "\
+" AND (pg_catalog.quote_ident(relname)='%s' "\
+" OR '\"' || relname || '\"'='%s') "
+
+#define Query_for_list_of_attributes_with_schema \
+"SELECT pg_catalog.quote_ident(attname) "\
+" FROM pg_catalog.pg_attribute a, pg_catalog.pg_class c, pg_catalog.pg_namespace n "\
+" WHERE c.oid = a.attrelid "\
+" AND n.oid = c.relnamespace "\
+" AND a.attnum > 0 "\
+" AND NOT a.attisdropped "\
+" AND substring(pg_catalog.quote_ident(attname),1,%d)='%s' "\
+" AND (pg_catalog.quote_ident(relname)='%s' "\
+" OR '\"' || relname || '\"' ='%s') "\
+" AND (pg_catalog.quote_ident(nspname)='%s' "\
+" OR '\"' || nspname || '\"' ='%s') "
+
+#define Query_for_list_of_cursors \
+" SELECT trim(name) FROM pg_cursors ORDER BY 1"
+
+#define Query_for_list_of_enum_values \
+"SELECT pg_catalog.quote_literal(enumlabel) "\
+" FROM pg_catalog.pg_enum e, pg_catalog.pg_type t "\
+" WHERE t.oid = e.enumtypid "\
+" AND substring(pg_catalog.quote_literal(enumlabel),1,%d)='%s' "\
+" AND (pg_catalog.quote_ident(typname)='%s' "\
+" OR '\"' || typname || '\"'='%s') "
+
+#define Query_for_list_of_enum_values_with_schema \
+"SELECT pg_catalog.quote_literal(enumlabel) "\
+" FROM pg_catalog.pg_enum e, pg_catalog.pg_type t, pg_catalog.pg_namespace n "\
+" WHERE t.oid = e.enumtypid "\
+" AND n.oid = t.typnamespace "\
+" AND substring(pg_catalog.quote_literal(enumlabel),1,%d)='%s' "\
+" AND (pg_catalog.quote_ident(typname)='%s' "\
+" OR '\"' || typname || '\"'='%s') "\
+" AND (pg_catalog.quote_ident(nspname)='%s' "\
+" OR '\"' || nspname || '\"' ='%s') "
+
+#define Query_for_list_of_template_databases \
+"SELECT pg_catalog.quote_ident(d.datname) "\
+" FROM pg_catalog.pg_database d "\
+" WHERE substring(pg_catalog.quote_ident(d.datname),1,%d)='%s' "\
+" AND (d.datistemplate OR pg_catalog.pg_has_role(d.datdba, 'USAGE'))"
+
+#define Query_for_list_of_databases \
+"SELECT pg_catalog.quote_ident(datname) FROM pg_catalog.pg_database "\
+" WHERE substring(pg_catalog.quote_ident(datname),1,%d)='%s'"
+
+#define Query_for_list_of_tablespaces \
+"SELECT pg_catalog.quote_ident(spcname) FROM pg_catalog.pg_tablespace "\
+" WHERE substring(pg_catalog.quote_ident(spcname),1,%d)='%s'"
+
+#define Query_for_list_of_encodings \
+" SELECT DISTINCT pg_catalog.pg_encoding_to_char(conforencoding) "\
+" FROM pg_catalog.pg_conversion "\
+" WHERE substring(pg_catalog.pg_encoding_to_char(conforencoding),1,%d)=UPPER('%s')"
+
+#define Query_for_list_of_languages \
+"SELECT pg_catalog.quote_ident(lanname) "\
+" FROM pg_catalog.pg_language "\
+" WHERE lanname != 'internal' "\
+" AND substring(pg_catalog.quote_ident(lanname),1,%d)='%s'"
+
+#define Query_for_list_of_schemas \
+"SELECT pg_catalog.quote_ident(nspname) FROM pg_catalog.pg_namespace "\
+" WHERE substring(pg_catalog.quote_ident(nspname),1,%d)='%s'"
+
+#define Query_for_list_of_alter_system_set_vars \
+"SELECT name FROM "\
+" (SELECT pg_catalog.lower(name) AS name FROM pg_catalog.pg_settings "\
+" WHERE context != 'internal' "\
+" UNION ALL SELECT 'all') ss "\
+" WHERE substring(name,1,%d)='%s'"
+
+#define Query_for_list_of_pids \
+"SELECT process || ' (user->' || usename || '; database->' || datname || ')' FROM pg_stat_activity ORDER BY datname, usename"
+
+#define Query_for_list_of_set_vars \
+"SELECT name FROM "\
+" (SELECT pg_catalog.lower(name) AS name FROM pg_catalog.pg_settings "\
+" WHERE context IN ('user', 'superuser') "\
+" UNION ALL SELECT 'constraints' "\
+" UNION ALL SELECT 'transaction' "\
+" UNION ALL SELECT 'session' "\
+" UNION ALL SELECT 'role' "\
+" UNION ALL SELECT 'tablespace' "\
+" UNION ALL SELECT 'all') ss "\
+" WHERE substring(name,1,%d)='%s'"
+
+#define Query_for_list_of_show_vars \
+"SELECT name FROM "\
+" (SELECT pg_catalog.lower(name) AS name FROM pg_catalog.pg_settings "\
+" UNION ALL SELECT 'session authorization' "\
+" UNION ALL SELECT 'all') ss "\
+" WHERE substring(name,1,%d)='%s'"
+
+#define Query_for_list_of_roles \
+" SELECT pg_catalog.quote_ident(rolname) "\
+" FROM pg_catalog.pg_roles "\
+" WHERE substring(pg_catalog.quote_ident(rolname),1,%d)='%s'"
+
+#define Query_for_list_of_users \
+" SELECT pg_catalog.quote_ident(usename) "\
+" FROM pg_catalog.pg_user "\
+" WHERE substring(pg_catalog.quote_ident(usename),1,%d)='%s'"
+
+#define Query_for_list_of_grant_roles \
+" SELECT pg_catalog.quote_ident(rolname) "\
+" FROM pg_catalog.pg_roles "\
+" WHERE substring(pg_catalog.quote_ident(rolname),1,%d)='%s'"\
+" UNION ALL SELECT 'PUBLIC'"\
+" UNION ALL SELECT 'CURRENT_USER'"\
+" UNION ALL SELECT 'SESSION_USER'"
+
+/* the silly-looking length condition is just to eat up the current word */
+#define Query_for_table_owning_index \
+"SELECT pg_catalog.quote_ident(c1.relname) "\
+" FROM pg_catalog.pg_class c1, pg_catalog.pg_class c2, pg_catalog.pg_index i"\
+" WHERE c1.oid=i.indrelid and i.indexrelid=c2.oid"\
+" and (%d = pg_catalog.length('%s'))"\
+" and pg_catalog.quote_ident(c2.relname)='%s'"
+
+/* the silly-looking length condition is just to eat up the current word */
+#define Query_for_index_of_table \
+"SELECT pg_catalog.quote_ident(c2.relname) "\
+" FROM pg_catalog.pg_class c1, pg_catalog.pg_class c2, pg_catalog.pg_index i"\
+" WHERE c1.oid=i.indrelid and i.indexrelid=c2.oid"\
+" and (%d = pg_catalog.length('%s'))"\
+" and pg_catalog.quote_ident(c1.relname)='%s'"
+
+/* the silly-looking length condition is just to eat up the current word */
+#define Query_for_constraint_of_table \
+"SELECT pg_catalog.quote_ident(conname) "\
+" FROM pg_catalog.pg_class c1, pg_catalog.pg_constraint con "\
+" WHERE c1.oid=conrelid and (%d = pg_catalog.length('%s'))"\
+" and pg_catalog.quote_ident(c1.relname)='%s'"
+
+#define Query_for_all_table_constraints \
+"SELECT pg_catalog.quote_ident(conname) "\
+" FROM pg_catalog.pg_constraint c "\
+" WHERE c.conrelid <> 0 "
+
+/* the silly-looking length condition is just to eat up the current word */
+#define Query_for_constraint_of_type \
+"SELECT pg_catalog.quote_ident(conname) "\
+" FROM pg_catalog.pg_type t, pg_catalog.pg_constraint con "\
+" WHERE t.oid=contypid and (%d = pg_catalog.length('%s'))"\
+" and pg_catalog.quote_ident(t.typname)='%s'"
+
+/* the silly-looking length condition is just to eat up the current word */
+#define Query_for_list_of_tables_for_constraint \
+"SELECT pg_catalog.quote_ident(relname) "\
+" FROM pg_catalog.pg_class"\
+" WHERE (%d = pg_catalog.length('%s'))"\
+" AND oid IN "\
+" (SELECT conrelid FROM pg_catalog.pg_constraint "\
+" WHERE pg_catalog.quote_ident(conname)='%s')"
+
+/* the silly-looking length condition is just to eat up the current word */
+#define Query_for_rule_of_table \
+"SELECT pg_catalog.quote_ident(rulename) "\
+" FROM pg_catalog.pg_class c1, pg_catalog.pg_rewrite "\
+" WHERE c1.oid=ev_class and (%d = pg_catalog.length('%s'))"\
+" and pg_catalog.quote_ident(c1.relname)='%s'"
+
+/* the silly-looking length condition is just to eat up the current word */
+#define Query_for_list_of_tables_for_rule \
+"SELECT pg_catalog.quote_ident(relname) "\
+" FROM pg_catalog.pg_class"\
+" WHERE (%d = pg_catalog.length('%s'))"\
+" AND oid IN "\
+" (SELECT ev_class FROM pg_catalog.pg_rewrite "\
+" WHERE pg_catalog.quote_ident(rulename)='%s')"
+
+/* the silly-looking length condition is just to eat up the current word */
+#define Query_for_trigger_of_table \
+"SELECT pg_catalog.quote_ident(tgname) "\
+" FROM pg_catalog.pg_class c1, pg_catalog.pg_trigger "\
+" WHERE c1.oid=tgrelid and (%d = pg_catalog.length('%s'))"\
+" and pg_catalog.quote_ident(c1.relname)='%s'"\
+" and not tgisinternal"
+
+/* the silly-looking length condition is just to eat up the current word */
+#define Query_for_list_of_tables_for_trigger \
+"SELECT pg_catalog.quote_ident(relname) "\
+" FROM pg_catalog.pg_class"\
+" WHERE (%d = pg_catalog.length('%s'))"\
+" AND oid IN "\
+" (SELECT tgrelid FROM pg_catalog.pg_trigger "\
+" WHERE pg_catalog.quote_ident(tgname)='%s')"
+
+#define Query_for_list_of_ts_configurations \
+"SELECT pg_catalog.quote_ident(cfgname) FROM pg_catalog.pg_ts_config "\
+" WHERE substring(pg_catalog.quote_ident(cfgname),1,%d)='%s'"
+
+#define Query_for_list_of_ts_dictionaries \
+"SELECT pg_catalog.quote_ident(dictname) FROM pg_catalog.pg_ts_dict "\
+" WHERE substring(pg_catalog.quote_ident(dictname),1,%d)='%s'"
+
+#define Query_for_list_of_ts_parsers \
+"SELECT pg_catalog.quote_ident(prsname) FROM pg_catalog.pg_ts_parser "\
+" WHERE substring(pg_catalog.quote_ident(prsname),1,%d)='%s'"
+
+#define Query_for_list_of_ts_templates \
+"SELECT pg_catalog.quote_ident(tmplname) FROM pg_catalog.pg_ts_template "\
+" WHERE substring(pg_catalog.quote_ident(tmplname),1,%d)='%s'"
+
+#define Query_for_list_of_fdws \
+" SELECT pg_catalog.quote_ident(fdwname) "\
+" FROM pg_catalog.pg_foreign_data_wrapper "\
+" WHERE substring(pg_catalog.quote_ident(fdwname),1,%d)='%s'"
+
+#define Query_for_list_of_servers \
+" SELECT pg_catalog.quote_ident(srvname) "\
+" FROM pg_catalog.pg_foreign_server "\
+" WHERE substring(pg_catalog.quote_ident(srvname),1,%d)='%s'"
+
+#define Query_for_list_of_user_mappings \
+" SELECT pg_catalog.quote_ident(usename) "\
+" FROM pg_catalog.pg_user_mappings "\
+" WHERE substring(pg_catalog.quote_ident(usename),1,%d)='%s'"
+
+#define Query_for_list_of_access_methods \
+" SELECT pg_catalog.quote_ident(amname) "\
+" FROM pg_catalog.pg_am "\
+" WHERE substring(pg_catalog.quote_ident(amname),1,%d)='%s'"
+
+#define Query_for_list_of_libraries \
+" SELECT pg_catalog.quote_ident(name) "\
+" FROM pg_catalog.pg_library "\
+" WHERE substring(pg_catalog.quote_ident(name),1,%d)='%s'"
+
+#define Query_for_list_of_publications \
+" SELECT pg_catalog.quote_ident(pubname) "\
+" FROM pg_catalog.pg_publication "\
+" WHERE substring(pg_catalog.quote_ident(pubname),1,%d)='%s'"
+
+#define Query_for_list_of_subscriptions \
+" SELECT pg_catalog.quote_ident(s.subname) "\
+" FROM pg_catalog.pg_subscription s, pg_catalog.pg_database d "\
+" WHERE substring(pg_catalog.quote_ident(s.subname),1,%d)='%s' "\
+" AND d.datname = pg_catalog.current_database() "\
+" AND s.subdbid = d.oid"
+
+/* the silly-looking length condition is just to eat up the current word */
+#define Query_for_list_of_arguments \
+"SELECT pg_catalog.oidvectortypes(proargtypes)||')' "\
+" FROM pg_catalog.pg_proc "\
+" WHERE (%d = pg_catalog.length('%s'))"\
+" AND (pg_catalog.quote_ident(proname)='%s'"\
+" OR '\"' || proname || '\"'='%s') "
+
+/* the silly-looking length condition is just to eat up the current word */
+#define Query_for_list_of_arguments_with_schema \
+"SELECT pg_catalog.oidvectortypes(proargtypes)||')' "\
+" FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n "\
+" WHERE (%d = pg_catalog.length('%s'))"\
+" AND n.oid = p.pronamespace "\
+" AND (pg_catalog.quote_ident(proname)='%s' "\
+" OR '\"' || proname || '\"' ='%s') "\
+" AND (pg_catalog.quote_ident(nspname)='%s' "\
+" OR '\"' || nspname || '\"' ='%s') "
+
+#define Query_for_list_of_extensions \
+" SELECT pg_catalog.quote_ident(extname) "\
+" FROM pg_catalog.pg_extension "\
+" WHERE substring(pg_catalog.quote_ident(extname),1,%d)='%s'"
+
+#define Query_for_list_of_available_extensions \
+" SELECT pg_catalog.quote_ident(name) "\
+" FROM pg_catalog.pg_available_extensions "\
+" WHERE substring(pg_catalog.quote_ident(name),1,%d)='%s' AND installed_version IS NULL"
+
+/* the silly-looking length condition is just to eat up the current word */
+#define Query_for_list_of_available_extension_versions \
+" SELECT pg_catalog.quote_ident(version) "\
+" FROM pg_catalog.pg_available_extension_versions "\
+" WHERE (%d = pg_catalog.length('%s'))"\
+" AND pg_catalog.quote_ident(name)='%s'"
+
+/* the silly-looking length condition is just to eat up the current word */
+#define Query_for_list_of_available_extension_versions_with_TO \
+" SELECT 'TO ' || pg_catalog.quote_ident(version) "\
+" FROM pg_catalog.pg_available_extension_versions "\
+" WHERE (%d = pg_catalog.length('%s'))"\
+" AND pg_catalog.quote_ident(name)='%s'"
+
+#define Query_for_list_of_prepared_statements \
+" SELECT pg_catalog.quote_ident(name) "\
+" FROM pg_catalog.pg_prepared_statements "\
+" WHERE substring(pg_catalog.quote_ident(name),1,%d)='%s'"
+
+#define Query_for_list_of_event_triggers \
+" SELECT pg_catalog.quote_ident(evtname) "\
+" FROM pg_catalog.pg_event_trigger "\
+" WHERE substring(pg_catalog.quote_ident(evtname),1,%d)='%s'"
+
+#define Query_for_list_of_tablesample_methods \
+" SELECT pg_catalog.quote_ident(proname) "\
+" FROM pg_catalog.pg_proc "\
+" WHERE prorettype = 'pg_catalog.tsm_handler'::pg_catalog.regtype AND "\
+" proargtypes[0] = 'pg_catalog.internal'::pg_catalog.regtype AND "\
+" substring(pg_catalog.quote_ident(proname),1,%d)='%s'"
+
+#define Query_for_list_of_policies \
+" SELECT pg_catalog.quote_ident(polname) "\
+" FROM pg_catalog.pg_policy "\
+" WHERE substring(pg_catalog.quote_ident(polname),1,%d)='%s'"
+
+#define Query_for_list_of_tables_for_policy \
+"SELECT pg_catalog.quote_ident(relname) "\
+" FROM pg_catalog.pg_class"\
+" WHERE (%d = pg_catalog.length('%s'))"\
+" AND oid IN "\
+" (SELECT polrelid FROM pg_catalog.pg_policy "\
+" WHERE pg_catalog.quote_ident(polname)='%s')"
+
+#define Query_for_enum \
+" SELECT name FROM ( "\
+" SELECT pg_catalog.quote_ident(pg_catalog.unnest(enumvals)) AS name "\
+" FROM pg_catalog.pg_settings "\
+" WHERE pg_catalog.lower(name)=pg_catalog.lower('%s') "\
+" UNION ALL " \
+" SELECT 'DEFAULT' ) ss "\
+" WHERE pg_catalog.substring(name,1,%%d)='%%s'"
+
+/* the silly-looking length condition is just to eat up the current word */
+#define Query_for_partition_of_table \
+"SELECT pg_catalog.quote_ident(c2.relname) "\
+" FROM pg_catalog.pg_class c1, pg_catalog.pg_class c2, pg_catalog.pg_inherits i"\
+" WHERE c1.oid=i.inhparent and i.inhrelid=c2.oid"\
+" and (%d = pg_catalog.length('%s'))"\
+" and pg_catalog.quote_ident(c1.relname)='%s'"\
+" and c2.relispartition = 'true'"
+
+/*
+ * This is a list of all "things" in Pgsql, which can show up after CREATE or
+ * DROP; and there is also a query to get a list of them.
+ */
+
+typedef struct
+{
+ const char *name;
+ const char *query; /* simple query, or NULL */
+ const SchemaQuery *squery; /* schema query, or NULL */
+ const bits32 flags; /* visibility flags, see below */
+} pgsql_thing_t;
+
+#define THING_NO_CREATE (1 << 0) /* should not show up after CREATE */
+#define THING_NO_DROP (1 << 1) /* should not show up after DROP */
+#define THING_NO_ALTER (1 << 2) /* should not show up after ALTER */
+#define THING_NO_SHOW (THING_NO_CREATE | THING_NO_DROP | THING_NO_ALTER)
+
+static const pgsql_thing_t words_after_create[] = {
+ {"ACCESS METHOD", NULL, NULL, THING_NO_ALTER},
+ {"AGGREGATE", NULL, &Query_for_list_of_aggregates},
+ {"CAST", NULL, NULL}, /* Casts have complex structures for names, so
+ * skip it */
+ {"COLLATION", "SELECT pg_catalog.quote_ident(collname) FROM pg_catalog.pg_collation WHERE collencoding IN (-1, pg_catalog.pg_char_to_encoding(pg_catalog.getdatabaseencoding())) AND substring(pg_catalog.quote_ident(collname),1,%d)='%s'"},
+
+ /*
+ * CREATE CONSTRAINT TRIGGER is not supported here because it is designed
+ * to be used only by pg_dump.
+ */
+ {"CONFIGURATION", Query_for_list_of_ts_configurations, NULL, THING_NO_SHOW},
+ {"CONVERSION", "SELECT pg_catalog.quote_ident(conname) FROM pg_catalog.pg_conversion WHERE substring(pg_catalog.quote_ident(conname),1,%d)='%s'"},
+ {"DATABASE", Query_for_list_of_databases},
+ {"DEFAULT PRIVILEGES", NULL, NULL, THING_NO_CREATE | THING_NO_DROP},
+ {"DICTIONARY", Query_for_list_of_ts_dictionaries, NULL, THING_NO_SHOW},
+ {"DOMAIN", NULL, &Query_for_list_of_domains},
+ {"EVENT TRIGGER", NULL, NULL},
+ {"EXTENSION", Query_for_list_of_extensions},
+ {"FOREIGN DATA WRAPPER", NULL, NULL},
+ {"FOREIGN TABLE", NULL, NULL},
+ {"FUNCTION", NULL, &Query_for_list_of_functions},
+ {"GROUP", Query_for_list_of_roles},
+ {"INDEX", NULL, &Query_for_list_of_indexes},
+ {"LANGUAGE", Query_for_list_of_languages},
+ {"LARGE OBJECT", NULL, NULL, THING_NO_CREATE | THING_NO_DROP},
+ {"LIBRARY", NULL, NULL, THING_NO_ALTER},
+ {"LOCAL", NULL, NULL, THING_NO_DROP | THING_NO_ALTER}, /* CREATE LOCAL TABLE */
+ {"MATERIALIZED VIEW", NULL, &Query_for_list_of_matviews},
+ {"OPERATOR", NULL, NULL}, /* Querying for this is probably not such a
+ * good idea. */
+ {"OR REPLACE FUNCTION", NULL, &Query_for_list_of_functions},
+ {"OR REPLACE LIBRARY", Query_for_list_of_libraries},
+ {"OR REPLACE VIEW", NULL, &Query_for_list_of_views},
+ {"OWNED", NULL, NULL, THING_NO_CREATE | THING_NO_ALTER}, /* for DROP OWNED BY ... */
+ {"PARSER", Query_for_list_of_ts_parsers, NULL, THING_NO_SHOW},
+ {"POLICY", NULL, NULL},
+ {"PUBLICATION", Query_for_list_of_publications},
+ {"ROLE", Query_for_list_of_roles},
+ {"RULE", "SELECT pg_catalog.quote_ident(rulename) FROM pg_catalog.pg_rules WHERE substring(pg_catalog.quote_ident(rulename),1,%d)='%s'"},
+ {"SCHEMA", Query_for_list_of_schemas},
+ {"SEQUENCE", NULL, &Query_for_list_of_sequences},
+ {"SERVER", Query_for_list_of_servers},
+ {"STATISTICS", NULL, &Query_for_list_of_statistics},
+ {"SUBSCRIPTION", Query_for_list_of_subscriptions},
+ {"SYSTEM", NULL, NULL, THING_NO_CREATE | THING_NO_DROP},
+ {"TABLE", NULL, &Query_for_list_of_tables},
+ {"TABLESPACE", Query_for_list_of_tablespaces},
+ {"TEMP", NULL, NULL, THING_NO_DROP | THING_NO_ALTER}, /* for CREATE TEMP TABLE
+ * ... */
+ {"TEMPLATE", Query_for_list_of_ts_templates, NULL, THING_NO_SHOW},
+ {"TEMPORARY", NULL, NULL, THING_NO_DROP | THING_NO_ALTER}, /* for CREATE TEMPORARY
+ * TABLE ... */
+ {"TEXT SEARCH", NULL, NULL},
+ {"TRANSFORM", NULL, NULL},
+ {"TRIGGER", "SELECT pg_catalog.quote_ident(tgname) FROM pg_catalog.pg_trigger WHERE substring(pg_catalog.quote_ident(tgname),1,%d)='%s' AND NOT tgisinternal"},
+ {"TYPE", NULL, &Query_for_list_of_datatypes},
+ {"UNIQUE", NULL, NULL, THING_NO_DROP | THING_NO_ALTER}, /* for CREATE UNIQUE
+ * INDEX ... */
+ {"UNLOGGED", NULL, NULL, THING_NO_DROP | THING_NO_ALTER}, /* for CREATE UNLOGGED
+ * TABLE ... */
+ {"USER", Query_for_list_of_roles " UNION SELECT 'MAPPING FOR'"},
+ {"USER MAPPING FOR", NULL, NULL},
+ {"VIEW", NULL, &Query_for_list_of_views},
+ {NULL} /* end of list */
+};
+
+
+/* Forward declaration of functions */
+static char **psql_completion(const char *text, int start, int end);
+static char *create_command_generator(const char *text, int state);
+static char *drop_command_generator(const char *text, int state);
+static char *alter_command_generator(const char *text, int state);
+static char *complete_from_query(const char *text, int state);
+static char *complete_from_schema_query(const char *text, int state);
+static char *_complete_from_query(int is_schema_query,
+ const char *text, int state);
+static char *complete_from_list(const char *text, int state);
+static char *complete_from_const(const char *text, int state);
+static void append_variable_names(char ***varnames, int *nvars,
+ int *maxvars, const char *varname,
+ const char *prefix, const char *suffix);
+static char **complete_from_variables(const char *text,
+ const char *prefix, const char *suffix, bool need_value);
+static char *complete_from_files(const char *text, int state);
+
+static char *pg_strdup_keyword_case(const char *s, const char *ref);
+static char *escape_string(const char *text);
+static PGresult *exec_query(const char *query);
+
+static char **get_previous_words(int point, char **buffer, int *nwords);
+
+static char *get_guctype(const char *varname);
+
+#ifdef NOT_USED
+static char *quote_file_name(char *text, int match_type, char *quote_pointer);
+static char *dequote_file_name(char *text, char quote_char);
+#endif
+
+
+/*
+ * Initialize the readline library for our purposes.
+ */
+void
+initialize_readline_cockroachdb(void)
+{
+ rl_readline_name = (char *) pset.progname;
+ rl_attempted_completion_function = psql_completion;
+
+ rl_basic_word_break_characters = WORD_BREAKS;
+
+ completion_max_records = 1000;
+
+ /*
+ * There is a variable rl_completion_query_items for this but apparently
+ * it's not defined everywhere.
+ */
+}
+
+/*
+ * Check if 'word' matches any of the '|'-separated strings in 'pattern',
+ * using case-insensitive or case-sensitive comparisons.
+ *
+ * If pattern is NULL, it's a wild card that matches any word.
+ * If pattern begins with '!', the result is negated, ie we check that 'word'
+ * does *not* match any alternative appearing in the rest of 'pattern'.
+ * Any alternative can end with '*' which is a wild card, i.e., it means
+ * match any word that matches the characters so far. (We do not currently
+ * support '*' elsewhere than the end of an alternative.)
+ *
+ * For readability, callers should use the macros MatchAny and MatchAnyExcept
+ * to invoke those two special cases for 'pattern'. (But '|' and '*' must
+ * just be written directly in patterns.)
+ */
+#define MatchAny NULL
+#define MatchAnyExcept(pattern) ("!" pattern)
+
+static bool
+word_matches_internal(const char *pattern,
+ const char *word,
+ bool case_sensitive)
+{
+ size_t wordlen,
+ patternlen;
+
+ /* NULL pattern matches anything. */
+ if (pattern == NULL)
+ return true;
+
+ /* Handle negated patterns from the MatchAnyExcept macro. */
+ if (*pattern == '!')
+ return !word_matches_internal(pattern + 1, word, case_sensitive);
+
+ /* Else consider each alternative in the pattern. */
+ wordlen = strlen(word);
+ for (;;)
+ {
+ const char *c;
+
+ /* Find end of current alternative. */
+ c = pattern;
+ while (*c != '\0' && *c != '|')
+ c++;
+ /* Was there a wild card? (Assumes first alternative is not empty) */
+ if (c[-1] == '*')
+ {
+ /* Yes, wildcard match? */
+ patternlen = c - pattern - 1;
+ if (wordlen >= patternlen &&
+ (case_sensitive ?
+ strncmp(word, pattern, patternlen) == 0 :
+ pg_strncasecmp(word, pattern, patternlen) == 0))
+ return true;
+ }
+ else
+ {
+ /* No, plain match? */
+ patternlen = c - pattern;
+ if (wordlen == patternlen &&
+ (case_sensitive ?
+ strncmp(word, pattern, wordlen) == 0 :
+ pg_strncasecmp(word, pattern, wordlen) == 0))
+ return true;
+ }
+ /* Out of alternatives? */
+ if (*c == '\0')
+ break;
+ /* Nope, try next alternative. */
+ pattern = c + 1;
+ }
+
+ return false;
+}
+
+/*
+ * There are enough matching calls below that it seems worth having these two
+ * interface routines rather than including a third parameter in every call.
+ *
+ * word_matches --- match case-insensitively.
+ */
+static bool
+word_matches(const char *pattern, const char *word)
+{
+ return word_matches_internal(pattern, word, false);
+}
+
+/*
+ * word_matches_cs --- match case-sensitively.
+ */
+static bool
+word_matches_cs(const char *pattern, const char *word)
+{
+ return word_matches_internal(pattern, word, true);
+}
+
+/*
+ * Check if the final character of 's' is 'c'.
+ */
+static bool
+ends_with(const char *s, char c)
+{
+ size_t length = strlen(s);
+
+ return (length > 0 && s[length - 1] == c);
+}
+
+/*
+ * The completion function.
+ *
+ * According to readline spec this gets passed the text entered so far and its
+ * start and end positions in the readline buffer. The return value is some
+ * partially obscure list format that can be generated by readline's
+ * completion_matches() function, so we don't have to worry about it.
+ */
+static char **
+psql_completion(const char *text, int start, int end)
+{
+ /* This is the variable we'll return. */
+ char **matches = NULL;
+
+ /* Workspace for parsed words. */
+ char *words_buffer;
+
+ /* This array will contain pointers to parsed words. */
+ char **previous_words;
+
+ /* The number of words found on the input line. */
+ int previous_words_count;
+
+ /*
+ * For compactness, we use these macros to reference previous_words[].
+ * Caution: do not access a previous_words[] entry without having checked
+ * previous_words_count to be sure it's valid. In most cases below, that
+ * check is implicit in a TailMatches() or similar macro, but in some
+ * places we have to check it explicitly.
+ */
+#define prev_wd (previous_words[0])
+#define prev2_wd (previous_words[1])
+#define prev3_wd (previous_words[2])
+#define prev4_wd (previous_words[3])
+#define prev5_wd (previous_words[4])
+#define prev6_wd (previous_words[5])
+#define prev7_wd (previous_words[6])
+#define prev8_wd (previous_words[7])
+#define prev9_wd (previous_words[8])
+
+ /* Macros for matching the last N words before point, case-insensitively. */
+#define TailMatches1(p1) \
+ (previous_words_count >= 1 && \
+ word_matches(p1, prev_wd))
+
+#define TailMatches2(p2, p1) \
+ (previous_words_count >= 2 && \
+ word_matches(p1, prev_wd) && \
+ word_matches(p2, prev2_wd))
+
+#define TailMatches3(p3, p2, p1) \
+ (previous_words_count >= 3 && \
+ word_matches(p1, prev_wd) && \
+ word_matches(p2, prev2_wd) && \
+ word_matches(p3, prev3_wd))
+
+#define TailMatches4(p4, p3, p2, p1) \
+ (previous_words_count >= 4 && \
+ word_matches(p1, prev_wd) && \
+ word_matches(p2, prev2_wd) && \
+ word_matches(p3, prev3_wd) && \
+ word_matches(p4, prev4_wd))
+
+#define TailMatches5(p5, p4, p3, p2, p1) \
+ (previous_words_count >= 5 && \
+ word_matches(p1, prev_wd) && \
+ word_matches(p2, prev2_wd) && \
+ word_matches(p3, prev3_wd) && \
+ word_matches(p4, prev4_wd) && \
+ word_matches(p5, prev5_wd))
+
+#define TailMatches6(p6, p5, p4, p3, p2, p1) \
+ (previous_words_count >= 6 && \
+ word_matches(p1, prev_wd) && \
+ word_matches(p2, prev2_wd) && \
+ word_matches(p3, prev3_wd) && \
+ word_matches(p4, prev4_wd) && \
+ word_matches(p5, prev5_wd) && \
+ word_matches(p6, prev6_wd))
+
+#define TailMatches7(p7, p6, p5, p4, p3, p2, p1) \
+ (previous_words_count >= 7 && \
+ word_matches(p1, prev_wd) && \
+ word_matches(p2, prev2_wd) && \
+ word_matches(p3, prev3_wd) && \
+ word_matches(p4, prev4_wd) && \
+ word_matches(p5, prev5_wd) && \
+ word_matches(p6, prev6_wd) && \
+ word_matches(p7, prev7_wd))
+
+#define TailMatches8(p8, p7, p6, p5, p4, p3, p2, p1) \
+ (previous_words_count >= 8 && \
+ word_matches(p1, prev_wd) && \
+ word_matches(p2, prev2_wd) && \
+ word_matches(p3, prev3_wd) && \
+ word_matches(p4, prev4_wd) && \
+ word_matches(p5, prev5_wd) && \
+ word_matches(p6, prev6_wd) && \
+ word_matches(p7, prev7_wd) && \
+ word_matches(p8, prev8_wd))
+
+#define TailMatches9(p9, p8, p7, p6, p5, p4, p3, p2, p1) \
+ (previous_words_count >= 9 && \
+ word_matches(p1, prev_wd) && \
+ word_matches(p2, prev2_wd) && \
+ word_matches(p3, prev3_wd) && \
+ word_matches(p4, prev4_wd) && \
+ word_matches(p5, prev5_wd) && \
+ word_matches(p6, prev6_wd) && \
+ word_matches(p7, prev7_wd) && \
+ word_matches(p8, prev8_wd) && \
+ word_matches(p9, prev9_wd))
+
+ /* Macros for matching the last N words before point, case-sensitively. */
+#define TailMatchesCS1(p1) \
+ (previous_words_count >= 1 && \
+ word_matches_cs(p1, prev_wd))
+#define TailMatchesCS2(p2, p1) \
+ (previous_words_count >= 2 && \
+ word_matches_cs(p1, prev_wd) && \
+ word_matches_cs(p2, prev2_wd))
+#define TailMatchesCS3(p3, p2, p1) \
+ (previous_words_count >= 3 && \
+ word_matches_cs(p1, prev_wd) && \
+ word_matches_cs(p2, prev2_wd) && \
+ word_matches_cs(p3, prev3_wd))
+#define TailMatchesCS4(p4, p3, p2, p1) \
+ (previous_words_count >= 4 && \
+ word_matches_cs(p1, prev_wd) && \
+ word_matches_cs(p2, prev2_wd) && \
+ word_matches_cs(p3, prev3_wd) && \
+ word_matches_cs(p4, prev4_wd))
+
+ /*
+ * Macros for matching N words beginning at the start of the line,
+ * case-insensitively.
+ */
+#define Matches1(p1) \
+ (previous_words_count == 1 && \
+ TailMatches1(p1))
+#define Matches2(p1, p2) \
+ (previous_words_count == 2 && \
+ TailMatches2(p1, p2))
+#define Matches3(p1, p2, p3) \
+ (previous_words_count == 3 && \
+ TailMatches3(p1, p2, p3))
+#define Matches4(p1, p2, p3, p4) \
+ (previous_words_count == 4 && \
+ TailMatches4(p1, p2, p3, p4))
+#define Matches5(p1, p2, p3, p4, p5) \
+ (previous_words_count == 5 && \
+ TailMatches5(p1, p2, p3, p4, p5))
+#define Matches6(p1, p2, p3, p4, p5, p6) \
+ (previous_words_count == 6 && \
+ TailMatches6(p1, p2, p3, p4, p5, p6))
+#define Matches7(p1, p2, p3, p4, p5, p6, p7) \
+ (previous_words_count == 7 && \
+ TailMatches7(p1, p2, p3, p4, p5, p6, p7))
+#define Matches8(p1, p2, p3, p4, p5, p6, p7, p8) \
+ (previous_words_count == 8 && \
+ TailMatches8(p1, p2, p3, p4, p5, p6, p7, p8))
+#define Matches9(p1, p2, p3, p4, p5, p6, p7, p8, p9) \
+ (previous_words_count == 9 && \
+ TailMatches9(p1, p2, p3, p4, p5, p6, p7, p8, p9))
+
+ /*
+ * Macros for matching N words at the start of the line, regardless of
+ * what is after them, case-insensitively.
+ */
+#define HeadMatches1(p1) \
+ (previous_words_count >= 1 && \
+ word_matches(p1, previous_words[previous_words_count - 1]))
+
+#define HeadMatches2(p1, p2) \
+ (previous_words_count >= 2 && \
+ word_matches(p1, previous_words[previous_words_count - 1]) && \
+ word_matches(p2, previous_words[previous_words_count - 2]))
+
+#define HeadMatches3(p1, p2, p3) \
+ (previous_words_count >= 3 && \
+ word_matches(p1, previous_words[previous_words_count - 1]) && \
+ word_matches(p2, previous_words[previous_words_count - 2]) && \
+ word_matches(p3, previous_words[previous_words_count - 3]))
+
+ #define HeadMatches4(p1, p2, p3, p4) \
+ (previous_words_count >= 4 && \
+ word_matches(p1, previous_words[previous_words_count - 1]) && \
+ word_matches(p2, previous_words[previous_words_count - 2]) && \
+ word_matches(p3, previous_words[previous_words_count - 3]) && \
+ word_matches(p4, previous_words[previous_words_count - 4]))
+
+ #define HeadMatches5(p1, p2, p3, p4, p5) \
+ (previous_words_count >= 5 && \
+ word_matches(p1, previous_words[previous_words_count - 1]) && \
+ word_matches(p2, previous_words[previous_words_count - 2]) && \
+ word_matches(p3, previous_words[previous_words_count - 3]) && \
+ word_matches(p4, previous_words[previous_words_count - 4]) && \
+ word_matches(p5, previous_words[previous_words_count - 5]))
+
+ #define HeadMatches6(p1, p2, p3, p4, p5, p6) \
+ (previous_words_count >= 6 && \
+ word_matches(p1, previous_words[previous_words_count - 1]) && \
+ word_matches(p2, previous_words[previous_words_count - 2]) && \
+ word_matches(p3, previous_words[previous_words_count - 3]) && \
+ word_matches(p4, previous_words[previous_words_count - 4]) && \
+ word_matches(p5, previous_words[previous_words_count - 5]) && \
+ word_matches(p6, previous_words[previous_words_count - 6]))
+
+ #define HeadMatches7(p1, p2, p3, p4, p5, p6, p7) \
+ (previous_words_count >= 7 && \
+ word_matches(p1, previous_words[previous_words_count - 1]) && \
+ word_matches(p2, previous_words[previous_words_count - 2]) && \
+ word_matches(p3, previous_words[previous_words_count - 3]) && \
+ word_matches(p4, previous_words[previous_words_count - 4]) && \
+ word_matches(p5, previous_words[previous_words_count - 5]) && \
+ word_matches(p6, previous_words[previous_words_count - 6]) && \
+ word_matches(p7, previous_words[previous_words_count - 7]))
+
+ #define HeadMatches8(p1, p2, p3, p4, p5, p6, p7, p8) \
+ (previous_words_count >= 8 && \
+ word_matches(p1, previous_words[previous_words_count - 1]) && \
+ word_matches(p2, previous_words[previous_words_count - 2]) && \
+ word_matches(p3, previous_words[previous_words_count - 3]) && \
+ word_matches(p4, previous_words[previous_words_count - 4]) && \
+ word_matches(p5, previous_words[previous_words_count - 5]) && \
+ word_matches(p6, previous_words[previous_words_count - 6]) && \
+ word_matches(p7, previous_words[previous_words_count - 7]) && \
+ word_matches(p8, previous_words[previous_words_count - 8]))
+
+ #define HeadMatches9(p1, p2, p3, p4, p5, p6, p7, p8, p9) \
+ (previous_words_count >= 9 && \
+ word_matches(p1, previous_words[previous_words_count - 1]) && \
+ word_matches(p2, previous_words[previous_words_count - 2]) && \
+ word_matches(p3, previous_words[previous_words_count - 3]) && \
+ word_matches(p4, previous_words[previous_words_count - 4]) && \
+ word_matches(p5, previous_words[previous_words_count - 5]) && \
+ word_matches(p6, previous_words[previous_words_count - 6]) && \
+ word_matches(p7, previous_words[previous_words_count - 7]) && \
+ word_matches(p8, previous_words[previous_words_count - 8]) && \
+ word_matches(p9, previous_words[previous_words_count - 9]))
+
+ /* Known command-starting keywords. */
+ static const char *const sql_commands[] = {
+ "ABORT", "ALTER", "ANALYZE", "BEGIN", "CHECKPOINT", "CLOSE", "CLUSTER",
+ "COMMENT", "COMMIT", "COPY", "CREATE", "DEALLOCATE", "DECLARE",
+ "DELETE FROM", "DISCARD", "DO", "DROP", "END", "EXECUTE", "EXPLAIN",
+ "FETCH", "GRANT", "IMPORT", "INSERT", "LISTEN", "LOAD", "LOCK",
+ "MOVE", "NOTIFY", "PREPARE",
+ "REASSIGN", "REFRESH MATERIALIZED VIEW", "REINDEX", "RELEASE",
+ "RESET", "REVOKE", "ROLLBACK",
+ "SAVEPOINT", "SECURITY LABEL", "SELECT", "SET", "SHOW", "START",
+ "TABLE", "TRUNCATE", "UNLISTEN", "UPDATE", "VACUUM", "VALUES", "WITH",
+ NULL
+ };
+
+ /* psql's backslash commands. */
+ static const char *const backslash_commands[] = {
+ "\\a",
+ "\\connect", "\\conninfo", "\\C", "\\cd", "\\copy",
+ "\\copyright", "\\crosstabview",
+ "\\d", "\\da", "\\dA", "\\db", "\\dc", "\\dC", "\\dd", "\\ddp", "\\dD",
+ "\\des", "\\det", "\\deu", "\\dew", "\\dE", "\\df",
+ "\\dF", "\\dFd", "\\dFp", "\\dFt", "\\dg", "\\di", "\\dl", "\\dL",
+ "\\dm", "\\dn", "\\do", "\\dO", "\\dp",
+ "\\drds", "\\dRs", "\\dRp", "\\ds", "\\dS",
+ "\\dt", "\\dT", "\\dv", "\\du", "\\dx", "\\dy",
+ "\\e", "\\echo", "\\ef", "\\elif", "\\else", "\\encoding",
+ "\\endif", "\\errverbose", "\\ev",
+ "\\f",
+ "\\g", "\\gdesc", "\\gexec", "\\gset", "\\gx",
+ "\\h", "\\help", "\\H",
+ "\\i", "\\if", "\\ir",
+ "\\l", "\\lo_import", "\\lo_export", "\\lo_list", "\\lo_unlink",
+ "\\o",
+ "\\p", "\\password", "\\prompt", "\\pset",
+ "\\q", "\\qecho",
+ "\\r",
+ "\\s", "\\set", "\\setenv", "\\sf", "\\sv",
+ "\\t", "\\T", "\\timing",
+ "\\unset",
+ "\\x",
+ "\\w", "\\watch",
+ "\\z",
+ "\\!", "\\?",
+ NULL
+ };
+
+ (void) end; /* "end" is not used */
+
+#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
+ rl_completion_append_character = ' ';
+#endif
+
+ /* Clear a few things. */
+ completion_charp = NULL;
+ completion_charpp = NULL;
+ completion_info_charp = NULL;
+ completion_info_charp2 = NULL;
+
+ /*
+ * Scan the input line to extract the words before our current position.
+ * According to those we'll make some smart decisions on what the user is
+ * probably intending to type.
+ */
+ previous_words = get_previous_words(start,
+ &words_buffer,
+ &previous_words_count);
+
+ /* If current word is a backslash command, offer completions for that */
+ if (text[0] == '\\')
+ COMPLETE_WITH_LIST_CS(backslash_commands);
+
+ /* If current word is a variable interpolation, handle that case */
+ else if (text[0] == ':' && text[1] != ':')
+ {
+ if (text[1] == '\'')
+ matches = complete_from_variables(text, ":'", "'", true);
+ else if (text[1] == '"')
+ matches = complete_from_variables(text, ":\"", "\"", true);
+ else
+ matches = complete_from_variables(text, ":", "", true);
+ }
+
+ /* If no previous word, suggest one of the basic sql commands */
+ else if (previous_words_count == 0)
+ COMPLETE_WITH_LIST(sql_commands);
+
+/* CREATE */
+ /* complete with something you can create */
+ else if (TailMatches1("CREATE"))
+ matches = completion_matches(text, create_command_generator);
+
+/* DROP, but not DROP embedded in other commands */
+ /* complete with something you can drop */
+ else if (Matches1("DROP"))
+ matches = completion_matches(text, drop_command_generator);
+
+/* ALTER */
+
+ /* ALTER TABLE */
+ else if (Matches2("ALTER", "TABLE"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables,
+ "UNION SELECT 'ALL IN TABLESPACE'");
+
+ /* ALTER something */
+ else if (Matches1("ALTER"))
+ matches = completion_matches(text, alter_command_generator);
+ /* ALTER TABLE,INDEX,MATERIALIZED VIEW ALL IN TABLESPACE xxx */
+ else if (TailMatches4("ALL", "IN", "TABLESPACE", MatchAny))
+ COMPLETE_WITH_LIST2("SET TABLESPACE", "OWNED BY");
+ /* ALTER TABLE,INDEX,MATERIALIZED VIEW ALL IN TABLESPACE xxx OWNED BY */
+ else if (TailMatches6("ALL", "IN", "TABLESPACE", MatchAny, "OWNED", "BY"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_roles);
+ /* ALTER TABLE,INDEX,MATERIALIZED VIEW ALL IN TABLESPACE xxx OWNED BY xxx */
+ else if (TailMatches7("ALL", "IN", "TABLESPACE", MatchAny, "OWNED", "BY", MatchAny))
+ COMPLETE_WITH_CONST("SET TABLESPACE");
+ /* ALTER AGGREGATE,FUNCTION */
+ else if (Matches3("ALTER", "AGGREGATE|FUNCTION", MatchAny))
+ COMPLETE_WITH_CONST("(");
+ /* ALTER AGGREGATE,FUNCTION (...) */
+ else if (Matches4("ALTER", "AGGREGATE|FUNCTION", MatchAny, MatchAny))
+ {
+ if (ends_with(prev_wd, ')'))
+ COMPLETE_WITH_LIST3("OWNER TO", "RENAME TO", "SET SCHEMA");
+ else
+ COMPLETE_WITH_FUNCTION_ARG(prev2_wd);
+ }
+ /* ALTER PUBLICATION */
+ else if (Matches3("ALTER", "PUBLICATION", MatchAny))
+ COMPLETE_WITH_LIST5("ADD TABLE", "DROP TABLE", "OWNER TO", "RENAME TO", "SET");
+ /* ALTER PUBLICATION SET */
+ else if (Matches4("ALTER", "PUBLICATION", MatchAny, "SET"))
+ COMPLETE_WITH_LIST2("(", "TABLE");
+ /* ALTER PUBLICATION SET ( */
+ else if (HeadMatches3("ALTER", "PUBLICATION", MatchAny) && TailMatches2("SET", "("))
+ COMPLETE_WITH_CONST("publish");
+ /* ALTER SUBSCRIPTION */
+ else if (Matches3("ALTER", "SUBSCRIPTION", MatchAny))
+ COMPLETE_WITH_LIST7("CONNECTION", "ENABLE", "DISABLE", "OWNER TO",
+ "RENAME TO", "REFRESH PUBLICATION", "SET");
+ /* ALTER SUBSCRIPTION REFRESH PUBLICATION */
+ else if (HeadMatches3("ALTER", "SUBSCRIPTION", MatchAny) &&
+ TailMatches2("REFRESH", "PUBLICATION"))
+ COMPLETE_WITH_CONST("WITH (");
+ /* ALTER SUBSCRIPTION REFRESH PUBLICATION WITH ( */
+ else if (HeadMatches3("ALTER", "SUBSCRIPTION", MatchAny) &&
+ TailMatches4("REFRESH", "PUBLICATION", "WITH", "("))
+ COMPLETE_WITH_CONST("copy_data");
+ /* ALTER SUBSCRIPTION SET */
+ else if (Matches4("ALTER", "SUBSCRIPTION", MatchAny, "SET"))
+ COMPLETE_WITH_LIST2("(", "PUBLICATION");
+ /* ALTER SUBSCRIPTION SET ( */
+ else if (HeadMatches3("ALTER", "SUBSCRIPTION", MatchAny) && TailMatches2("SET", "("))
+ COMPLETE_WITH_LIST2("slot_name", "synchronous_commit");
+ /* ALTER SUBSCRIPTION SET PUBLICATION */
+ else if (HeadMatches3("ALTER", "SUBSCRIPTION", MatchAny) && TailMatches2("SET", "PUBLICATION"))
+ {
+ /* complete with nothing here as this refers to remote publications */
+ }
+ /* ALTER SUBSCRIPTION SET PUBLICATION */
+ else if (HeadMatches3("ALTER", "SUBSCRIPTION", MatchAny) &&
+ TailMatches3("SET", "PUBLICATION", MatchAny))
+ COMPLETE_WITH_CONST("WITH (");
+ /* ALTER SUBSCRIPTION SET PUBLICATION WITH ( */
+ else if (HeadMatches3("ALTER", "SUBSCRIPTION", MatchAny) &&
+ TailMatches5("SET", "PUBLICATION", MatchAny, "WITH", "("))
+ COMPLETE_WITH_LIST2("copy_data", "refresh");
+ /* ALTER SCHEMA */
+ else if (Matches3("ALTER", "SCHEMA", MatchAny))
+ COMPLETE_WITH_LIST2("OWNER TO", "RENAME TO");
+
+ /* ALTER COLLATION */
+ else if (Matches3("ALTER", "COLLATION", MatchAny))
+ COMPLETE_WITH_LIST3("OWNER TO", "RENAME TO", "SET SCHEMA");
+
+ /* ALTER CONVERSION */
+ else if (Matches3("ALTER", "CONVERSION", MatchAny))
+ COMPLETE_WITH_LIST3("OWNER TO", "RENAME TO", "SET SCHEMA");
+
+ /* ALTER DATABASE */
+ else if (Matches3("ALTER", "DATABASE", MatchAny))
+ COMPLETE_WITH_LIST7("RESET", "SET", "OWNER TO", "RENAME TO",
+ "IS_TEMPLATE", "ALLOW_CONNECTIONS",
+ "CONNECTION LIMIT");
+
+ /* ALTER EVENT TRIGGER */
+ else if (Matches3("ALTER", "EVENT", "TRIGGER"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers);
+
+ /* ALTER EVENT TRIGGER */
+ else if (Matches4("ALTER", "EVENT", "TRIGGER", MatchAny))
+ COMPLETE_WITH_LIST4("DISABLE", "ENABLE", "OWNER TO", "RENAME TO");
+
+ /* ALTER EVENT TRIGGER ENABLE */
+ else if (Matches5("ALTER", "EVENT", "TRIGGER", MatchAny, "ENABLE"))
+ COMPLETE_WITH_LIST2("REPLICA", "ALWAYS");
+
+ /* ALTER EXTENSION */
+ else if (Matches3("ALTER", "EXTENSION", MatchAny))
+ COMPLETE_WITH_LIST4("ADD", "DROP", "UPDATE", "SET SCHEMA");
+
+ /* ALTER EXTENSION UPDATE */
+ else if (Matches4("ALTER", "EXTENSION", MatchAny, "UPDATE"))
+ {
+ completion_info_charp = prev2_wd;
+ COMPLETE_WITH_QUERY(Query_for_list_of_available_extension_versions_with_TO);
+ }
+
+ /* ALTER EXTENSION UPDATE TO */
+ else if (Matches5("ALTER", "EXTENSION", MatchAny, "UPDATE", "TO"))
+ {
+ completion_info_charp = prev3_wd;
+ COMPLETE_WITH_QUERY(Query_for_list_of_available_extension_versions);
+ }
+
+ /* ALTER FOREIGN */
+ else if (Matches2("ALTER", "FOREIGN"))
+ COMPLETE_WITH_LIST2("DATA WRAPPER", "TABLE");
+
+ /* ALTER FOREIGN DATA WRAPPER */
+ else if (Matches5("ALTER", "FOREIGN", "DATA", "WRAPPER", MatchAny))
+ COMPLETE_WITH_LIST5("HANDLER", "VALIDATOR", "OPTIONS", "OWNER TO", "RENAME TO");
+
+ /* ALTER FOREIGN TABLE */
+ else if (Matches4("ALTER", "FOREIGN", "TABLE", MatchAny))
+ {
+ static const char *const list_ALTER_FOREIGN_TABLE[] =
+ {"ADD", "ALTER", "DISABLE TRIGGER", "DROP", "ENABLE", "INHERIT",
+ "NO INHERIT", "OPTIONS", "OWNER TO", "RENAME", "SET",
+ "VALIDATE CONSTRAINT", NULL};
+
+ COMPLETE_WITH_LIST(list_ALTER_FOREIGN_TABLE);
+ }
+
+ /* ALTER INDEX */
+ else if (Matches2("ALTER", "INDEX"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes,
+ "UNION SELECT 'ALL IN TABLESPACE'");
+ /* ALTER INDEX */
+ else if (Matches3("ALTER", "INDEX", MatchAny))
+ COMPLETE_WITH_LIST5("ALTER COLUMN", "OWNER TO", "RENAME TO", "SET", "RESET");
+ /* ALTER INDEX ALTER COLUMN */
+ else if (Matches6("ALTER", "INDEX", MatchAny, "ALTER", "COLUMN", MatchAny))
+ COMPLETE_WITH_CONST("SET STATISTICS");
+ /* ALTER INDEX SET */
+ else if (Matches4("ALTER", "INDEX", MatchAny, "SET"))
+ COMPLETE_WITH_LIST2("(", "TABLESPACE");
+ /* ALTER INDEX RESET */
+ else if (Matches4("ALTER", "INDEX", MatchAny, "RESET"))
+ COMPLETE_WITH_CONST("(");
+ /* ALTER INDEX SET|RESET ( */
+ else if (Matches5("ALTER", "INDEX", MatchAny, "RESET", "("))
+ COMPLETE_WITH_LIST3("fillfactor", "fastupdate",
+ "gin_pending_list_limit");
+ else if (Matches5("ALTER", "INDEX", MatchAny, "SET", "("))
+ COMPLETE_WITH_LIST3("fillfactor =", "fastupdate =",
+ "gin_pending_list_limit =");
+
+ /* ALTER LANGUAGE */
+ else if (Matches3("ALTER", "LANGUAGE", MatchAny))
+ COMPLETE_WITH_LIST2("OWNER_TO", "RENAME TO");
+
+ /* ALTER LARGE OBJECT */
+ else if (Matches4("ALTER", "LARGE", "OBJECT", MatchAny))
+ COMPLETE_WITH_CONST("OWNER TO");
+
+ /* ALTER MATERIALIZED VIEW */
+ else if (Matches3("ALTER", "MATERIALIZED", "VIEW"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews,
+ "UNION SELECT 'ALL IN TABLESPACE'");
+
+ /* ALTER USER,ROLE */
+ else if (Matches3("ALTER", "USER|ROLE", MatchAny) &&
+ !TailMatches2("USER", "MAPPING"))
+ {
+ static const char *const list_ALTERUSER[] =
+ {"BYPASSRLS", "CONNECTION LIMIT", "CREATEDB", "CREATEROLE",
+ "ENCRYPTED PASSWORD", "INHERIT", "LOGIN", "NOBYPASSRLS",
+ "NOCREATEDB", "NOCREATEROLE", "NOINHERIT",
+ "NOLOGIN", "NOREPLICATION", "NOSUPERUSER", "PASSWORD", "RENAME TO",
+ "REPLICATION", "RESET", "SET", "SUPERUSER",
+ "VALID UNTIL", "WITH", NULL};
+
+ COMPLETE_WITH_LIST(list_ALTERUSER);
+ }
+
+ /* ALTER USER,ROLE WITH */
+ else if (Matches4("ALTER", "USER|ROLE", MatchAny, "WITH"))
+ {
+ /* Similar to the above, but don't complete "WITH" again. */
+ static const char *const list_ALTERUSER_WITH[] =
+ {"BYPASSRLS", "CONNECTION LIMIT", "CREATEDB", "CREATEROLE",
+ "ENCRYPTED PASSWORD", "INHERIT", "LOGIN", "NOBYPASSRLS",
+ "NOCREATEDB", "NOCREATEROLE", "NOINHERIT",
+ "NOLOGIN", "NOREPLICATION", "NOSUPERUSER", "PASSWORD", "RENAME TO",
+ "REPLICATION", "RESET", "SET", "SUPERUSER",
+ "VALID UNTIL", NULL};
+
+ COMPLETE_WITH_LIST(list_ALTERUSER_WITH);
+ }
+
+ /* ALTER DEFAULT PRIVILEGES */
+ else if (Matches3("ALTER", "DEFAULT", "PRIVILEGES"))
+ COMPLETE_WITH_LIST2("FOR ROLE", "IN SCHEMA");
+ /* ALTER DEFAULT PRIVILEGES FOR */
+ else if (Matches4("ALTER", "DEFAULT", "PRIVILEGES", "FOR"))
+ COMPLETE_WITH_CONST("ROLE");
+ /* ALTER DEFAULT PRIVILEGES IN */
+ else if (Matches4("ALTER", "DEFAULT", "PRIVILEGES", "IN"))
+ COMPLETE_WITH_CONST("SCHEMA");
+ /* ALTER DEFAULT PRIVILEGES FOR ROLE|USER ... */
+ else if (Matches6("ALTER", "DEFAULT", "PRIVILEGES", "FOR", "ROLE|USER",
+ MatchAny))
+ COMPLETE_WITH_LIST3("GRANT", "REVOKE", "IN SCHEMA");
+ /* ALTER DEFAULT PRIVILEGES IN SCHEMA ... */
+ else if (Matches6("ALTER", "DEFAULT", "PRIVILEGES", "IN", "SCHEMA",
+ MatchAny))
+ COMPLETE_WITH_LIST3("GRANT", "REVOKE", "FOR ROLE");
+ /* ALTER DEFAULT PRIVILEGES IN SCHEMA ... FOR */
+ else if (Matches7("ALTER", "DEFAULT", "PRIVILEGES", "IN", "SCHEMA",
+ MatchAny, "FOR"))
+ COMPLETE_WITH_CONST("ROLE");
+ /* ALTER DEFAULT PRIVILEGES FOR ROLE|USER ... IN SCHEMA ... */
+ /* ALTER DEFAULT PRIVILEGES IN SCHEMA ... FOR ROLE|USER ... */
+ else if (Matches9("ALTER", "DEFAULT", "PRIVILEGES", "FOR", "ROLE|USER",
+ MatchAny, "IN", "SCHEMA", MatchAny) ||
+ Matches9("ALTER", "DEFAULT", "PRIVILEGES", "IN", "SCHEMA",
+ MatchAny, "FOR", "ROLE|USER", MatchAny))
+ COMPLETE_WITH_LIST2("GRANT", "REVOKE");
+ /* ALTER DOMAIN */
+ else if (Matches3("ALTER", "DOMAIN", MatchAny))
+ COMPLETE_WITH_LIST6("ADD", "DROP", "OWNER TO", "RENAME", "SET",
+ "VALIDATE CONSTRAINT");
+ /* ALTER DOMAIN DROP */
+ else if (Matches4("ALTER", "DOMAIN", MatchAny, "DROP"))
+ COMPLETE_WITH_LIST3("CONSTRAINT", "DEFAULT", "NOT NULL");
+ /* ALTER DOMAIN DROP|RENAME|VALIDATE CONSTRAINT */
+ else if (Matches5("ALTER", "DOMAIN", MatchAny, "DROP|RENAME|VALIDATE", "CONSTRAINT"))
+ {
+ completion_info_charp = prev3_wd;
+ COMPLETE_WITH_QUERY(Query_for_constraint_of_type);
+ }
+ /* ALTER DOMAIN RENAME */
+ else if (Matches4("ALTER", "DOMAIN", MatchAny, "RENAME"))
+ COMPLETE_WITH_LIST2("CONSTRAINT", "TO");
+ /* ALTER DOMAIN RENAME CONSTRAINT */
+ else if (Matches6("ALTER", "DOMAIN", MatchAny, "RENAME", "CONSTRAINT", MatchAny))
+ COMPLETE_WITH_CONST("TO");
+
+ /* ALTER DOMAIN SET */
+ else if (Matches4("ALTER", "DOMAIN", MatchAny, "SET"))
+ COMPLETE_WITH_LIST3("DEFAULT", "NOT NULL", "SCHEMA");
+ /* ALTER SEQUENCE */
+ else if (Matches3("ALTER", "SEQUENCE", MatchAny))
+ {
+ static const char *const list_ALTERSEQUENCE[] =
+ {"INCREMENT", "MINVALUE", "MAXVALUE", "RESTART", "NO", "CACHE", "CYCLE",
+ "SET SCHEMA", "OWNED BY", "OWNER TO", "RENAME TO", NULL};
+
+ COMPLETE_WITH_LIST(list_ALTERSEQUENCE);
+ }
+ /* ALTER SEQUENCE NO */
+ else if (Matches4("ALTER", "SEQUENCE", MatchAny, "NO"))
+ COMPLETE_WITH_LIST3("MINVALUE", "MAXVALUE", "CYCLE");
+ /* ALTER SERVER */
+ else if (Matches3("ALTER", "SERVER", MatchAny))
+ COMPLETE_WITH_LIST4("VERSION", "OPTIONS", "OWNER TO", "RENAME TO");
+ /* ALTER SERVER VERSION */
+ else if (Matches5("ALTER", "SERVER", MatchAny, "VERSION", MatchAny))
+ COMPLETE_WITH_CONST("OPTIONS");
+ /* ALTER SYSTEM SET, RESET, RESET ALL */
+ else if (Matches2("ALTER", "SYSTEM"))
+ COMPLETE_WITH_LIST2("SET", "RESET");
+ else if (Matches3("ALTER", "SYSTEM", "SET|RESET"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_alter_system_set_vars);
+ else if (Matches4("ALTER", "SYSTEM", "SET", MatchAny))
+ COMPLETE_WITH_CONST("TO");
+ /* ALTER VIEW */
+ else if (Matches3("ALTER", "VIEW", MatchAny))
+ COMPLETE_WITH_LIST4("ALTER COLUMN", "OWNER TO", "RENAME TO",
+ "SET SCHEMA");
+ /* ALTER MATERIALIZED VIEW */
+ else if (Matches4("ALTER", "MATERIALIZED", "VIEW", MatchAny))
+ COMPLETE_WITH_LIST4("ALTER COLUMN", "OWNER TO", "RENAME TO",
+ "SET SCHEMA");
+
+ /* ALTER POLICY */
+ else if (Matches2("ALTER", "POLICY"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_policies);
+ /* ALTER POLICY ON */
+ else if (Matches3("ALTER", "POLICY", MatchAny))
+ COMPLETE_WITH_CONST("ON");
+ /* ALTER POLICY ON
*/
+ else if (Matches4("ALTER", "POLICY", MatchAny, "ON"))
+ {
+ completion_info_charp = prev2_wd;
+ COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_policy);
+ }
+ /* ALTER POLICY ON
- show options */
+ else if (Matches5("ALTER", "POLICY", MatchAny, "ON", MatchAny))
+ COMPLETE_WITH_LIST4("RENAME TO", "TO", "USING (", "WITH CHECK (");
+ /* ALTER POLICY ON
TO */
+ else if (Matches6("ALTER", "POLICY", MatchAny, "ON", MatchAny, "TO"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles);
+ /* ALTER POLICY ON
USING ( */
+ else if (Matches6("ALTER", "POLICY", MatchAny, "ON", MatchAny, "USING"))
+ COMPLETE_WITH_CONST("(");
+ /* ALTER POLICY ON
WITH CHECK ( */
+ else if (Matches7("ALTER", "POLICY", MatchAny, "ON", MatchAny, "WITH", "CHECK"))
+ COMPLETE_WITH_CONST("(");
+
+ /* ALTER RULE , add ON */
+ else if (Matches3("ALTER", "RULE", MatchAny))
+ COMPLETE_WITH_CONST("ON");
+
+ /* If we have ALTER RULE ON, then add the correct tablename */
+ else if (Matches4("ALTER", "RULE", MatchAny, "ON"))
+ {
+ completion_info_charp = prev2_wd;
+ COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_rule);
+ }
+
+ /* ALTER RULE ON */
+ else if (Matches5("ALTER", "RULE", MatchAny, "ON", MatchAny))
+ COMPLETE_WITH_CONST("RENAME TO");
+
+ /* ALTER STATISTICS */
+ else if (Matches3("ALTER", "STATISTICS", MatchAny))
+ COMPLETE_WITH_LIST3("OWNER TO", "RENAME TO", "SET SCHEMA");
+
+ /* ALTER TRIGGER , add ON */
+ else if (Matches3("ALTER", "TRIGGER", MatchAny))
+ COMPLETE_WITH_CONST("ON");
+
+ else if (Matches4("ALTER", "TRIGGER", MatchAny, MatchAny))
+ {
+ completion_info_charp = prev2_wd;
+ COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_trigger);
+ }
+
+ /*
+ * If we have ALTER TRIGGER ON, then add the correct tablename
+ */
+ else if (Matches4("ALTER", "TRIGGER", MatchAny, "ON"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
+
+ /* ALTER TRIGGER ON */
+ else if (Matches5("ALTER", "TRIGGER", MatchAny, "ON", MatchAny))
+ COMPLETE_WITH_CONST("RENAME TO");
+
+ /*
+ * If we detect ALTER TABLE , suggest sub commands
+ */
+ else if (Matches3("ALTER", "TABLE", MatchAny))
+ {
+ static const char *const list_ALTER2[] =
+ {"ADD", "ALTER", "CLUSTER ON", "DISABLE", "DROP", "ENABLE", "INHERIT",
+ "NO INHERIT", "RENAME", "RESET", "OWNER TO", "SET",
+ "VALIDATE CONSTRAINT", "REPLICA IDENTITY", "ATTACH PARTITION",
+ "DETACH PARTITION", NULL};
+
+ COMPLETE_WITH_LIST(list_ALTER2);
+ }
+ /* ALTER TABLE xxx ENABLE */
+ else if (Matches4("ALTER", "TABLE", MatchAny, "ENABLE"))
+ COMPLETE_WITH_LIST5("ALWAYS", "REPLICA", "ROW LEVEL SECURITY", "RULE",
+ "TRIGGER");
+ else if (Matches5("ALTER", "TABLE", MatchAny, "ENABLE", "REPLICA|ALWAYS"))
+ COMPLETE_WITH_LIST2("RULE", "TRIGGER");
+ else if (Matches5("ALTER", "TABLE", MatchAny, "ENABLE", "RULE"))
+ {
+ completion_info_charp = prev3_wd;
+ COMPLETE_WITH_QUERY(Query_for_rule_of_table);
+ }
+ else if (Matches6("ALTER", "TABLE", MatchAny, "ENABLE", MatchAny, "RULE"))
+ {
+ completion_info_charp = prev4_wd;
+ COMPLETE_WITH_QUERY(Query_for_rule_of_table);
+ }
+ else if (Matches5("ALTER", "TABLE", MatchAny, "ENABLE", "TRIGGER"))
+ {
+ completion_info_charp = prev3_wd;
+ COMPLETE_WITH_QUERY(Query_for_trigger_of_table);
+ }
+ else if (Matches6("ALTER", "TABLE", MatchAny, "ENABLE", MatchAny, "TRIGGER"))
+ {
+ completion_info_charp = prev4_wd;
+ COMPLETE_WITH_QUERY(Query_for_trigger_of_table);
+ }
+ /* ALTER TABLE xxx INHERIT */
+ else if (Matches4("ALTER", "TABLE", MatchAny, "INHERIT"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, "");
+ /* ALTER TABLE xxx NO INHERIT */
+ else if (Matches5("ALTER", "TABLE", MatchAny, "NO", "INHERIT"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, "");
+ /* ALTER TABLE xxx DISABLE */
+ else if (Matches4("ALTER", "TABLE", MatchAny, "DISABLE"))
+ COMPLETE_WITH_LIST3("ROW LEVEL SECURITY", "RULE", "TRIGGER");
+ else if (Matches5("ALTER", "TABLE", MatchAny, "DISABLE", "RULE"))
+ {
+ completion_info_charp = prev3_wd;
+ COMPLETE_WITH_QUERY(Query_for_rule_of_table);
+ }
+ else if (Matches5("ALTER", "TABLE", MatchAny, "DISABLE", "TRIGGER"))
+ {
+ completion_info_charp = prev3_wd;
+ COMPLETE_WITH_QUERY(Query_for_trigger_of_table);
+ }
+
+ /* ALTER TABLE xxx ALTER */
+ else if (Matches4("ALTER", "TABLE", MatchAny, "ALTER"))
+ COMPLETE_WITH_ATTR(prev2_wd, " UNION SELECT 'COLUMN' UNION SELECT 'CONSTRAINT'");
+
+ /* ALTER TABLE xxx RENAME */
+ else if (Matches4("ALTER", "TABLE", MatchAny, "RENAME"))
+ COMPLETE_WITH_ATTR(prev2_wd, " UNION SELECT 'COLUMN' UNION SELECT 'CONSTRAINT' UNION SELECT 'TO'");
+ else if (Matches5("ALTER", "TABLE", MatchAny, "ALTER|RENAME", "COLUMN"))
+ COMPLETE_WITH_ATTR(prev3_wd, "");
+
+ /* ALTER TABLE xxx RENAME yyy */
+ else if (Matches5("ALTER", "TABLE", MatchAny, "RENAME", MatchAnyExcept("CONSTRAINT|TO")))
+ COMPLETE_WITH_CONST("TO");
+
+ /* ALTER TABLE xxx RENAME COLUMN/CONSTRAINT yyy */
+ else if (Matches6("ALTER", "TABLE", MatchAny, "RENAME", "COLUMN|CONSTRAINT", MatchAnyExcept("TO")))
+ COMPLETE_WITH_CONST("TO");
+
+ /* If we have ALTER TABLE DROP, provide COLUMN or CONSTRAINT */
+ else if (Matches4("ALTER", "TABLE", MatchAny, "DROP"))
+ COMPLETE_WITH_LIST2("COLUMN", "CONSTRAINT");
+ /* If we have ALTER TABLE DROP COLUMN, provide list of columns */
+ else if (Matches5("ALTER", "TABLE", MatchAny, "DROP", "COLUMN"))
+ COMPLETE_WITH_ATTR(prev3_wd, "");
+
+ /*
+ * If we have ALTER TABLE ALTER|DROP|RENAME|VALIDATE CONSTRAINT,
+ * provide list of constraints
+ */
+ else if (Matches5("ALTER", "TABLE", MatchAny, "ALTER|DROP|RENAME|VALIDATE", "CONSTRAINT"))
+ {
+ completion_info_charp = prev3_wd;
+ COMPLETE_WITH_QUERY(Query_for_constraint_of_table);
+ }
+ /* ALTER TABLE ALTER [COLUMN] */
+ else if (Matches6("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny) ||
+ Matches5("ALTER", "TABLE", MatchAny, "ALTER", MatchAny))
+ COMPLETE_WITH_LIST6("TYPE", "SET", "RESET", "RESTART", "ADD", "DROP");
+ /* ALTER TABLE ALTER [COLUMN] SET */
+ else if (Matches7("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET") ||
+ Matches6("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET"))
+ COMPLETE_WITH_LIST5("(", "DEFAULT", "NOT NULL", "STATISTICS", "STORAGE");
+ /* ALTER TABLE ALTER [COLUMN] SET ( */
+ else if (Matches8("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "(") ||
+ Matches7("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "("))
+ COMPLETE_WITH_LIST2("n_distinct", "n_distinct_inherited");
+ /* ALTER TABLE ALTER [COLUMN] SET STORAGE */
+ else if (Matches8("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "STORAGE") ||
+ Matches7("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "STORAGE"))
+ COMPLETE_WITH_LIST4("PLAIN", "EXTERNAL", "EXTENDED", "MAIN");
+ /* ALTER TABLE ALTER [COLUMN] DROP */
+ else if (Matches7("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "DROP") ||
+ Matches6("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "DROP"))
+ COMPLETE_WITH_LIST3("DEFAULT", "IDENTITY", "NOT NULL");
+ else if (Matches4("ALTER", "TABLE", MatchAny, "CLUSTER"))
+ COMPLETE_WITH_CONST("ON");
+ else if (Matches5("ALTER", "TABLE", MatchAny, "CLUSTER", "ON"))
+ {
+ completion_info_charp = prev3_wd;
+ COMPLETE_WITH_QUERY(Query_for_index_of_table);
+ }
+ /* If we have ALTER TABLE SET, provide list of attributes and '(' */
+ else if (Matches4("ALTER", "TABLE", MatchAny, "SET"))
+ COMPLETE_WITH_LIST7("(", "LOGGED", "SCHEMA", "TABLESPACE", "UNLOGGED",
+ "WITH", "WITHOUT");
+
+ /*
+ * If we have ALTER TABLE SET TABLESPACE provide a list of
+ * tablespaces
+ */
+ else if (Matches5("ALTER", "TABLE", MatchAny, "SET", "TABLESPACE"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
+ /* If we have ALTER TABLE SET WITH provide OIDS */
+ else if (Matches5("ALTER", "TABLE", MatchAny, "SET", "WITH"))
+ COMPLETE_WITH_CONST("OIDS");
+ /* If we have ALTER TABLE SET WITHOUT provide CLUSTER or OIDS */
+ else if (Matches5("ALTER", "TABLE", MatchAny, "SET", "WITHOUT"))
+ COMPLETE_WITH_LIST2("CLUSTER", "OIDS");
+ /* ALTER TABLE RESET */
+ else if (Matches4("ALTER", "TABLE", MatchAny, "RESET"))
+ COMPLETE_WITH_CONST("(");
+ /* ALTER TABLE SET|RESET ( */
+ else if (Matches5("ALTER", "TABLE", MatchAny, "SET|RESET", "("))
+ {
+ static const char *const list_TABLEOPTIONS[] =
+ {
+ "autovacuum_analyze_scale_factor",
+ "autovacuum_analyze_threshold",
+ "autovacuum_enabled",
+ "autovacuum_freeze_max_age",
+ "autovacuum_freeze_min_age",
+ "autovacuum_freeze_table_age",
+ "autovacuum_multixact_freeze_max_age",
+ "autovacuum_multixact_freeze_min_age",
+ "autovacuum_multixact_freeze_table_age",
+ "autovacuum_vacuum_cost_delay",
+ "autovacuum_vacuum_cost_limit",
+ "autovacuum_vacuum_scale_factor",
+ "autovacuum_vacuum_threshold",
+ "fillfactor",
+ "parallel_workers",
+ "log_autovacuum_min_duration",
+ "toast.autovacuum_enabled",
+ "toast.autovacuum_freeze_max_age",
+ "toast.autovacuum_freeze_min_age",
+ "toast.autovacuum_freeze_table_age",
+ "toast.autovacuum_multixact_freeze_max_age",
+ "toast.autovacuum_multixact_freeze_min_age",
+ "toast.autovacuum_multixact_freeze_table_age",
+ "toast.autovacuum_vacuum_cost_delay",
+ "toast.autovacuum_vacuum_cost_limit",
+ "toast.autovacuum_vacuum_scale_factor",
+ "toast.autovacuum_vacuum_threshold",
+ "toast.log_autovacuum_min_duration",
+ "user_catalog_table",
+ NULL
+ };
+
+ COMPLETE_WITH_LIST(list_TABLEOPTIONS);
+ }
+ else if (Matches7("ALTER", "TABLE", MatchAny, "REPLICA", "IDENTITY", "USING", "INDEX"))
+ {
+ completion_info_charp = prev5_wd;
+ COMPLETE_WITH_QUERY(Query_for_index_of_table);
+ }
+ else if (Matches6("ALTER", "TABLE", MatchAny, "REPLICA", "IDENTITY", "USING"))
+ COMPLETE_WITH_CONST("INDEX");
+ else if (Matches5("ALTER", "TABLE", MatchAny, "REPLICA", "IDENTITY"))
+ COMPLETE_WITH_LIST4("FULL", "NOTHING", "DEFAULT", "USING");
+ else if (Matches4("ALTER", "TABLE", MatchAny, "REPLICA"))
+ COMPLETE_WITH_CONST("IDENTITY");
+
+ /*
+ * If we have ALTER TABLE ATTACH PARTITION, provide a list of
+ * tables.
+ */
+ else if (Matches5("ALTER", "TABLE", MatchAny, "ATTACH", "PARTITION"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, "");
+ /* Limited completion support for partition bound specification */
+ else if (TailMatches3("ATTACH", "PARTITION", MatchAny))
+ COMPLETE_WITH_LIST2("FOR VALUES", "DEFAULT");
+ else if (TailMatches2("FOR", "VALUES"))
+ COMPLETE_WITH_LIST2("FROM (", "IN (");
+
+ /*
+ * If we have ALTER TABLE DETACH PARTITION, provide a list of
+ * partitions of .
+ */
+ else if (Matches5("ALTER", "TABLE", MatchAny, "DETACH", "PARTITION"))
+ {
+ completion_info_charp = prev3_wd;
+ COMPLETE_WITH_QUERY(Query_for_partition_of_table);
+ }
+
+ /* ALTER TABLESPACE with RENAME TO, OWNER TO, SET, RESET */
+ else if (Matches3("ALTER", "TABLESPACE", MatchAny))
+ COMPLETE_WITH_LIST4("RENAME TO", "OWNER TO", "SET", "RESET");
+ /* ALTER TABLESPACE SET|RESET */
+ else if (Matches4("ALTER", "TABLESPACE", MatchAny, "SET|RESET"))
+ COMPLETE_WITH_CONST("(");
+ /* ALTER TABLESPACE SET|RESET ( */
+ else if (Matches5("ALTER", "TABLESPACE", MatchAny, "SET|RESET", "("))
+ COMPLETE_WITH_LIST3("seq_page_cost", "random_page_cost",
+ "effective_io_concurrency");
+
+ /* ALTER TEXT SEARCH */
+ else if (Matches3("ALTER", "TEXT", "SEARCH"))
+ COMPLETE_WITH_LIST4("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
+ else if (Matches5("ALTER", "TEXT", "SEARCH", "TEMPLATE|PARSER", MatchAny))
+ COMPLETE_WITH_LIST2("RENAME TO", "SET SCHEMA");
+ else if (Matches5("ALTER", "TEXT", "SEARCH", "DICTIONARY", MatchAny))
+ COMPLETE_WITH_LIST3("OWNER TO", "RENAME TO", "SET SCHEMA");
+ else if (Matches5("ALTER", "TEXT", "SEARCH", "CONFIGURATION", MatchAny))
+ COMPLETE_WITH_LIST6("ADD MAPPING FOR", "ALTER MAPPING",
+ "DROP MAPPING FOR",
+ "OWNER TO", "RENAME TO", "SET SCHEMA");
+
+ /* complete ALTER TYPE with actions */
+ else if (Matches3("ALTER", "TYPE", MatchAny))
+ COMPLETE_WITH_LIST7("ADD ATTRIBUTE", "ADD VALUE", "ALTER ATTRIBUTE",
+ "DROP ATTRIBUTE",
+ "OWNER TO", "RENAME", "SET SCHEMA");
+ /* complete ALTER TYPE ADD with actions */
+ else if (Matches4("ALTER", "TYPE", MatchAny, "ADD"))
+ COMPLETE_WITH_LIST2("ATTRIBUTE", "VALUE");
+ /* ALTER TYPE RENAME */
+ else if (Matches4("ALTER", "TYPE", MatchAny, "RENAME"))
+ COMPLETE_WITH_LIST3("ATTRIBUTE", "TO", "VALUE");
+ /* ALTER TYPE xxx RENAME (ATTRIBUTE|VALUE) yyy */
+ else if (Matches6("ALTER", "TYPE", MatchAny, "RENAME", "ATTRIBUTE|VALUE", MatchAny))
+ COMPLETE_WITH_CONST("TO");
+
+ /*
+ * If we have ALTER TYPE ALTER/DROP/RENAME ATTRIBUTE, provide list
+ * of attributes
+ */
+ else if (Matches5("ALTER", "TYPE", MatchAny, "ALTER|DROP|RENAME", "ATTRIBUTE"))
+ COMPLETE_WITH_ATTR(prev3_wd, "");
+ /* ALTER TYPE ALTER ATTRIBUTE */
+ else if (Matches6("ALTER", "TYPE", MatchAny, "ALTER", "ATTRIBUTE", MatchAny))
+ COMPLETE_WITH_CONST("TYPE");
+ /* complete ALTER GROUP */
+ else if (Matches3("ALTER", "GROUP", MatchAny))
+ COMPLETE_WITH_LIST3("ADD USER", "DROP USER", "RENAME TO");
+ /* complete ALTER GROUP ADD|DROP with USER */
+ else if (Matches4("ALTER", "GROUP", MatchAny, "ADD|DROP"))
+ COMPLETE_WITH_CONST("USER");
+ /* complete ALTER GROUP ADD|DROP USER with a user name */
+ else if (Matches5("ALTER", "GROUP", MatchAny, "ADD|DROP", "USER"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_roles);
+
+ /*
+ * If we have ALTER TYPE RENAME VALUE, provide list of enum values
+ */
+ else if (Matches5("ALTER", "TYPE", MatchAny, "RENAME", "VALUE"))
+ COMPLETE_WITH_ENUM_VALUE(prev3_wd);
+
+/* BEGIN */
+ else if (Matches1("BEGIN"))
+ COMPLETE_WITH_LIST6("WORK", "TRANSACTION", "ISOLATION LEVEL", "READ", "DEFERRABLE", "NOT DEFERRABLE");
+/* END, ABORT */
+ else if (Matches1("END|ABORT"))
+ COMPLETE_WITH_LIST2("WORK", "TRANSACTION");
+/* COMMIT */
+ else if (Matches1("COMMIT"))
+ COMPLETE_WITH_LIST3("WORK", "TRANSACTION", "PREPARED");
+/* RELEASE SAVEPOINT */
+ else if (Matches1("RELEASE"))
+ COMPLETE_WITH_CONST("SAVEPOINT");
+/* ROLLBACK */
+ else if (Matches1("ROLLBACK"))
+ COMPLETE_WITH_LIST4("WORK", "TRANSACTION", "TO SAVEPOINT", "PREPARED");
+/* CLUSTER */
+ else if (Matches1("CLUSTER"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, "UNION SELECT 'VERBOSE'");
+ else if (Matches2("CLUSTER", "VERBOSE"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, NULL);
+ /* If we have CLUSTER , then add "USING" */
+ else if (Matches2("CLUSTER", MatchAnyExcept("VERBOSE|ON")))
+ COMPLETE_WITH_CONST("USING");
+ /* If we have CLUSTER VERBOSE , then add "USING" */
+ else if (Matches3("CLUSTER", "VERBOSE", MatchAny))
+ COMPLETE_WITH_CONST("USING");
+ /* If we have CLUSTER USING, then add the index as well */
+ else if (Matches3("CLUSTER", MatchAny, "USING") ||
+ Matches4("CLUSTER", "VERBOSE", MatchAny, "USING"))
+ {
+ completion_info_charp = prev2_wd;
+ COMPLETE_WITH_QUERY(Query_for_index_of_table);
+ }
+
+/* CLOSE */
+ else if (Matches1("CLOSE"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_cursors);
+
+/* COMMENT */
+ else if (Matches1("COMMENT"))
+ COMPLETE_WITH_CONST("ON");
+ else if (Matches2("COMMENT", "ON"))
+ {
+ static const char *const list_COMMENT[] =
+ {"ACCESS METHOD", "CAST", "COLLATION", "CONVERSION", "DATABASE",
+ "EVENT TRIGGER", "EXTENSION",
+ "FOREIGN DATA WRAPPER", "FOREIGN TABLE",
+ "SERVER", "INDEX", "LANGUAGE", "POLICY", "PUBLICATION", "RULE",
+ "SCHEMA", "SEQUENCE", "STATISTICS", "SUBSCRIPTION",
+ "TABLE", "TYPE", "VIEW", "MATERIALIZED VIEW", "COLUMN", "AGGREGATE", "FUNCTION",
+ "OPERATOR", "TRIGGER", "CONSTRAINT", "DOMAIN", "LARGE OBJECT",
+ "TABLESPACE", "TEXT SEARCH", "ROLE", NULL};
+
+ COMPLETE_WITH_LIST(list_COMMENT);
+ }
+ else if (Matches4("COMMENT", "ON", "ACCESS", "METHOD"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_access_methods);
+ else if (Matches3("COMMENT", "ON", "FOREIGN"))
+ COMPLETE_WITH_LIST2("DATA WRAPPER", "TABLE");
+ else if (Matches4("COMMENT", "ON", "TEXT", "SEARCH"))
+ COMPLETE_WITH_LIST4("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
+ else if (Matches3("COMMENT", "ON", "CONSTRAINT"))
+ COMPLETE_WITH_QUERY(Query_for_all_table_constraints);
+ else if (Matches4("COMMENT", "ON", "CONSTRAINT", MatchAny))
+ COMPLETE_WITH_CONST("ON");
+ else if (Matches5("COMMENT", "ON", "CONSTRAINT", MatchAny, "ON"))
+ {
+ completion_info_charp = prev2_wd;
+ COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_constraint);
+ }
+ else if (Matches4("COMMENT", "ON", "MATERIALIZED", "VIEW"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews, NULL);
+ else if (Matches4("COMMENT", "ON", "EVENT", "TRIGGER"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers);
+ else if (Matches4("COMMENT", "ON", MatchAny, MatchAnyExcept("IS")) ||
+ Matches5("COMMENT", "ON", MatchAny, MatchAny, MatchAnyExcept("IS")) ||
+ Matches6("COMMENT", "ON", MatchAny, MatchAny, MatchAny, MatchAnyExcept("IS")))
+ COMPLETE_WITH_CONST("IS");
+
+/* COPY */
+
+ /*
+ * If we have COPY, offer list of tables or "(" (Also cover the analogous
+ * backslash command).
+ */
+ else if (Matches1("COPY|\\copy"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables,
+ " UNION ALL SELECT '('");
+ /* If we have COPY BINARY, complete with list of tables */
+ else if (Matches2("COPY", "BINARY"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
+ /* If we have COPY (, complete it with legal commands */
+ else if (Matches2("COPY|\\copy", "("))
+ COMPLETE_WITH_LIST7("SELECT", "TABLE", "VALUES", "INSERT", "UPDATE", "DELETE", "WITH");
+ /* If we have COPY [BINARY] , complete it with "TO" or "FROM" */
+ else if (Matches2("COPY|\\copy", MatchAny) ||
+ Matches3("COPY", "BINARY", MatchAny))
+ COMPLETE_WITH_LIST2("FROM", "TO");
+ /* If we have COPY [BINARY] FROM|TO, complete with filename */
+ else if (Matches3("COPY|\\copy", MatchAny, "FROM|TO") ||
+ Matches4("COPY", "BINARY", MatchAny, "FROM|TO"))
+ {
+ completion_charp = "";
+ matches = completion_matches(text, complete_from_files);
+ }
+
+ /* Handle COPY [BINARY] FROM|TO filename */
+ else if (Matches4("COPY|\\copy", MatchAny, "FROM|TO", MatchAny) ||
+ Matches5("COPY", "BINARY", MatchAny, "FROM|TO", MatchAny))
+ COMPLETE_WITH_LIST6("BINARY", "OIDS", "DELIMITER", "NULL", "CSV",
+ "ENCODING");
+
+ /* Handle COPY [BINARY] FROM|TO filename CSV */
+ else if (Matches5("COPY|\\copy", MatchAny, "FROM|TO", MatchAny, "CSV") ||
+ Matches6("COPY", "BINARY", MatchAny, "FROM|TO", MatchAny, "CSV"))
+ COMPLETE_WITH_LIST5("HEADER", "QUOTE", "ESCAPE", "FORCE QUOTE",
+ "FORCE NOT NULL");
+
+ /* CREATE ACCESS METHOD */
+ /* Complete "CREATE ACCESS METHOD " */
+ else if (Matches4("CREATE", "ACCESS", "METHOD", MatchAny))
+ COMPLETE_WITH_CONST("TYPE");
+ /* Complete "CREATE ACCESS METHOD TYPE" */
+ else if (Matches5("CREATE", "ACCESS", "METHOD", MatchAny, "TYPE"))
+ COMPLETE_WITH_CONST("INDEX");
+ /* Complete "CREATE ACCESS METHOD TYPE " */
+ else if (Matches6("CREATE", "ACCESS", "METHOD", MatchAny, "TYPE", MatchAny))
+ COMPLETE_WITH_CONST("HANDLER");
+
+ /* CREATE DATABASE */
+ else if (Matches3("CREATE", "DATABASE", MatchAny))
+ COMPLETE_WITH_LIST10("WITH", "OWNER", "TEMPLATE", "ENCODING", "TABLESPACE",
+ "IS_TEMPLATE",
+ "ALLOW_CONNECTIONS", "CONNECTION LIMIT",
+ "LC_COLLATE", "LC_CTYPE");
+
+ /* CREATE DATABASE WITH */
+ else if (Matches4("CREATE", "DATABASE", MatchAny, "WITH"))
+ COMPLETE_WITH_LIST9("OWNER", "TEMPLATE", "ENCODING", "TABLESPACE",
+ "IS_TEMPLATE",
+ "ALLOW_CONNECTIONS", "CONNECTION LIMIT",
+ "LC_COLLATE", "LC_CTYPE");
+
+ /* CREATE DATABASE WITH OWNER */
+ else if (Matches5("CREATE", "DATABASE", MatchAny, "WITH", "OWNER"))
+ COMPLETE_WITH_LIST8("TEMPLATE", "ENCODING", "TABLESPACE",
+ "IS_TEMPLATE",
+ "ALLOW_CONNECTIONS", "CONNECTION LIMIT",
+ "LC_COLLATE", "LC_CTYPE");
+
+ /* CREATE DATABASE OWNER */
+ else if (Matches4("CREATE", "DATABASE", MatchAny, "OWNER"))
+ COMPLETE_WITH_LIST8("TEMPLATE", "ENCODING", "TABLESPACE",
+ "IS_TEMPLATE",
+ "ALLOW_CONNECTIONS", "CONNECTION LIMIT",
+ "LC_COLLATE", "LC_CTYPE");
+
+ /* CONNECTION LIMIT -- is allowed inside CREATE DATABASE, so use TailMatches */
+ else if (TailMatches2("CONNECTION", "LIMIT"))
+ COMPLETE_WITH_CONST("UNLIMITED");
+
+ else if (Matches4("CREATE", "DATABASE", MatchAny, "TEMPLATE"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_template_databases);
+
+ /* CREATE EXTENSION */
+ /* Complete with available extensions rather than installed ones. */
+ else if (Matches2("CREATE", "EXTENSION"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_available_extensions);
+ /* CREATE EXTENSION */
+ else if (Matches3("CREATE", "EXTENSION", MatchAny))
+ COMPLETE_WITH_LIST3("WITH SCHEMA", "CASCADE", "VERSION");
+ /* CREATE EXTENSION VERSION */
+ else if (Matches4("CREATE", "EXTENSION", MatchAny, "VERSION"))
+ {
+ completion_info_charp = prev2_wd;
+ COMPLETE_WITH_QUERY(Query_for_list_of_available_extension_versions);
+ }
+
+ /* CREATE FOREIGN */
+ else if (Matches2("CREATE", "FOREIGN"))
+ COMPLETE_WITH_LIST2("DATA WRAPPER", "TABLE");
+
+ /* CREATE FOREIGN DATA WRAPPER */
+ else if (Matches5("CREATE", "FOREIGN", "DATA", "WRAPPER", MatchAny))
+ COMPLETE_WITH_LIST3("HANDLER", "VALIDATOR", "OPTIONS");
+
+ /* CREATE INDEX --- is allowed inside CREATE SCHEMA, so use TailMatches */
+ /* First off we complete CREATE UNIQUE with "INDEX" */
+ else if (TailMatches2("CREATE", "UNIQUE"))
+ COMPLETE_WITH_CONST("INDEX");
+
+ /*
+ * If we have CREATE|UNIQUE INDEX, then add "ON", "CONCURRENTLY", and
+ * existing indexes
+ */
+ else if (TailMatches2("CREATE|UNIQUE", "INDEX"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes,
+ " UNION SELECT 'ON'"
+ " UNION SELECT 'CONCURRENTLY'");
+ /* Complete ... INDEX|CONCURRENTLY [] ON with a list of tables */
+ else if (TailMatches3("INDEX|CONCURRENTLY", MatchAny, "ON") ||
+ TailMatches2("INDEX|CONCURRENTLY", "ON"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, NULL);
+
+ /*
+ * Complete CREATE|UNIQUE INDEX CONCURRENTLY with "ON" and existing
+ * indexes
+ */
+ else if (TailMatches3("CREATE|UNIQUE", "INDEX", "CONCURRENTLY"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes,
+ " UNION SELECT 'ON'");
+ /* Complete CREATE|UNIQUE INDEX [CONCURRENTLY] with "ON" */
+ else if (TailMatches3("CREATE|UNIQUE", "INDEX", MatchAny) ||
+ TailMatches4("CREATE|UNIQUE", "INDEX", "CONCURRENTLY", MatchAny))
+ COMPLETE_WITH_CONST("ON");
+
+ /*
+ * Complete INDEX ON
with a list of table columns (which
+ * should really be in parens)
+ */
+ else if (TailMatches4("INDEX", MatchAny, "ON", MatchAny) ||
+ TailMatches3("INDEX|CONCURRENTLY", "ON", MatchAny))
+ COMPLETE_WITH_LIST2("(", "USING");
+ else if (TailMatches5("INDEX", MatchAny, "ON", MatchAny, "(") ||
+ TailMatches4("INDEX|CONCURRENTLY", "ON", MatchAny, "("))
+ COMPLETE_WITH_ATTR(prev2_wd, "");
+ /* same if you put in USING */
+ else if (TailMatches5("ON", MatchAny, "USING", MatchAny, "("))
+ COMPLETE_WITH_ATTR(prev4_wd, "");
+ /* Complete USING with an index method */
+ else if (TailMatches6("INDEX", MatchAny, MatchAny, "ON", MatchAny, "USING") ||
+ TailMatches5("INDEX", MatchAny, "ON", MatchAny, "USING") ||
+ TailMatches4("INDEX", "ON", MatchAny, "USING"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_access_methods);
+ else if (TailMatches4("ON", MatchAny, "USING", MatchAny) &&
+ !TailMatches6("POLICY", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny) &&
+ !TailMatches4("FOR", MatchAny, MatchAny, MatchAny))
+ COMPLETE_WITH_CONST("(");
+
+ // XXX See if you can add Regions here!?
+
+ /* CREATE POLICY */
+ /* Complete "CREATE POLICY ON" */
+ else if (Matches3("CREATE", "POLICY", MatchAny))
+ COMPLETE_WITH_CONST("ON");
+ /* Complete "CREATE POLICY ON
" */
+ else if (Matches4("CREATE", "POLICY", MatchAny, "ON"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
+ /* Complete "CREATE POLICY ON
AS PERMISSIVE|RESTRICTIVE */
+ else if (Matches6("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS"))
+ COMPLETE_WITH_LIST2("PERMISSIVE", "RESTRICTIVE");
+
+ /*
+ * CREATE POLICY ON
AS PERMISSIVE|RESTRICTIVE
+ * FOR|TO|USING|WITH CHECK
+ */
+ else if (Matches7("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny))
+ COMPLETE_WITH_LIST4("FOR", "TO", "USING", "WITH CHECK");
+ /* CREATE POLICY ON
FOR ALL|SELECT|INSERT|UPDATE|DELETE */
+ else if (Matches6("CREATE", "POLICY", MatchAny, "ON", MatchAny, "FOR"))
+ COMPLETE_WITH_LIST5("ALL", "SELECT", "INSERT", "UPDATE", "DELETE");
+ /* Complete "CREATE POLICY ON
FOR INSERT TO|WITH CHECK" */
+ else if (Matches7("CREATE", "POLICY", MatchAny, "ON", MatchAny, "FOR", "INSERT"))
+ COMPLETE_WITH_LIST2("TO", "WITH CHECK (");
+ /* Complete "CREATE POLICY ON
FOR SELECT|DELETE TO|USING" */
+ else if (Matches7("CREATE", "POLICY", MatchAny, "ON", MatchAny, "FOR", "SELECT|DELETE"))
+ COMPLETE_WITH_LIST2("TO", "USING (");
+ /* CREATE POLICY ON
FOR ALL|UPDATE TO|USING|WITH CHECK */
+ else if (Matches7("CREATE", "POLICY", MatchAny, "ON", MatchAny, "FOR", "ALL|UPDATE"))
+ COMPLETE_WITH_LIST3("TO", "USING (", "WITH CHECK (");
+ /* Complete "CREATE POLICY ON
TO " */
+ else if (Matches6("CREATE", "POLICY", MatchAny, "ON", MatchAny, "TO"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles);
+ /* Complete "CREATE POLICY ON
USING (" */
+ else if (Matches6("CREATE", "POLICY", MatchAny, "ON", MatchAny, "USING"))
+ COMPLETE_WITH_CONST("(");
+
+ /*
+ * CREATE POLICY ON
AS PERMISSIVE|RESTRICTIVE FOR
+ * ALL|SELECT|INSERT|UPDATE|DELETE
+ */
+ else if (Matches8("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "FOR"))
+ COMPLETE_WITH_LIST5("ALL", "SELECT", "INSERT", "UPDATE", "DELETE");
+
+ /*
+ * Complete "CREATE POLICY ON
AS PERMISSIVE|RESTRICTIVE FOR
+ * INSERT TO|WITH CHECK"
+ */
+ else if (Matches9("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "FOR", "INSERT"))
+ COMPLETE_WITH_LIST2("TO", "WITH CHECK (");
+
+ /*
+ * Complete "CREATE POLICY ON
AS PERMISSIVE|RESTRICTIVE FOR
+ * SELECT|DELETE TO|USING"
+ */
+ else if (Matches9("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "FOR", "SELECT|DELETE"))
+ COMPLETE_WITH_LIST2("TO", "USING (");
+
+ /*
+ * CREATE POLICY ON
AS PERMISSIVE|RESTRICTIVE FOR
+ * ALL|UPDATE TO|USING|WITH CHECK
+ */
+ else if (Matches9("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "FOR", "ALL|UPDATE"))
+ COMPLETE_WITH_LIST3("TO", "USING (", "WITH CHECK (");
+
+ /*
+ * Complete "CREATE POLICY ON
AS PERMISSIVE|RESTRICTIVE TO
+ * "
+ */
+ else if (Matches8("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "TO"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles);
+
+ /*
+ * Complete "CREATE POLICY ON
AS PERMISSIVE|RESTRICTIVE
+ * USING ("
+ */
+ else if (Matches8("CREATE", "POLICY", MatchAny, "ON", MatchAny, "AS", MatchAny, "USING"))
+ COMPLETE_WITH_CONST("(");
+
+
+/* CREATE PUBLICATION */
+ else if (Matches3("CREATE", "PUBLICATION", MatchAny))
+ COMPLETE_WITH_LIST3("FOR TABLE", "FOR ALL TABLES", "WITH (");
+ else if (Matches4("CREATE", "PUBLICATION", MatchAny, "FOR"))
+ COMPLETE_WITH_LIST2("TABLE", "ALL TABLES");
+ /* Complete "CREATE PUBLICATION FOR TABLE
" */
+ else if (Matches4("CREATE", "PUBLICATION", MatchAny, "FOR TABLE"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
+ /* Complete "CREATE PUBLICATION [...] WITH" */
+ else if (HeadMatches2("CREATE", "PUBLICATION") && TailMatches2("WITH", "("))
+ COMPLETE_WITH_CONST("publish");
+
+/* CREATE RULE */
+ /* Complete "CREATE RULE " with "AS ON" */
+ else if (Matches3("CREATE", "RULE", MatchAny))
+ COMPLETE_WITH_CONST("AS ON");
+ /* Complete "CREATE RULE AS" with "ON" */
+ else if (Matches4("CREATE", "RULE", MatchAny, "AS"))
+ COMPLETE_WITH_CONST("ON");
+ /* Complete "CREATE RULE AS ON" with SELECT|UPDATE|INSERT|DELETE */
+ else if (Matches5("CREATE", "RULE", MatchAny, "AS", "ON"))
+ COMPLETE_WITH_LIST4("SELECT", "UPDATE", "INSERT", "DELETE");
+ /* Complete "AS ON SELECT|UPDATE|INSERT|DELETE" with a "TO" */
+ else if (TailMatches3("AS", "ON", "SELECT|UPDATE|INSERT|DELETE"))
+ COMPLETE_WITH_CONST("TO");
+ /* Complete "AS ON TO" with a table name */
+ else if (TailMatches4("AS", "ON", "SELECT|UPDATE|INSERT|DELETE", "TO"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
+
+/* CREATE SCHEMA */
+ else if (Matches2("CREATE", "SCHEMA"))
+ COMPLETE_WITH_LIST2("AUTHORIZATION", "IF NOT EXISTS");
+ else if (Matches3("CREATE", "SCHEMA", MatchAny))
+ COMPLETE_WITH_CONST("AUTHORIZATION");
+ else if (Matches4("CREATE", "SCHEMA", "IF NOT EXISTS", MatchAny))
+ COMPLETE_WITH_CONST("AUTHORIZATION");
+
+
+/* CREATE SEQUENCE --- is allowed inside CREATE SCHEMA, so use TailMatches */
+ else if (TailMatches3("CREATE", "SEQUENCE", MatchAny) ||
+ TailMatches4("CREATE", "TEMP|TEMPORARY", "SEQUENCE", MatchAny))
+ COMPLETE_WITH_LIST8("INCREMENT BY", "MINVALUE", "MAXVALUE", "NO", "CACHE",
+ "CYCLE", "OWNED BY", "START WITH");
+ else if (TailMatches4("CREATE", "SEQUENCE", MatchAny, "NO") ||
+ TailMatches5("CREATE", "TEMP|TEMPORARY", "SEQUENCE", MatchAny, "NO"))
+ COMPLETE_WITH_LIST3("MINVALUE", "MAXVALUE", "CYCLE");
+
+/* CREATE SERVER */
+ else if (Matches3("CREATE", "SERVER", MatchAny))
+ COMPLETE_WITH_LIST3("TYPE", "VERSION", "FOREIGN DATA WRAPPER");
+
+/* CREATE STATISTICS */
+ else if (Matches3("CREATE", "STATISTICS", MatchAny))
+ COMPLETE_WITH_LIST2("(", "ON");
+ else if (Matches4("CREATE", "STATISTICS", MatchAny, "("))
+ COMPLETE_WITH_LIST2("ndistinct", "dependencies");
+ else if (HeadMatches3("CREATE", "STATISTICS", MatchAny) &&
+ previous_words[0][0] == '(' &&
+ previous_words[0][strlen(previous_words[0]) - 1] == ')')
+ COMPLETE_WITH_CONST("ON");
+ else if (HeadMatches3("CREATE", "STATISTICS", MatchAny) &&
+ TailMatches1("FROM"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
+
+ /* Complete "CREATE TEMP/TEMPORARY" with the possible temp objects */
+ else if (HeadMatches2("CREATE", "TEMP|TEMPORARY"))
+ COMPLETE_WITH_LIST3("SEQUENCE", "TABLE", "VIEW");
+
+ /* Complete "CREATE UNLOGGED" with TABLE or MATVIEW */
+ else if (TailMatches2("CREATE", "UNLOGGED"))
+ COMPLETE_WITH_LIST2("TABLE", "MATERIALIZED VIEW");
+
+ /* CREATE TABLE is allowed inside CREATE SCHEMA in Native Postgres so although
+ we ought to use TailMatches, using HeadMatches since this allows supporting
+ far more options */
+ else if (Matches2("CREATE", "TABLE") ||
+ Matches3("CREATE", "TEMP|TEMPORARY", "TABLE") ||
+ Matches4("CREATE", "LOCAL", "TEMP|TEMPORARY", "TABLE"))
+ COMPLETE_WITH_LIST2("IF NOT EXISTS", "AS");
+
+ else if (Matches3("CREATE", "TABLE", MatchAny))
+ COMPLETE_WITH_CONST("(");
+
+ else if (HeadMatches2("CREATE", "TABLE") /*||
+ HeadMatches3("CREATE", "TEMP|TEMPORARY", "TABLE") ||
+ HeadMatches4("CREATE", "LOCAL", "TEMP|TEMPORARY", "TABLE")*/)
+ {
+ //if (TailMatches3(MatchAnyExcept("("), MatchAny, ")"))
+ if (TailMatches1("BACKUP"))
+ COMPLETE_WITH_LIST2("YES", "NO");
+ else if (TailMatches2("BACKUP", "YES|NO"))
+ COMPLETE_WITH_LIST5("DISTSTYLE", "DISTKEY (", "COMPOUND", "INTERLEAVED", "SORTKEY (");
+ else if (TailMatches1("DISTSTYLE"))
+ COMPLETE_WITH_LIST3("EVEN", "KEY", "ALL");
+ else if (TailMatches2("DISTSTYLE", "EVEN|KEY|ALL"))
+ COMPLETE_WITH_LIST3("COMPOUND", "INTERLEAVED", "SORTKEY (");
+ else if (TailMatches2("DISTKEY", MatchAny))
+ COMPLETE_WITH_LIST3("COMPOUND", "INTERLEAVED", "SORTKEY (");
+ else if (TailMatches1("COMPOUND|INTERLEAVED"))
+ COMPLETE_WITH_CONST("SORTKEY (");
+ else
+ COMPLETE_WITH_LIST6("BACKUP", "DISTSTYLE", "DISTKEY (", "COMPOUND", "INTERLEAVED", "SORTKEY (");
+ }
+
+ /* Complete PARTITION BY with RANGE ( or LIST ( or ... */
+ else if (TailMatches2("PARTITION", "BY"))
+ COMPLETE_WITH_LIST2("RANGE (", "LIST (");
+ /* If we have xxx PARTITION OF, provide a list of partitioned tables */
+ else if (TailMatches2("PARTITION", "OF"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_partitioned_tables, "");
+ /* Limited completion support for partition bound specification */
+ else if (TailMatches3("PARTITION", "OF", MatchAny))
+ COMPLETE_WITH_LIST2("FOR VALUES", "DEFAULT");
+
+/* CREATE TABLESPACE */
+ else if (Matches3("CREATE", "TABLESPACE", MatchAny))
+ COMPLETE_WITH_LIST2("OWNER", "LOCATION");
+ /* Complete CREATE TABLESPACE name OWNER name with "LOCATION" */
+ else if (Matches5("CREATE", "TABLESPACE", MatchAny, "OWNER", MatchAny))
+ COMPLETE_WITH_CONST("LOCATION");
+
+/* CREATE TEXT SEARCH */
+ else if (Matches3("CREATE", "TEXT", "SEARCH"))
+ COMPLETE_WITH_LIST4("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
+ else if (Matches5("CREATE", "TEXT", "SEARCH", "CONFIGURATION", MatchAny))
+ COMPLETE_WITH_CONST("(");
+
+/* CREATE SUBSCRIPTION */
+ else if (Matches3("CREATE", "SUBSCRIPTION", MatchAny))
+ COMPLETE_WITH_CONST("CONNECTION");
+ else if (Matches5("CREATE", "SUBSCRIPTION", MatchAny, "CONNECTION", MatchAny))
+ COMPLETE_WITH_CONST("PUBLICATION");
+ else if (Matches6("CREATE", "SUBSCRIPTION", MatchAny, "CONNECTION",
+ MatchAny, "PUBLICATION"))
+ {
+ /* complete with nothing here as this refers to remote publications */
+ }
+ else if (HeadMatches2("CREATE", "SUBSCRIPTION") && TailMatches2("PUBLICATION", MatchAny))
+ COMPLETE_WITH_CONST("WITH (");
+ /* Complete "CREATE SUBSCRIPTION ... WITH ( " */
+ else if (HeadMatches2("CREATE", "SUBSCRIPTION") && TailMatches2("WITH", "("))
+ COMPLETE_WITH_LIST6("copy_data", "connect", "create_slot", "enabled",
+ "slot_name", "synchronous_commit");
+
+/* CREATE TRIGGER --- is allowed inside CREATE SCHEMA, so use TailMatches */
+ /* complete CREATE TRIGGER with BEFORE,AFTER,INSTEAD OF */
+ else if (TailMatches3("CREATE", "TRIGGER", MatchAny))
+ COMPLETE_WITH_LIST3("BEFORE", "AFTER", "INSTEAD OF");
+ /* complete CREATE TRIGGER BEFORE,AFTER with an event */
+ else if (TailMatches4("CREATE", "TRIGGER", MatchAny, "BEFORE|AFTER"))
+ COMPLETE_WITH_LIST4("INSERT", "DELETE", "UPDATE", "TRUNCATE");
+ /* complete CREATE TRIGGER INSTEAD OF with an event */
+ else if (TailMatches5("CREATE", "TRIGGER", MatchAny, "INSTEAD", "OF"))
+ COMPLETE_WITH_LIST3("INSERT", "DELETE", "UPDATE");
+ /* complete CREATE TRIGGER BEFORE,AFTER sth with OR,ON */
+ else if (TailMatches5("CREATE", "TRIGGER", MatchAny, "BEFORE|AFTER", MatchAny) ||
+ TailMatches6("CREATE", "TRIGGER", MatchAny, "INSTEAD", "OF", MatchAny))
+ COMPLETE_WITH_LIST2("ON", "OR");
+
+ /*
+ * complete CREATE TRIGGER BEFORE,AFTER event ON with a list of
+ * tables
+ */
+ else if (TailMatches6("CREATE", "TRIGGER", MatchAny, "BEFORE|AFTER", MatchAny, "ON"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
+ /* complete CREATE TRIGGER ... INSTEAD OF event ON with a list of views */
+ else if (TailMatches7("CREATE", "TRIGGER", MatchAny, "INSTEAD", "OF", MatchAny, "ON"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views, NULL);
+ else if (HeadMatches2("CREATE", "TRIGGER") && TailMatches2("ON", MatchAny))
+ COMPLETE_WITH_LIST7("NOT DEFERRABLE", "DEFERRABLE", "INITIALLY",
+ "REFERENCING", "FOR", "WHEN (", "EXECUTE PROCEDURE");
+ else if (HeadMatches2("CREATE", "TRIGGER") &&
+ (TailMatches1("DEFERRABLE") || TailMatches2("INITIALLY", "IMMEDIATE|DEFERRED")))
+ COMPLETE_WITH_LIST4("REFERENCING", "FOR", "WHEN (", "EXECUTE PROCEDURE");
+ else if (HeadMatches2("CREATE", "TRIGGER") && TailMatches1("REFERENCING"))
+ COMPLETE_WITH_LIST2("OLD TABLE", "NEW TABLE");
+ else if (HeadMatches2("CREATE", "TRIGGER") && TailMatches2("OLD|NEW", "TABLE"))
+ COMPLETE_WITH_CONST("AS");
+ else if (HeadMatches2("CREATE", "TRIGGER") &&
+ (TailMatches5("REFERENCING", "OLD", "TABLE", "AS", MatchAny) ||
+ TailMatches4("REFERENCING", "OLD", "TABLE", MatchAny)))
+ COMPLETE_WITH_LIST4("NEW TABLE", "FOR", "WHEN (", "EXECUTE PROCEDURE");
+ else if (HeadMatches2("CREATE", "TRIGGER") &&
+ (TailMatches5("REFERENCING", "NEW", "TABLE", "AS", MatchAny) ||
+ TailMatches4("REFERENCING", "NEW", "TABLE", MatchAny)))
+ COMPLETE_WITH_LIST4("OLD TABLE", "FOR", "WHEN (", "EXECUTE PROCEDURE");
+ else if (HeadMatches2("CREATE", "TRIGGER") &&
+ (TailMatches9("REFERENCING", "OLD|NEW", "TABLE", "AS", MatchAny, "OLD|NEW", "TABLE", "AS", MatchAny) ||
+ TailMatches8("REFERENCING", "OLD|NEW", "TABLE", MatchAny, "OLD|NEW", "TABLE", "AS", MatchAny) ||
+ TailMatches8("REFERENCING", "OLD|NEW", "TABLE", "AS", MatchAny, "OLD|NEW", "TABLE", MatchAny) ||
+ TailMatches7("REFERENCING", "OLD|NEW", "TABLE", MatchAny, "OLD|NEW", "TABLE", MatchAny)))
+ COMPLETE_WITH_LIST3("FOR", "WHEN (", "EXECUTE PROCEDURE");
+ else if (HeadMatches2("CREATE", "TRIGGER") && TailMatches1("FOR"))
+ COMPLETE_WITH_LIST3("EACH", "ROW", "STATEMENT");
+ else if (HeadMatches2("CREATE", "TRIGGER") && TailMatches2("FOR", "EACH"))
+ COMPLETE_WITH_LIST2("ROW", "STATEMENT");
+ else if (HeadMatches2("CREATE", "TRIGGER") &&
+ (TailMatches3("FOR", "EACH", "ROW|STATEMENT") ||
+ TailMatches2("FOR", "ROW|STATEMENT")))
+ COMPLETE_WITH_LIST2("WHEN (", "EXECUTE PROCEDURE");
+ /* complete CREATE TRIGGER ... EXECUTE with PROCEDURE */
+ else if (HeadMatches2("CREATE", "TRIGGER") && TailMatches1("EXECUTE"))
+ COMPLETE_WITH_CONST("PROCEDURE");
+ else if (HeadMatches2("CREATE", "TRIGGER") && TailMatches2("EXECUTE", "PROCEDURE"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
+
+/* CREATE ROLE,USER,GROUP */
+ else if (Matches3("CREATE", "ROLE|GROUP|USER", MatchAny) &&
+ !TailMatches2("USER", "MAPPING"))
+ {
+ static const char *const list_CREATEROLE[] =
+ {"ADMIN", "BYPASSRLS", "CONNECTION LIMIT", "CREATEDB", "CREATEROLE", "CREATEUSER",
+ "ENCRYPTED PASSWORD", "IN", "INHERIT", "LOGIN", "NOBYPASSRLS",
+ "NOCREATEDB", "NOCREATEROLE", "NOCREATEUSER", "NOINHERIT",
+ "NOLOGIN", "NOREPLICATION", "NOSUPERUSER", "PASSWORD",
+ "REPLICATION", "ROLE", "SUPERUSER", "SYSID",
+ "VALID UNTIL", "WITH", NULL};
+
+ COMPLETE_WITH_LIST(list_CREATEROLE);
+ }
+
+/* CREATE ROLE,USER,GROUP WITH */
+ else if (Matches4("CREATE", "ROLE|GROUP|USER", MatchAny, "WITH"))
+ {
+ /* Similar to the above, but don't complete "WITH" again. */
+ static const char *const list_CREATEROLE_WITH[] =
+ {"ADMIN", "BYPASSRLS", "CONNECTION LIMIT", "CREATEDB", "CREATEROLE",
+ "ENCRYPTED PASSWORD", "IN", "INHERIT", "LOGIN", "NOBYPASSRLS",
+ "NOCREATEDB", "NOCREATEROLE", "NOINHERIT",
+ "NOLOGIN", "NOREPLICATION", "NOSUPERUSER", "PASSWORD",
+ "REPLICATION", "ROLE", "SUPERUSER", "SYSID",
+ "VALID UNTIL", NULL};
+
+ COMPLETE_WITH_LIST(list_CREATEROLE_WITH);
+ }
+
+ /* complete CREATE ROLE,USER,GROUP IN with ROLE,GROUP */
+ else if (Matches4("CREATE", "ROLE|USER|GROUP", MatchAny, "IN"))
+ COMPLETE_WITH_LIST2("GROUP", "ROLE");
+
+/* CREATE VIEW --- is allowed inside CREATE SCHEMA, so use TailMatches */
+ /* Complete CREATE VIEW with AS */
+ else if (TailMatches3("CREATE", "VIEW", MatchAny))
+ COMPLETE_WITH_CONST("AS");
+ /* Complete "CREATE VIEW AS with "SELECT" */
+ else if (TailMatches4("CREATE", "VIEW", MatchAny, "AS"))
+ COMPLETE_WITH_CONST("SELECT");
+
+/* CREATE MATERIALIZED VIEW */
+ else if (Matches2("CREATE", "MATERIALIZED"))
+ COMPLETE_WITH_CONST("VIEW");
+ /* Complete CREATE MATERIALIZED VIEW with AS */
+ else if (Matches4("CREATE", "MATERIALIZED", "VIEW", MatchAny))
+ COMPLETE_WITH_CONST("AS");
+ /* Complete "CREATE MATERIALIZED VIEW AS with "SELECT" */
+ else if (Matches5("CREATE", "MATERIALIZED", "VIEW", MatchAny, "AS"))
+ COMPLETE_WITH_CONST("SELECT");
+
+/* CREATE EVENT TRIGGER */
+ else if (Matches2("CREATE", "EVENT"))
+ COMPLETE_WITH_CONST("TRIGGER");
+ /* Complete CREATE EVENT TRIGGER with ON */
+ else if (Matches4("CREATE", "EVENT", "TRIGGER", MatchAny))
+ COMPLETE_WITH_CONST("ON");
+ /* Complete CREATE EVENT TRIGGER ON with event_type */
+ else if (Matches5("CREATE", "EVENT", "TRIGGER", MatchAny, "ON"))
+ COMPLETE_WITH_LIST3("ddl_command_start", "ddl_command_end", "sql_drop");
+
+/* DEALLOCATE */
+ else if (Matches1("DEALLOCATE"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_prepared_statements " UNION SELECT 'PREPARE'");
+ else if (Matches2("DEALLOCATE", "PREPARE"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_prepared_statements);
+
+/* DECLARE */
+ else if (Matches2("DECLARE", MatchAny))
+ COMPLETE_WITH_LIST5("BINARY", "INSENSITIVE", "SCROLL", "NO SCROLL",
+ "CURSOR");
+ else if (HeadMatches1("DECLARE") && TailMatches1("CURSOR"))
+ COMPLETE_WITH_LIST3("WITH HOLD", "WITHOUT HOLD", "FOR");
+
+/* DELETE --- can be inside EXPLAIN, RULE, etc */
+ /* ... despite which, only complete DELETE with FROM at start of line */
+ else if (Matches1("DELETE"))
+ COMPLETE_WITH_CONST("FROM");
+ /* Complete DELETE FROM with a list of tables */
+ else if (TailMatches2("DELETE", "FROM"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_updatables, NULL);
+ /* Complete DELETE FROM
*/
+ else if (TailMatches3("DELETE", "FROM", MatchAny))
+ COMPLETE_WITH_LIST2("USING", "WHERE");
+ else if (TailMatches4("DELETE", "FROM", MatchAny, "USING"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
+ else if (TailMatches5("DELETE", "FROM", MatchAny, "USING", MatchAny))
+ COMPLETE_WITH_CONST("WHERE");
+ else if ((TailMatches5("DELETE", MatchAny, "USING", MatchAny, "WHERE")) ||
+ (TailMatches6("DELETE", "FROM", MatchAny, "USING", MatchAny, "WHERE")))
+ COMPLETE_WITH_ATTR(prev2_wd, "");
+ /* XXX: implement tab completion for DELETE ... USING */
+
+/* DISCARD */
+ else if (Matches1("DISCARD"))
+ COMPLETE_WITH_LIST4("ALL", "PLANS", "SEQUENCES", "TEMP");
+
+/* DO */
+ else if (Matches1("DO"))
+ COMPLETE_WITH_CONST("LANGUAGE");
+
+/* DROP */
+ /* Complete DROP object with CASCADE / RESTRICT */
+ else if (Matches3("DROP",
+ "COLLATION|CONVERSION|DOMAIN|EXTENSION|LANGUAGE|PUBLICATION|SCHEMA|SEQUENCE|SERVER|SUBSCRIPTION|STATISTICS|TABLE|TYPE|VIEW",
+ MatchAny) ||
+ Matches4("DROP", "ACCESS", "METHOD", MatchAny) ||
+ (Matches4("DROP", "AGGREGATE|FUNCTION", MatchAny, MatchAny) &&
+ ends_with(prev_wd, ')')) ||
+ Matches4("DROP", "EVENT", "TRIGGER", MatchAny) ||
+ Matches5("DROP", "FOREIGN", "DATA", "WRAPPER", MatchAny) ||
+ Matches4("DROP", "FOREIGN", "TABLE", MatchAny) ||
+ Matches5("DROP", "TEXT", "SEARCH", "CONFIGURATION|DICTIONARY|PARSER|TEMPLATE", MatchAny))
+ COMPLETE_WITH_LIST2("CASCADE", "RESTRICT");
+
+ /* help completing some of the variants */
+ else if (Matches3("DROP", "AGGREGATE|FUNCTION", MatchAny))
+ COMPLETE_WITH_CONST("(");
+ else if (Matches4("DROP", "AGGREGATE|FUNCTION", MatchAny, "("))
+ COMPLETE_WITH_FUNCTION_ARG(prev2_wd);
+ else if (Matches2("DROP", "FOREIGN"))
+ COMPLETE_WITH_LIST2("DATA WRAPPER", "TABLE");
+
+ /* DROP INDEX */
+ else if (Matches2("DROP", "INDEX"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes,
+ " UNION SELECT 'CONCURRENTLY'");
+ else if (Matches3("DROP", "INDEX", "CONCURRENTLY"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes, NULL);
+ else if (Matches3("DROP", "INDEX", MatchAny))
+ COMPLETE_WITH_LIST2("CASCADE", "RESTRICT");
+ else if (Matches4("DROP", "INDEX", "CONCURRENTLY", MatchAny))
+ COMPLETE_WITH_LIST2("CASCADE", "RESTRICT");
+
+ /* DROP MATERIALIZED VIEW */
+ else if (Matches2("DROP", "MATERIALIZED"))
+ COMPLETE_WITH_CONST("VIEW");
+ else if (Matches3("DROP", "MATERIALIZED", "VIEW"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews, NULL);
+
+ /* DROP OWNED BY */
+ else if (Matches2("DROP", "OWNED"))
+ COMPLETE_WITH_CONST("BY");
+ else if (Matches3("DROP", "OWNED", "BY"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_roles);
+
+ /* DROP SCHEMA */
+ else if (Matches2("DROP", "SCHEMA"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_schemas
+ " UNION ALL SELECT 'IF EXISTS'");
+ else if ((Matches3("DROP", "SCHEMA", MatchAny)))
+ COMPLETE_WITH_LIST2("CASCADE", "RESTRICT");
+ else if (Matches4("DROP", "SCHEMA", MatchAny, MatchAny)
+ && TailMatches1(MatchAnyExcept("CASCADE|RESTRICT")))
+ COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
+ else if ((HeadMatches5("DROP", "SCHEMA", MatchAny, MatchAny, MatchAny))
+ && TailMatches1(MatchAnyExcept("EXISTS|CASCADE|RESTRICT")))
+ COMPLETE_WITH_LIST2("CASCADE", "RESTRICT");
+
+ /* DROP TEXT SEARCH */
+ else if (Matches3("DROP", "TEXT", "SEARCH"))
+ COMPLETE_WITH_LIST4("CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE");
+
+ /* DROP TRIGGER */
+ else if (Matches3("DROP", "TRIGGER", MatchAny))
+ COMPLETE_WITH_CONST("ON");
+ else if (Matches4("DROP", "TRIGGER", MatchAny, "ON"))
+ {
+ completion_info_charp = prev2_wd;
+ COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_trigger);
+ }
+ else if (Matches5("DROP", "TRIGGER", MatchAny, "ON", MatchAny))
+ COMPLETE_WITH_LIST2("CASCADE", "RESTRICT");
+
+ /* DROP ACCESS METHOD */
+ else if (Matches2("DROP", "ACCESS"))
+ COMPLETE_WITH_CONST("METHOD");
+ else if (Matches3("DROP", "ACCESS", "METHOD"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_access_methods);
+
+ /* DROP EVENT TRIGGER */
+ else if (Matches2("DROP", "EVENT"))
+ COMPLETE_WITH_CONST("TRIGGER");
+ else if (Matches3("DROP", "EVENT", "TRIGGER"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_event_triggers);
+
+ /* DROP POLICY */
+ else if (Matches2("DROP", "POLICY"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_policies);
+ /* DROP POLICY ON */
+ else if (Matches3("DROP", "POLICY", MatchAny))
+ COMPLETE_WITH_CONST("ON");
+ /* DROP POLICY ON
*/
+ else if (Matches4("DROP", "POLICY", MatchAny, "ON"))
+ {
+ completion_info_charp = prev2_wd;
+ COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_policy);
+ }
+
+ /* DROP RULE */
+ else if (Matches3("DROP", "RULE", MatchAny))
+ COMPLETE_WITH_CONST("ON");
+ else if (Matches4("DROP", "RULE", MatchAny, "ON"))
+ {
+ completion_info_charp = prev2_wd;
+ COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_rule);
+ }
+ else if (Matches5("DROP", "RULE", MatchAny, "ON", MatchAny))
+ COMPLETE_WITH_LIST2("CASCADE", "RESTRICT");
+
+ /* DROP TABLE */
+ else if (Matches2("DROP", "TABLE"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables,
+ " UNION ALL SELECT 'IF EXISTS'");
+ else if ((Matches3("DROP", "TABLE", MatchAny)))
+ COMPLETE_WITH_LIST2("CASCADE", "RESTRICT");
+ else if (Matches4("DROP", "TABLE", MatchAny, MatchAny)
+ && TailMatches1(MatchAnyExcept("CASCADE|RESTRICT")))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
+ else if ((HeadMatches5("DROP", "TABLE", MatchAny, MatchAny, MatchAny))
+ && TailMatches1(MatchAnyExcept("EXISTS|CASCADE|RESTRICT")))
+ COMPLETE_WITH_LIST2("CASCADE", "RESTRICT");
+
+ /* DROP USER */
+ else if (HeadMatches2("DROP", "USER"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_users
+ " UNION ALL SELECT 'IF EXISTS'");
+ else if (HeadMatches4("DROP", "USER", "IF", "EXISTS"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_users);
+
+ /* DROP VIEW */
+ else if (Matches2("DROP", "VIEW"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views,
+ " UNION ALL SELECT 'IF EXISTS'");
+ else if ((Matches3("DROP", "VIEW", MatchAny)))
+ COMPLETE_WITH_LIST2("CASCADE", "RESTRICT");
+ else if (Matches4("DROP", "VIEW", MatchAny, MatchAny)
+ && TailMatches1(MatchAnyExcept("CASCADE|RESTRICT")))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views, NULL);
+ else if ((HeadMatches5("DROP", "VIEW", MatchAny, MatchAny, MatchAny))
+ && TailMatches1(MatchAnyExcept("EXISTS|CASCADE|RESTRICT")))
+ COMPLETE_WITH_LIST2("CASCADE", "RESTRICT");
+
+
+/* EXECUTE */
+ else if (Matches1("EXECUTE"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_prepared_statements);
+
+/* EXPLAIN */
+
+ /*
+ * Complete EXPLAIN [ANALYZE] [VERBOSE] with list of EXPLAIN-able commands
+ */
+ else if (Matches1("EXPLAIN"))
+ COMPLETE_WITH_LIST7("SELECT", "INSERT", "DELETE", "UPDATE", "DECLARE",
+ "ANALYZE", "VERBOSE");
+ else if (Matches2("EXPLAIN", "ANALYZE"))
+ COMPLETE_WITH_LIST6("SELECT", "INSERT", "DELETE", "UPDATE", "DECLARE",
+ "VERBOSE");
+ else if (Matches2("EXPLAIN", "VERBOSE") ||
+ Matches3("EXPLAIN", "ANALYZE", "VERBOSE"))
+ COMPLETE_WITH_LIST5("SELECT", "INSERT", "DELETE", "UPDATE", "DECLARE");
+
+ /* FETCH && MOVE */
+ /* Complete FETCH with one of FORWARD, BACKWARD, RELATIVE */
+ else if (Matches1("FETCH|MOVE"))
+ COMPLETE_WITH_LIST4("ABSOLUTE", "BACKWARD", "FORWARD", "RELATIVE");
+ /* Complete FETCH with one of ALL, NEXT, PRIOR */
+ else if (Matches2("FETCH|MOVE", MatchAny))
+ COMPLETE_WITH_LIST3("ALL", "NEXT", "PRIOR");
+
+ /*
+ * Complete FETCH with "FROM" or "IN". These are equivalent,
+ * but we may as well tab-complete both: perhaps some users prefer one
+ * variant or the other.
+ */
+ else if (Matches3("FETCH|MOVE", MatchAny, MatchAny))
+ COMPLETE_WITH_LIST2("FROM", "IN");
+
+/* FOREIGN DATA WRAPPER */
+ /* applies in ALTER/DROP FDW and in CREATE SERVER */
+ else if (TailMatches3("FOREIGN", "DATA", "WRAPPER") &&
+ !TailMatches4("CREATE", MatchAny, MatchAny, MatchAny))
+ COMPLETE_WITH_QUERY(Query_for_list_of_fdws);
+ /* applies in CREATE SERVER */
+ else if (TailMatches4("FOREIGN", "DATA", "WRAPPER", MatchAny) &&
+ HeadMatches2("CREATE", "SERVER"))
+ COMPLETE_WITH_CONST("OPTIONS");
+
+/* FOREIGN TABLE */
+ else if (TailMatches2("FOREIGN", "TABLE") &&
+ !TailMatches3("CREATE", MatchAny, MatchAny))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_foreign_tables, NULL);
+
+/* FOREIGN SERVER */
+ else if (TailMatches2("FOREIGN", "SERVER"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_servers);
+
+/*
+ * GRANT and REVOKE are allowed inside CREATE SCHEMA and
+ * ALTER DEFAULT PRIVILEGES, so use TailMatches
+ */
+ /* Complete GRANT/REVOKE with a list of roles and privileges */
+ else if (TailMatches1("GRANT|REVOKE"))
+ {
+ /*
+ * With ALTER DEFAULT PRIVILEGES, restrict completion to grantable
+ * privileges (can't grant roles)
+ */
+ if (HeadMatches3("ALTER", "DEFAULT", "PRIVILEGES"))
+ COMPLETE_WITH_LIST10("SELECT", "INSERT", "UPDATE",
+ "DELETE", "TRUNCATE", "REFERENCES", "TRIGGER",
+ "EXECUTE", "USAGE", "ALL");
+ else
+ COMPLETE_WITH_QUERY(Query_for_list_of_roles
+ " UNION SELECT 'SELECT'"
+ " UNION SELECT 'INSERT'"
+ " UNION SELECT 'UPDATE'"
+ " UNION SELECT 'DELETE'"
+ " UNION SELECT 'TRUNCATE'"
+ " UNION SELECT 'REFERENCES'"
+ " UNION SELECT 'TRIGGER'"
+ " UNION SELECT 'CREATE'"
+ " UNION SELECT 'CONNECT'"
+ " UNION SELECT 'TEMPORARY'"
+ " UNION SELECT 'EXECUTE'"
+ " UNION SELECT 'USAGE'"
+ " UNION SELECT 'ALL'");
+ }
+
+ /*
+ * Complete GRANT/REVOKE with "ON", GRANT/REVOKE with
+ * TO/FROM
+ */
+ else if (TailMatches2("GRANT|REVOKE", MatchAny))
+ {
+ if (TailMatches1("SELECT|INSERT|UPDATE|DELETE|TRUNCATE|REFERENCES|TRIGGER|CREATE|CONNECT|TEMPORARY|TEMP|EXECUTE|USAGE|ALL"))
+ COMPLETE_WITH_CONST("ON");
+ else if (TailMatches2("GRANT", MatchAny))
+ COMPLETE_WITH_CONST("TO");
+ else
+ COMPLETE_WITH_CONST("FROM");
+ }
+
+ /*
+ * Complete GRANT/REVOKE ON with a list of tables, views, and
+ * sequences.
+ *
+ * Keywords like DATABASE, FUNCTION, LANGUAGE and SCHEMA added to query
+ * result via UNION; seems to work intuitively.
+ *
+ * Note: GRANT/REVOKE can get quite complex; tab-completion as implemented
+ * here will only work if the privilege list contains exactly one
+ * privilege.
+ */
+ else if (TailMatches3("GRANT|REVOKE", MatchAny, "ON"))
+ {
+ /*
+ * With ALTER DEFAULT PRIVILEGES, restrict completion to the kinds of
+ * objects supported.
+ */
+ if (HeadMatches3("ALTER", "DEFAULT", "PRIVILEGES"))
+ COMPLETE_WITH_LIST5("TABLES", "SEQUENCES", "FUNCTIONS", "TYPES", "SCHEMAS");
+ else
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tsvmf,
+ " UNION SELECT 'ALL FUNCTIONS IN SCHEMA'"
+ " UNION SELECT 'ALL SEQUENCES IN SCHEMA'"
+ " UNION SELECT 'ALL TABLES IN SCHEMA'"
+ " UNION SELECT 'DATABASE'"
+ " UNION SELECT 'DOMAIN'"
+ " UNION SELECT 'FOREIGN DATA WRAPPER'"
+ " UNION SELECT 'FOREIGN SERVER'"
+ " UNION SELECT 'FUNCTION'"
+ " UNION SELECT 'LANGUAGE'"
+ " UNION SELECT 'LARGE OBJECT'"
+ " UNION SELECT 'SCHEMA'"
+ " UNION SELECT 'SEQUENCE'"
+ " UNION SELECT 'TABLE'"
+ " UNION SELECT 'TABLESPACE'"
+ " UNION SELECT 'TYPE'");
+ }
+ else if (TailMatches4("GRANT|REVOKE", MatchAny, "ON", "ALL"))
+ COMPLETE_WITH_LIST3("FUNCTIONS IN SCHEMA", "SEQUENCES IN SCHEMA",
+ "TABLES IN SCHEMA");
+ else if (TailMatches4("GRANT|REVOKE", MatchAny, "ON", "FOREIGN"))
+ COMPLETE_WITH_LIST2("DATA WRAPPER", "SERVER");
+
+ /*
+ * Complete "GRANT/REVOKE * ON DATABASE/DOMAIN/..." with a list of
+ * appropriate objects.
+ *
+ * Complete "GRANT/REVOKE * ON *" with "TO/FROM".
+ */
+ else if (TailMatches4("GRANT|REVOKE", MatchAny, "ON", MatchAny))
+ {
+ if (TailMatches1("DATABASE"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_databases);
+ else if (TailMatches1("DOMAIN"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_domains, NULL);
+ else if (TailMatches1("FUNCTION"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
+ else if (TailMatches1("LANGUAGE"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_languages);
+ else if (TailMatches1("SCHEMA"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
+ else if (TailMatches1("SEQUENCE"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_sequences, NULL);
+ else if (TailMatches1("TABLE"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tsvmf, NULL);
+ else if (TailMatches1("TABLESPACE"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
+ else if (TailMatches1("TYPE"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes, NULL);
+ else if (TailMatches4("GRANT", MatchAny, MatchAny, MatchAny))
+ COMPLETE_WITH_CONST("TO");
+ else
+ COMPLETE_WITH_CONST("FROM");
+ }
+
+ /*
+ * Complete "GRANT/REVOKE ... TO/FROM" with username, PUBLIC,
+ * CURRENT_USER, or SESSION_USER.
+ */
+ else if ((HeadMatches1("GRANT") && TailMatches1("TO")) ||
+ (HeadMatches1("REVOKE") && TailMatches1("FROM")))
+ COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles);
+ /* Complete "ALTER DEFAULT PRIVILEGES ... GRANT/REVOKE ... TO/FROM */
+ else if (HeadMatches3("ALTER", "DEFAULT", "PRIVILEGES") && TailMatches1("TO|FROM"))
+ COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles);
+ /* Complete "GRANT/REVOKE ... ON * *" with TO/FROM */
+ else if (HeadMatches1("GRANT") && TailMatches3("ON", MatchAny, MatchAny))
+ COMPLETE_WITH_CONST("TO");
+ else if (HeadMatches1("REVOKE") && TailMatches3("ON", MatchAny, MatchAny))
+ COMPLETE_WITH_CONST("FROM");
+
+ /* Complete "GRANT/REVOKE * ON ALL * IN SCHEMA *" with TO/FROM */
+ else if (TailMatches8("GRANT|REVOKE", MatchAny, "ON", "ALL", MatchAny, "IN", "SCHEMA", MatchAny))
+ {
+ if (TailMatches8("GRANT", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny, MatchAny, MatchAny))
+ COMPLETE_WITH_CONST("TO");
+ else
+ COMPLETE_WITH_CONST("FROM");
+ }
+
+ /* Complete "GRANT/REVOKE * ON FOREIGN DATA WRAPPER *" with TO/FROM */
+ else if (TailMatches7("GRANT|REVOKE", MatchAny, "ON", "FOREIGN", "DATA", "WRAPPER", MatchAny))
+ {
+ if (TailMatches7("GRANT", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny, MatchAny))
+ COMPLETE_WITH_CONST("TO");
+ else
+ COMPLETE_WITH_CONST("FROM");
+ }
+
+ /* Complete "GRANT/REVOKE * ON FOREIGN SERVER *" with TO/FROM */
+ else if (TailMatches6("GRANT|REVOKE", MatchAny, "ON", "FOREIGN", "SERVER", MatchAny))
+ {
+ if (TailMatches6("GRANT", MatchAny, MatchAny, MatchAny, MatchAny, MatchAny))
+ COMPLETE_WITH_CONST("TO");
+ else
+ COMPLETE_WITH_CONST("FROM");
+ }
+
+/* GROUP BY */
+ else if (TailMatches3("FROM", MatchAny, "GROUP"))
+ COMPLETE_WITH_CONST("BY");
+
+/* IMPORT FOREIGN SCHEMA */
+ else if (Matches1("IMPORT"))
+ COMPLETE_WITH_CONST("FOREIGN SCHEMA");
+ else if (Matches2("IMPORT", "FOREIGN"))
+ COMPLETE_WITH_CONST("SCHEMA");
+
+/* INSERT --- can be inside EXPLAIN, RULE, etc */
+ /* Complete INSERT with "INTO" */
+ else if (TailMatches1("INSERT"))
+ COMPLETE_WITH_CONST("INTO");
+ /* Complete INSERT INTO with table names */
+ else if (TailMatches2("INSERT", "INTO"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_updatables, NULL);
+ /* Complete "INSERT INTO
(" with attribute names */
+ else if (TailMatches4("INSERT", "INTO", MatchAny, "("))
+ COMPLETE_WITH_ATTR(prev2_wd, "");
+
+ /*
+ * Complete INSERT INTO
with "(" or "VALUES" or "SELECT" or
+ * "TABLE" or "DEFAULT VALUES" or "OVERRIDING"
+ */
+ else if (TailMatches3("INSERT", "INTO", MatchAny))
+ COMPLETE_WITH_LIST6("(", "DEFAULT VALUES", "SELECT", "TABLE", "VALUES", "OVERRIDING");
+
+ /*
+ * Complete INSERT INTO
(attribs) with "VALUES" or "SELECT" or
+ * "TABLE" or "OVERRIDING"
+ */
+ else if (TailMatches4("INSERT", "INTO", MatchAny, MatchAny) &&
+ ends_with(prev_wd, ')'))
+ COMPLETE_WITH_LIST4("SELECT", "TABLE", "VALUES", "OVERRIDING");
+
+ /* Complete OVERRIDING */
+ else if (TailMatches1("OVERRIDING"))
+ COMPLETE_WITH_LIST2("SYSTEM VALUE", "USER VALUE");
+
+ /* Complete after OVERRIDING clause */
+ else if (TailMatches3("OVERRIDING", MatchAny, "VALUE"))
+ COMPLETE_WITH_LIST3("SELECT", "TABLE", "VALUES");
+
+ /* Insert an open parenthesis after "VALUES" */
+ else if (TailMatches1("VALUES") && !TailMatches2("DEFAULT", "VALUES"))
+ COMPLETE_WITH_CONST("(");
+
+/* LOCK */
+ /* Complete LOCK [TABLE] with a list of tables */
+ else if (Matches1("LOCK"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables,
+ " UNION SELECT 'TABLE'");
+ else if (Matches2("LOCK", "TABLE"))
+ COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, "");
+
+ /* For the following, handle the case of a single table only for now */
+
+ /* Complete LOCK [TABLE]