source: branches/4.x/module/setup.py @ 700

Last change on this file since 700 was 700, checked in by cito, 4 years ago

Use appropriate compiler options with Visual Studio

The MSVC compiler does not recognize some of the GNU compiler options.
So when MSVC is detected, we replace them with equivalent options.

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 7.4 KB
Line 
1#! /usr/bin/python
2# $Id: setup.py 700 2016-01-08 13:18:36Z cito $
3
4"""Setup script for PyGreSQL version 4.2
5
6PyGreSQL is an open-source Python module that interfaces to a
7PostgreSQL database. It embeds the PostgreSQL query library to allow
8easy use of the powerful PostgreSQL features from a Python script.
9
10Authors and history:
11* PyGreSQL written 1997 by D'Arcy J.M. Cain <darcy@druid.net>
12* based on code written 1995 by Pascal Andre <andre@chimay.via.ecp.fr>
13* setup script created 2000/04 Mark Alexander <mwa@gate.net>
14* tweaked 2000/05 Jeremy Hylton <jeremy@cnri.reston.va.us>
15* win32 support 2001/01 by Gerhard Haering <gerhard@bigfoot.de>
16* tweaked 2006/02-2010/02 by Christoph Zwerschke <cito@online.de>
17
18Prerequisites to be installed:
19* Python including devel package (header files and distutils)
20* PostgreSQL libs and devel packages (header file of the libpq client)
21* PostgreSQL pg_config tool (usually included in the devel package)
22  (the Windows installer has it as part of the database server feature)
23
24The supported versions are Python 2.4-2.7 and PostgreSQL 8.3-9.4.
25
26Use as follows:
27python setup.py build   # to build the module
28python setup.py install # to install it
29
30You can use MinGW or MinGW-w64 for building on Windows:
31python setup.py build -c mingw32 install
32
33See docs.python.org/doc/install/ for more information on
34using distutils to install Python programs.
35
36"""
37
38version = '4.2'
39
40
41import sys
42
43if not (2, 4) <= sys.version_info[:2] <= (2, 7):
44    raise Exception("Sorry, PyGreSQL %s"
45        " does not support this Python version" % version)
46
47
48import os
49import platform
50import warnings
51try:
52    from setuptools import setup
53except ImportError:
54    from distutils.core import setup
55from distutils.extension import Extension
56from distutils.command.build_ext import build_ext
57from distutils.ccompiler import get_default_compiler
58from distutils.sysconfig import get_python_inc, get_python_lib
59
60
61def pg_config(s):
62    """Retrieve information about installed version of PostgreSQL."""
63    f = os.popen('pg_config --%s' % s)
64    d = f.readline().strip()
65    if f.close() is not None:
66        raise Exception("pg_config tool is not available.")
67    if not d:
68        raise Exception("Could not get %s information." % s)
69    return d
70
71
72def pg_version():
73    """Return the PostgreSQL version as a tuple of integers."""
74    parts = []
75    for part in pg_config('version').split()[-1].split('.'):
76        if part.isdigit():
77            part = int(part)
78        parts.append(part)
79    return tuple(parts or [8, 3])
80
81
82pg_version = pg_version()
83py_modules = ['pg', 'pgdb']
84libraries = ['pq']
85# Make sure that the Python header files are searched before
86# those of PostgreSQL, because PostgreSQL can have its own Python.h
87include_dirs = [get_python_inc(), pg_config('includedir')]
88library_dirs = [get_python_lib(), pg_config('libdir')]
89define_macros = [('PYGRESQL_VERSION', version)]
90undef_macros = []
91extra_compile_args = ['-O2', '-funsigned-char', '-Wall', '-Werror']
92
93
94class build_pg_ext(build_ext):
95    """Customized build_ext command for PyGreSQL."""
96
97    description = "build the PyGreSQL C extension"
98
99    user_options = build_ext.user_options + [
100        ('direct-access', None,
101            "enable direct access functions"),
102        ('large-objects', None,
103            "enable large object support"),
104        ('default-vars', None,
105            "enable default variables use"),
106        ('escaping-funcs', None,
107            "enable string escaping functions")]
108
109    boolean_options = build_ext.boolean_options + [
110        'direct-access', 'large-objects', 'default-vars', 'escaping-funcs']
111
112    def get_compiler(self):
113        """Return the C compiler used for building the extension."""
114        return self.compiler or get_default_compiler()
115
116    def initialize_options(self):
117        build_ext.initialize_options(self)
118        self.direct_access = True
119        self.large_objects = True
120        self.default_vars = True
121        self.escaping_funcs = pg_version[0] >= 9
122        if pg_version < (8, 3):
123            warnings.warn("PygreSQL does not support this PostgreSQL version.")
124
125    def finalize_options(self):
126        """Set final values for all build_pg options."""
127        build_ext.finalize_options(self)
128        if self.direct_access:
129            define_macros.append(('DIRECT_ACCESS', None))
130        if self.large_objects:
131            define_macros.append(('LARGE_OBJECTS', None))
132        if self.default_vars:
133            define_macros.append(('DEFAULT_VARS', None))
134        if self.escaping_funcs and pg_version[0] >= 9:
135            define_macros.append(('ESCAPING_FUNCS', None))
136        if sys.platform == 'win32':
137            bits = platform.architecture()[0]
138            if bits == '64bit':  # we need to find libpq64
139                for path in os.environ['PATH'].split(os.pathsep) + [
140                        r'C:\Program Files\PostgreSQL\libpq64']:
141                    library_dir = os.path.join(path, 'lib')
142                    if not os.path.isdir(library_dir):
143                        continue
144                    lib = os.path.join(library_dir, 'libpqdll.')
145                    if not (os.path.exists(lib + 'lib')
146                            or os.path.exists(lib + 'a')):
147                        continue
148                    include_dir = os.path.join(path, 'include')
149                    if not os.path.isdir(include_dir):
150                        continue
151                    if library_dir not in library_dirs:
152                        library_dirs.insert(1, library_dir)
153                    if include_dir not in include_dirs:
154                        include_dirs.insert(1, include_dir)
155                    libraries[0] += 'dll'  # libpqdll instead of libpq
156                    break
157            compiler = self.get_compiler()
158            if compiler == 'mingw32':  # MinGW
159                if bits == '64bit':  # needs MinGW-w64
160                    define_macros.append(('MS_WIN64', None))
161            elif compiler == 'msvc':  # Microsoft Visual C++
162                libraries[0] = 'lib' + libraries[0]
163                extra_compile_args[1:] = ['-J', '-W3', '-WX']
164
165
166setup(
167    name="PyGreSQL",
168    version=version,
169    description="Python PostgreSQL Interfaces",
170    long_description=__doc__.split('\n\n', 2)[1],  # first passage
171    keywords="pygresql postgresql database api dbapi",
172    author="D'Arcy J. M. Cain",
173    author_email="darcy@PyGreSQL.org",
174    url="http://www.pygresql.org",
175    download_url="ftp://ftp.pygresql.org/pub/distrib/",
176    platforms=["any"],
177    license="Python",
178    py_modules=py_modules,
179    ext_modules=[Extension('_pg', ['pgmodule.c'],
180        include_dirs=include_dirs, library_dirs=library_dirs,
181        define_macros=define_macros, undef_macros=undef_macros,
182        libraries=libraries, extra_compile_args=extra_compile_args)],
183    zip_safe=False,
184    cmdclass=dict(build_ext=build_pg_ext),
185    test_suite='tests.discover',
186    classifiers=[
187        "Development Status :: 6 - Mature",
188        "Intended Audience :: Developers",
189        "License :: OSI Approved :: Python Software Foundation License",
190        "Operating System :: OS Independent",
191        "Programming Language :: C",
192        'Programming Language :: Python',
193        'Programming Language :: Python :: 2',
194        'Programming Language :: Python :: 2.4',
195        'Programming Language :: Python :: 2.5',
196        'Programming Language :: Python :: 2.6',
197        'Programming Language :: Python :: 2.7',
198        "Programming Language :: SQL",
199        "Topic :: Database",
200        "Topic :: Database :: Front-Ends",
201        "Topic :: Software Development :: Libraries :: Python Modules"]
202)
Note: See TracBrowser for help on using the repository browser.