[Python-modules-commits] [python-pgspecial] 04/08: Imported Upstream version 1.2.0+20151123
ChangZhuo Chen
czchen at moszumanska.debian.org
Wed Nov 25 11:01:21 UTC 2015
This is an automated email from the git hooks/post-receive script.
czchen pushed a commit to branch master
in repository python-pgspecial.
commit 4e8192ab56ebae6b01c1d1fad6af7aee5c1fbd6f
Author: ChangZhuo Chen (陳昌倬) <czchen at debian.org>
Date: Wed Nov 25 18:35:26 2015 +0800
Imported Upstream version 1.2.0+20151123
---
.gitignore | 108 ++++++++++++++++++++++++++++
.travis.yml | 23 ++++++
DEVELOP.rst | 121 ++++++++++++++++++++++++++++++++
License.txt | 27 +++++++
PKG-INFO | 100 --------------------------
changelog.rst | 28 ++++++++
pgspecial.egg-info/PKG-INFO | 100 --------------------------
pgspecial.egg-info/SOURCES.txt | 15 ----
pgspecial.egg-info/dependency_links.txt | 1 -
pgspecial.egg-info/pbr.json | 1 -
pgspecial.egg-info/requires.txt | 1 -
pgspecial.egg-info/top_level.txt | 1 -
pgspecial/namedqueries.py | 20 +++---
release.py | 113 +++++++++++++++++++++++++++++
requirements-dev.txt | 4 ++
scripts/README.rst | 21 ++++++
scripts/docparser.py | 52 ++++++++++++++
setup.cfg | 5 --
tests/conftest.py | 36 ++++++++++
tests/dbutils.py | 71 +++++++++++++++++++
tests/pytest.ini | 2 +
tests/test_specials.py | 90 ++++++++++++++++++++++++
tox.ini | 7 ++
23 files changed, 713 insertions(+), 234 deletions(-)
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..bbf58a0
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,108 @@
+### Python template
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+env/
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+*.egg-info/
+.installed.cfg
+*.egg
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*,cover
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+target/
+### JetBrains template
+# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio
+
+*.iml
+
+## Directory-based project format:
+.idea/
+# if you remove the above rule, at least ignore the following:
+
+# User-specific stuff:
+# .idea/workspace.xml
+# .idea/tasks.xml
+# .idea/dictionaries
+
+# Sensitive or high-churn files:
+# .idea/dataSources.ids
+# .idea/dataSources.xml
+# .idea/sqlDataSources.xml
+# .idea/dynamic.xml
+# .idea/uiDesigner.xml
+
+# Gradle:
+# .idea/gradle.xml
+# .idea/libraries
+
+# Mongo Explorer plugin:
+# .idea/mongoSettings.xml
+
+## File-based project format:
+*.ipr
+*.iws
+
+## Plugin-specific files:
+
+# IntelliJ
+/out/
+
+# mpeltonen/sbt-idea plugin
+.idea_modules/
+
+# JIRA plugin
+atlassian-ide-plugin.xml
+
+# Crashlytics plugin (for Android Studio and IntelliJ)
+com_crashlytics_export_strings.xml
+crashlytics.properties
+crashlytics-build.properties
+
+# Created by .ignore support plugin (hsz.mobi)
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..5494afc
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,23 @@
+language: python
+python:
+ - "2.6"
+ - "2.7"
+ - "3.3"
+ - "3.4"
+
+install:
+ - pip install . pytest mock codecov psycopg2
+
+script:
+ - coverage run --source pgspecial -m py.test
+
+after_success:
+ - codecov
+
+notifications:
+ webhooks:
+ urls:
+ - YOUR_WEBHOOK_URL
+ on_success: change # options: [always|never|change] default: always
+ on_failure: always # options: [always|never|change] default: always
+ on_start: false # default: false
diff --git a/DEVELOP.rst b/DEVELOP.rst
new file mode 100644
index 0000000..1342f84
--- /dev/null
+++ b/DEVELOP.rst
@@ -0,0 +1,121 @@
+Development Guide
+-----------------
+This is a guide for developers who would like to contribute to this project.
+
+GitHub Workflow
+---------------
+
+If you're interested in contributing to pgcli, first of all my heart felt
+thanks. `Fork the project <https://github.com/dbcli/pgspecial>`_ in github.
+Then clone your fork into your computer (``git clone <url-for-your-fork>``).
+Make the changes and create the commits in your local machine. Then push those
+changes to your fork. Then click on the pull request icon on github and create
+a new pull request. Add a description about the change and send it along. I
+promise to review the pull request in a reasonable window of time and get back
+to you.
+
+In order to keep your fork up to date with any changes from mainline, add a new
+git remote to your local copy called 'upstream' and point it to the main
+``pgspecial`` repo.
+
+::
+
+ $ git remote add upstream git at github.com:dbcli/pgspecial.git
+
+Once the 'upstream' end point is added you can then periodically do a ``git
+pull upstream master`` to update your local copy and then do a ``git push
+origin master`` to keep your own fork up to date.
+
+Local Setup
+-----------
+
+The installation instructions in the README file are intended for users of
+``pgspecial``. If you're developing ``pgspecial``, you'll need to install it in
+a slightly different way so you can see the effects of your changes right away
+without having to go through the install cycle every time you change the code.
+
+It is highly recommended to use virtualenv for development. If you don't know
+what a virtualenv is, this `guide
+<http://docs.python-guide.org/en/latest/dev/virtualenvs/#virtual-environments>`_
+will help you get started.
+
+Create a virtualenv (let's call it ``pgspecial-dev``). Activate it:
+
+::
+
+ virtualenv ./pgspecial-dev
+ source ./pgspecial-dev/bin/activate
+
+Once the virtualenv is activated, `cd` into the local clone of pgspecial folder
+and install pgspecial using pip as follows:
+
+::
+
+ $ pip install --editable .
+
+ or
+
+ $ pip install -e .
+
+This will install the necessary dependencies as well as install pgspecial from
+the working folder into the virtualenv. By installing it using `pip install -e`
+we've linked the pgspecial installation with the working copy. So any changes
+made to the code is immediately available in the installed version of
+pgspecial.
+
+Adding PostgreSQL Special (Meta) Commands
+-----------------------------------------
+
+If you want to add a new meta-command, you'll write a function that accepts 3
+parameters. Then you'll mark it with a ``@special_command`` decorator. For
+an example, look at ``list_roles`` in ``dbcommands.py``:
+
+ ::
+
+ @special_command('\\du', '\\du[+] [pattern]', 'List roles.')
+ def list_roles(cur, pattern, verbose):
+ # some code here
+ return [(None, cur, headers, cur.statusmessage)]
+
+Things to note:
+
+* Your function should return 4 items: ``title, cur, headers, status``.
+* ``title`` is optional. It is something you can print out as first line of your
+ output.
+* ``cur`` is cursor that contains records to iterate.
+* ``headers`` is result table's list of column headers.
+* ``status`` is optional. If provided, it will be printed out last.
+
+Now, take a closer look at the decorator. The first item in a tuple of
+arguments is the command's name. It should be unique. The second item is this
+command's syntax. The third item in the tuple is a string which is
+the documentation for that special command.
+
+The example command here, ``\du``, is a meta-command that lists all roles in
+the databases. The way you can see the SQL statement issued by PostgreSQL when
+this command is executed is to launch `psql -E` and entering ``\du``.
+
+That will print the results and also print the sql statement that was executed
+to produce that result. In most cases it's a single sql statement, but
+sometimes it's a series of sql statements that feed the results to each other
+to get to the final result.
+
+Running the tests
+-----------------
+
+The tests are using default user ``postgres`` at ``localhost``, without
+the password (authentication mode ``trust``). This can be changed in
+``tests/db_utils.py``.
+
+First, install the requirements for testing:
+
+::
+
+ $ pip install -r requirements-dev.txt
+
+After that, tests can be run with:
+
+::
+
+ $ cd tests
+ $ py.test
diff --git a/License.txt b/License.txt
new file mode 100644
index 0000000..087af3a
--- /dev/null
+++ b/License.txt
@@ -0,0 +1,27 @@
+Copyright (c) 2015, dbcli
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+* Neither the name of pgspecial nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/PKG-INFO b/PKG-INFO
deleted file mode 100644
index 2d5f2aa..0000000
--- a/PKG-INFO
+++ /dev/null
@@ -1,100 +0,0 @@
-Metadata-Version: 1.1
-Name: pgspecial
-Version: 1.2.0
-Summary: Meta-commands handler for Postgres Database.
-Home-page: http://pgcli.com
-Author: Amjith Ramanujam
-Author-email: amjith[dot]r[at]gmail.com
-License: LICENSE.txt
-Description: Meta-commands for Postgres
- --------------------------
-
- |BuildStatus| |PyPI|
-
- This package provides an API to execute meta-commands (AKA "special", or
- "backslash commands") on PostgreSQL.
-
- Quick Start
- -----------
-
- This is a python package. It can be installed with:
-
- ::
-
- $ pip install pgspecial
-
-
- Usage
- -----
-
- Once this library is included into your project, you will most likely use the
- following imports:
-
- ::
-
- from pgspecial.main import PGSpecial
- from pgspecial.namedqueries import NamedQueries
-
- Then you will create and use an instance of PGSpecial:
-
- ::
-
- pgspecial = PGSpecial()
- for result in pgspecial.execute(cur, sql):
- # Do something
-
- If you want to import named queries from an existing config file, it is
- convenient to initialize and keep around the class variable in
- ``NamedQueries``:
-
- ::
-
- from configobj import ConfigObj
-
- NamedQueries.instance = NamedQueries.from_config(
- ConfigObj('~/.config_file_name'))
-
- Contributions:
- --------------
-
- If you're interested in contributing to this project, first of all I would like
- to extend my heartfelt gratitude. I've written a small doc to describe how to
- get this running in a development setup.
-
- https://github.com/dbcli/pgspecial/blob/master/DEVELOP.rst
-
- Please feel free to reach out to me if you need help.
- My email: amjith.r at gmail.com, Twitter: `@amjithr <http://twitter.com/amjithr>`_
-
- Projects using it:
- ------------------
-
- This module is being used by pgcli_: A REPL for Postgres.
-
- If you find this module useful and include it in your project, I'll be happy
- to know about it and list it here.
-
- .. |BuildStatus| image:: https://api.travis-ci.org/dbcli/pgspecial.svg?branch=master
- :target: https://travis-ci.org/dbcli/pgspecial
-
- .. |PyPI| image:: https://badge.fury.io/py/pgspecial.svg
- :target: https://pypi.python.org/pypi/pgspecial/
- :alt: Latest Version
-
- .. _pgcli: https://github.com/dbcli/pgcli
-
-Platform: UNKNOWN
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: BSD License
-Classifier: Operating System :: Unix
-Classifier: Programming Language :: Python
-Classifier: Programming Language :: Python :: 2.6
-Classifier: Programming Language :: Python :: 2.7
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3.3
-Classifier: Programming Language :: Python :: 3.4
-Classifier: Programming Language :: SQL
-Classifier: Topic :: Database
-Classifier: Topic :: Database :: Front-Ends
-Classifier: Topic :: Software Development
-Classifier: Topic :: Software Development :: Libraries :: Python Modules
diff --git a/changelog.rst b/changelog.rst
new file mode 100644
index 0000000..261db23
--- /dev/null
+++ b/changelog.rst
@@ -0,0 +1,28 @@
+1.2.0
+=====
+
+Features:
+---------
+
+* Add support for ``\h``. (Thanks: `stuartquin`_)
+ Users can now run ``\h [keyword]`` to checkout the help for a keyboard.
+
+1.1.0
+=====
+
+Features:
+---------
+
+* Support for ``\x auto`` by `stuartquin`_ with `darikg`_ (ported over from `pgcli`_).
+
+1.0.0
+=====
+
+Features:
+---------
+
+* First release as an independent package.
+
+.. _`pgcli`: https://github.com/dbcli/pgcli
+.. _`stuartquin`: https://github.com/stuartquin
+.. _`darikg`: https://github.com/darikg
diff --git a/pgspecial.egg-info/PKG-INFO b/pgspecial.egg-info/PKG-INFO
deleted file mode 100644
index 2d5f2aa..0000000
--- a/pgspecial.egg-info/PKG-INFO
+++ /dev/null
@@ -1,100 +0,0 @@
-Metadata-Version: 1.1
-Name: pgspecial
-Version: 1.2.0
-Summary: Meta-commands handler for Postgres Database.
-Home-page: http://pgcli.com
-Author: Amjith Ramanujam
-Author-email: amjith[dot]r[at]gmail.com
-License: LICENSE.txt
-Description: Meta-commands for Postgres
- --------------------------
-
- |BuildStatus| |PyPI|
-
- This package provides an API to execute meta-commands (AKA "special", or
- "backslash commands") on PostgreSQL.
-
- Quick Start
- -----------
-
- This is a python package. It can be installed with:
-
- ::
-
- $ pip install pgspecial
-
-
- Usage
- -----
-
- Once this library is included into your project, you will most likely use the
- following imports:
-
- ::
-
- from pgspecial.main import PGSpecial
- from pgspecial.namedqueries import NamedQueries
-
- Then you will create and use an instance of PGSpecial:
-
- ::
-
- pgspecial = PGSpecial()
- for result in pgspecial.execute(cur, sql):
- # Do something
-
- If you want to import named queries from an existing config file, it is
- convenient to initialize and keep around the class variable in
- ``NamedQueries``:
-
- ::
-
- from configobj import ConfigObj
-
- NamedQueries.instance = NamedQueries.from_config(
- ConfigObj('~/.config_file_name'))
-
- Contributions:
- --------------
-
- If you're interested in contributing to this project, first of all I would like
- to extend my heartfelt gratitude. I've written a small doc to describe how to
- get this running in a development setup.
-
- https://github.com/dbcli/pgspecial/blob/master/DEVELOP.rst
-
- Please feel free to reach out to me if you need help.
- My email: amjith.r at gmail.com, Twitter: `@amjithr <http://twitter.com/amjithr>`_
-
- Projects using it:
- ------------------
-
- This module is being used by pgcli_: A REPL for Postgres.
-
- If you find this module useful and include it in your project, I'll be happy
- to know about it and list it here.
-
- .. |BuildStatus| image:: https://api.travis-ci.org/dbcli/pgspecial.svg?branch=master
- :target: https://travis-ci.org/dbcli/pgspecial
-
- .. |PyPI| image:: https://badge.fury.io/py/pgspecial.svg
- :target: https://pypi.python.org/pypi/pgspecial/
- :alt: Latest Version
-
- .. _pgcli: https://github.com/dbcli/pgcli
-
-Platform: UNKNOWN
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: BSD License
-Classifier: Operating System :: Unix
-Classifier: Programming Language :: Python
-Classifier: Programming Language :: Python :: 2.6
-Classifier: Programming Language :: Python :: 2.7
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3.3
-Classifier: Programming Language :: Python :: 3.4
-Classifier: Programming Language :: SQL
-Classifier: Topic :: Database
-Classifier: Topic :: Database :: Front-Ends
-Classifier: Topic :: Software Development
-Classifier: Topic :: Software Development :: Libraries :: Python Modules
diff --git a/pgspecial.egg-info/SOURCES.txt b/pgspecial.egg-info/SOURCES.txt
deleted file mode 100644
index 0a1bb52..0000000
--- a/pgspecial.egg-info/SOURCES.txt
+++ /dev/null
@@ -1,15 +0,0 @@
-README.rst
-setup.py
-pgspecial/__init__.py
-pgspecial/dbcommands.py
-pgspecial/iocommands.py
-pgspecial/main.py
-pgspecial/namedqueries.py
-pgspecial.egg-info/PKG-INFO
-pgspecial.egg-info/SOURCES.txt
-pgspecial.egg-info/dependency_links.txt
-pgspecial.egg-info/pbr.json
-pgspecial.egg-info/requires.txt
-pgspecial.egg-info/top_level.txt
-pgspecial/help/__init__.py
-pgspecial/help/commands.py
\ No newline at end of file
diff --git a/pgspecial.egg-info/dependency_links.txt b/pgspecial.egg-info/dependency_links.txt
deleted file mode 100644
index 8b13789..0000000
--- a/pgspecial.egg-info/dependency_links.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/pgspecial.egg-info/pbr.json b/pgspecial.egg-info/pbr.json
deleted file mode 100644
index 14a80e3..0000000
--- a/pgspecial.egg-info/pbr.json
+++ /dev/null
@@ -1 +0,0 @@
-{"is_release": false, "git_version": "4a122da"}
\ No newline at end of file
diff --git a/pgspecial.egg-info/requires.txt b/pgspecial.egg-info/requires.txt
deleted file mode 100644
index e86a836..0000000
--- a/pgspecial.egg-info/requires.txt
+++ /dev/null
@@ -1 +0,0 @@
-click >= 4.1
diff --git a/pgspecial.egg-info/top_level.txt b/pgspecial.egg-info/top_level.txt
deleted file mode 100644
index a8ad873..0000000
--- a/pgspecial.egg-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-pgspecial
diff --git a/pgspecial/namedqueries.py b/pgspecial/namedqueries.py
index 143ca2e..32658eb 100644
--- a/pgspecial/namedqueries.py
+++ b/pgspecial/namedqueries.py
@@ -12,19 +12,19 @@ Examples:
# List all named queries.
> \\n
- ╒════════╤═══════════════════════════════════════╕
- │ Name │ Query │
- ╞════════╪═══════════════════════════════════════╡
- │ simple │ SELECT * FROM abc where a is not NULL │
- ╘════════╧═══════════════════════════════════════╛
+ +--------+----------------------------------------+
+ | Name | Query |
+ |--------+----------------------------------------|
+ | simple | SELECT * FROM xyzb where a is not null |
+ +--------+----------------------------------------+
# Run a named query.
> \\n simple
- ╒════════╤════════╕
- │ a │ b │
- ╞════════╪════════╡
- │ 日本語 │ 日本語 │
- ╘════════╧════════╛
+ +-----+
+ | a |
+ |-----|
+ | 50 |
+ +-----+
# Delete a named query.
> \\nd simple
diff --git a/release.py b/release.py
new file mode 100644
index 0000000..994bc49
--- /dev/null
+++ b/release.py
@@ -0,0 +1,113 @@
+#!/usr/bin/env python
+from __future__ import print_function
+import re
+import ast
+import subprocess
+import sys
+from optparse import OptionParser
+
+DEBUG = False
+CONFIRM_STEPS = False
+DRY_RUN = False
+
+
+def skip_step():
+ """
+ Asks for user's response whether to run a step. Default is yes.
+ :return: boolean
+ """
+ global CONFIRM_STEPS
+
+ if CONFIRM_STEPS:
+ choice = raw_input("--- Confirm step? (y/N) [y] ")
+ if choice.lower() == 'n':
+ return True
+ return False
+
+
+def run_step(*args):
+ """
+ Prints out the command and asks if it should be run.
+ If yes (default), runs it.
+ :param args: list of strings (command and args)
+ """
+ global DRY_RUN
+
+ cmd = args
+ print(' '.join(cmd))
+ if skip_step():
+ print('--- Skipping...')
+ elif DRY_RUN:
+ print('--- Pretending to run...')
+ else:
+ subprocess.check_output(cmd)
+
+
+def version(version_file):
+ _version_re = re.compile(r'__version__\s+=\s+(.*)')
+
+ with open(version_file, 'rb') as f:
+ ver = str(ast.literal_eval(_version_re.search(
+ f.read().decode('utf-8')).group(1)))
+
+ return ver
+
+
+def commit_for_release(version_file, ver):
+ run_step('git', 'reset')
+ run_step('git', 'add', version_file)
+ run_step('git', 'commit', '--message', 'Releasing version %s' % ver)
+
+
+def create_git_tag(tag_name):
+ run_step('git', 'tag', tag_name)
+
+
+def register_with_pypi():
+ run_step('python', 'setup.py', 'register')
+
+
+def create_source_tarball():
+ run_step('python', 'setup.py', 'sdist')
+
+
+def push_to_github():
+ run_step('git', 'push', 'origin', 'master')
+
+
+def push_tags_to_github():
+ run_step('git', 'push', '--tags', 'origin')
+
+
+if __name__ == '__main__':
+ if DEBUG:
+ subprocess.check_output = lambda x: x
+
+ ver = version('pgspecial/__init__.py')
+ print('Releasing Version:', ver)
+
+ parser = OptionParser()
+ parser.add_option(
+ "-c", "--confirm-steps", action="store_true", dest="confirm_steps",
+ default=False, help=("Confirm every step. If the step is not "
+ "confirmed, it will be skipped.")
+ )
+ parser.add_option(
+ "-d", "--dry-run", action="store_true", dest="dry_run",
+ default=False, help="Print out, but not actually run any steps."
+ )
+
+ popts, pargs = parser.parse_args()
+ CONFIRM_STEPS = popts.confirm_steps
+ DRY_RUN = popts.dry_run
+
+ choice = raw_input('Are you sure? (y/N) [n] ')
+ if choice.lower() != 'y':
+ sys.exit(1)
+
+ commit_for_release('pgspecial/__init__.py', ver)
+ create_git_tag('v%s' % ver)
+ register_with_pypi()
+ create_source_tarball()
+ push_to_github()
+ push_tags_to_github()
diff --git a/requirements-dev.txt b/requirements-dev.txt
new file mode 100644
index 0000000..736f093
--- /dev/null
+++ b/requirements-dev.txt
@@ -0,0 +1,4 @@
+pytest >= 2.7.0
+mock >= 1.0.1
+tox >= 1.9.2
+psycopg2 >= 2.5.4
diff --git a/scripts/README.rst b/scripts/README.rst
new file mode 100644
index 0000000..6d96afd
--- /dev/null
+++ b/scripts/README.rst
@@ -0,0 +1,21 @@
+Scripts
+--------------------------
+
+**docparser.py**
+
+Parses SGML files containing Postgres command information and converts them
+into a JSON data structure, this is the converted into a python dictionary
+and saved to `pgspecial/help/commands.py`
+
+This should me manually ran and the results committed after each new release
+of the main Postgres project.
+
+SGML files can be found: https://github.com/postgres/postgres/tree/master/doc/src/sgml/ref
+Grab a copy of this directory on your local system.
+
+**Usage**
+
+::
+ pip install beautifulsoup4
+ # From root of project
+ echo -n "helpcommands = " > pgspecial/help/commands.py; python scripts/docparser.py ref/ | python -mjson.tool | sed 's/"\: null/": None/g' >> pgspecial/help/commands.py
diff --git a/scripts/docparser.py b/scripts/docparser.py
new file mode 100644
index 0000000..fe99ee8
--- /dev/null
+++ b/scripts/docparser.py
@@ -0,0 +1,52 @@
+from bs4 import BeautifulSoup
+import sys
+import os
+import json
+
+
+def get_section(doc, section):
+ element = doc.find(section)
+ if element:
+ return element.get_text()
+
+
+def get_description(doc):
+ text = get_section(doc, "refsect1")
+ if text:
+ lines = filter(lambda x: x.strip(), text.split("\n"))
+
+ if len(lines) > 1 and lines[0] == "Description":
+ return lines[0] + "\n" + lines[1]
+
+
+def parse(file_name):
+ with open(file_name, "r") as file:
+ doc = BeautifulSoup(file.read(), "html.parser")
+ desc = get_description(doc)
+ synopsis = get_section(doc, "synopsis")
+ if desc and synopsis:
+ return {
+ "description": desc,
+ "synopsis": synopsis
+ }
+
+
+if __name__ == "__main__":
+ if len(sys.argv) < 2:
+ print("Parse postgres SGML reference files into JSON")
+ print("Usage:")
+ print("echo -n \"commands = \" > command_help.py; python parser.py ref/ | python -mjson.tool | sed 's/\"\: null/\": None/g' >> command_help.py")
+ print("")
+ sys.exit(0)
+
+ dir = sys.argv[1]
+ docs = {}
+
+ for file_name in os.listdir(dir):
+ if file_name.endswith(".sgml"):
+ path = dir.rstrip("/") + "/" + file_name
+ command = file_name[:-5].replace("_", " ")
+ parsed = parse(path)
+ if parsed:
+ docs[command.upper()] = parsed
+ print(json.dumps(docs))
diff --git a/setup.cfg b/setup.cfg
deleted file mode 100644
index 861a9f5..0000000
--- a/setup.cfg
+++ /dev/null
@@ -1,5 +0,0 @@
-[egg_info]
-tag_build =
-tag_date = 0
-tag_svn_revision = 0
-
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..5de0077
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,36 @@
+import pytest
+from dbutils import (create_db, db_connection, setup_db, teardown_db)
+from pgspecial.main import PGSpecial
+
+
+ at pytest.yield_fixture(scope='module')
+def connection():
+ create_db('_test_db')
+ connection = db_connection('_test_db')
+ setup_db(connection)
+ yield connection
+
+ teardown_db(connection)
+ connection.close()
+
+
+ at pytest.fixture
+def cursor(connection):
+ with connection.cursor() as cur:
+ return cur
+
+
+ at pytest.fixture
+def executor(connection):
+ cur = connection.cursor()
+ pgspecial = PGSpecial()
+
+ def query_runner(sql):
+ results = []
+ for title, rows, headers, status in pgspecial.execute(cur=cur, sql=sql):
+ if rows:
+ results.extend((title, list(rows), headers, status))
+ else:
+ results.extend((title, None, headers, status))
+ return results
+ return query_runner
diff --git a/tests/dbutils.py b/tests/dbutils.py
new file mode 100644
index 0000000..065ae83
--- /dev/null
+++ b/tests/dbutils.py
@@ -0,0 +1,71 @@
+import pytest
+import psycopg2
+import psycopg2.extras
+
+# TODO: should this be somehow be divined from environment?
+POSTGRES_USER, POSTGRES_HOST = 'postgres', 'localhost'
+
+
+def db_connection(dbname=None):
+ conn = psycopg2.connect(user=POSTGRES_USER, host=POSTGRES_HOST,
+ database=dbname)
+ conn.autocommit = True
+ return conn
+
+
+try:
+ conn = db_connection()
+ CAN_CONNECT_TO_DB = True
+ SERVER_VERSION = conn.server_version
+except:
+ CAN_CONNECT_TO_DB = False
+ SERVER_VERSION = 0
+
+
+dbtest = pytest.mark.skipif(
+ not CAN_CONNECT_TO_DB,
+ reason="Need a postgres instance at localhost accessible by user "
+ "'postgres'")
+
+
+def create_db(dbname):
+ with db_connection().cursor() as cur:
+ try:
+ cur.execute('''CREATE DATABASE _test_db''')
+ except:
+ pass
+
+
+def setup_db(conn):
+ with conn.cursor() as cur:
+ # schemas
+ cur.execute('create schema schema1')
+ cur.execute('create schema schema2')
+
+ # tables
+ cur.execute('create table tbl1(id1 integer, txt1 text)')
+ cur.execute('create table tbl2(id2 integer, txt2 text)')
+ cur.execute('create table schema1.s1_tbl1(id1 integer, txt1 text)')
+
+ # views
+ cur.execute('create view vw1 as select * from tbl1')
+ cur.execute('''create view schema1.s1_vw1 as select * from
+ schema1.s1_tbl1''')
+
+ # datatype
+ cur.execute('create type foo AS (a int, b text)')
+
+ # functions
+ cur.execute('''create function func1() returns int language sql as
+ $$select 1$$''')
+ cur.execute('''create function schema1.s1_func1() returns int language
+ sql as $$select 2$$''')
... 127 lines suppressed ...
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/python-pgspecial.git
More information about the Python-modules-commits
mailing list