* Update README

* Completely rewrite setup.py

* Make pytimes the only time implementation, moved into times
This commit is contained in:
adustman
2006-02-28 04:19:27 +00:00
parent b3ce052525
commit 45c9f5d0ed
8 changed files with 274 additions and 366 deletions

View File

@@ -1,50 +0,0 @@
"""Use mx.DateTime to handle date and time columns."""
from time import strftime, localtime
try:
# new packaging
from mx.DateTime import Date, Time, Timestamp, ISO, \
DateTimeType, DateTimeDeltaType
except ImportError:
# old packaging, deprecated
from DateTime import Date, Time, Timestamp, ISO, \
DateTimeType, DateTimeDeltaType
def DateFromTicks(ticks):
"""Convert UNIX ticks into a mx.DateTime.Date."""
return Date(*localtime(ticks)[:3])
def TimeFromTicks(ticks):
"""Convert UNIX ticks into a mx.DateTime.Time."""
return Time(*localtime(ticks)[3:6])
def TimestampFromTicks(ticks):
"""Convert UNIX ticks into a mx.DateTime.Timestamp."""
return Timestamp(*localtime(ticks)[:6])
def format_DATE(d):
"""Format a DateTime object as an ISO date."""
return d.strftime("%Y-%m-%d")
def format_TIME(d):
"""Format a DateTime object as a time value."""
return d.strftime("%d %H:%M:%S")
def format_TIMESTAMP(d):
"""Format a DateTime object as an ISO timestamp."""
return d.strftime("%Y-%m-%d %H:%M:%S")
def DateTime_or_None(s):
try: return ISO.ParseDateTime(s)
except: return None
def TimeDelta_or_None(s):
try: return ISO.ParseTimeDelta(s)
except: return None
Time_or_None = TimeDelta_or_None
def Date_or_None(s):
try: return ISO.ParseDate(s)
except: return None

View File

@@ -1,73 +0,0 @@
"""Use Python datetime module to handle date and time columns."""
# datetime is only in Python 2.3 or newer, so it is safe to use
# string methods.
from time import localtime
from datetime import date, datetime, time, timedelta
Date = date
Time = time
TimeDelta = timedelta
Timestamp = datetime
DateTimeDeltaType = timedelta
DateTimeType = datetime
def DateFromTicks(ticks):
"""Convert UNIX ticks into a date instance."""
return date(*localtime(ticks)[:3])
def TimeFromTicks(ticks):
"""Convert UNIX ticks into a time instance."""
return time(*localtime(ticks)[3:6])
def TimestampFromTicks(ticks):
"""Convert UNIX ticks into a datetime instance."""
return datetime(*localtime(ticks)[:6])
format_TIME = format_DATE = str
def format_TIMESTAMP(d):
return d.strftime("%Y-%m-%d %H:%M:%S")
def DateTime_or_None(s):
if ' ' in s:
sep = ' '
elif 'T' in s:
sep = 'T'
else:
return Date_or_None(s)
try:
d, t = s.split(sep, 1)
return datetime(*[ int(x) for x in d.split('-')+t.split(':') ])
except:
return Date_or_None(s)
def TimeDelta_or_None(s):
from math import modf
try:
h, m, s = s.split(':')
td = timedelta(hours=int(h), minutes=int(m), seconds=int(float(s)),
microseconds=int(modf(float(s))[0]*1000000))
if h < 0:
return -td
else:
return td
except:
return None
def Time_or_None(s):
from math import modf
try:
h, m, s = s.split(':')
return time(hour=int(h), minute=int(m), second=int(float(s)),
microsecond=int(modf(float(s))[0]*1000000))
except:
return None
def Date_or_None(s):
try: return date(*[ int(x) for x in s.split('-',2)])
except: return None

View File

@@ -1,38 +0,0 @@
"""Use strings to handle date and time columns as a last resort."""
from time import strftime, localtime
DateTimeDeltaType = "DateTimeDeltaType"
DateTimeType = "DateTimeType"
def Date(year, month, day):
"""Construct an ISO date string."""
return "%04d-%02d-%02d" % (year, month, day)
def Time(hour, min, sec):
"""Construct a TIME string."""
return "%02d:%02d:%02d" % (hour, min, sec)
def Timestamp(year, month, day, hour, min, sec):
"""Construct an ISO timestamp."""
return "%04d-%02d-%02d %02d:%02d:%02d" % \
(year, month, day, hour, min, sec)
def DateFromTicks(ticks):
"""Convert UNIX ticks to ISO date format."""
return strftime("%Y-%m-%d", localtime(ticks))
def TimeFromTicks(ticks):
"""Convert UNIX ticks to time format."""
return strftime("%H:%M:%S", localtime(ticks))
def TimestampFromTicks(ticks):
"""Convert UNIX ticks to ISO timestamp format."""
return strftime("%Y-%m-%d %H:%M:%S", localtime(ticks))
def format_DATE(d):
"""Format a date as a date (does nothing, you don't have mx.DateTime)"""
return d
format_TIME = format_TIMESTAMP = format_DATE
Time_or_None = TimeDelta_or_None = Date_or_None = DateTime_or_None = format_DATE

View File

@@ -1,20 +1,78 @@
"""times module
This module provides some Date and Time classes for dealing with MySQL data.
"""
Use Python datetime module to handle date and time columns."""
from time import localtime
from datetime import date, datetime, time, timedelta
from _mysql import string_literal
try:
from pytimes import *
Date = date
Time = time
TimeDelta = timedelta
Timestamp = datetime
DateTimeDeltaType = timedelta
DateTimeType = datetime
def DateFromTicks(ticks):
"""Convert UNIX ticks into a date instance."""
return date(*localtime(ticks)[:3])
def TimeFromTicks(ticks):
"""Convert UNIX ticks into a time instance."""
return time(*localtime(ticks)[3:6])
def TimestampFromTicks(ticks):
"""Convert UNIX ticks into a datetime instance."""
return datetime(*localtime(ticks)[:6])
format_TIME = format_DATE = str
def format_TIMESTAMP(d):
return d.strftime("%Y-%m-%d %H:%M:%S")
def DateTime_or_None(s):
if ' ' in s:
sep = ' '
elif 'T' in s:
sep = 'T'
else:
return Date_or_None(s)
except ImportError:
try:
from mxdatetimes import *
d, t = s.split(sep, 1)
return datetime(*[ int(x) for x in d.split('-')+t.split(':') ])
except:
return Date_or_None(s)
except ImportError:
# no DateTime? We'll muddle through somehow.
from stringtimes import *
def TimeDelta_or_None(s):
from math import modf
try:
h, m, s = s.split(':')
td = timedelta(hours=int(h), minutes=int(m), seconds=int(float(s)),
microseconds=int(modf(float(s))[0]*1000000))
if h < 0:
return -td
else:
return td
except:
return None
def Time_or_None(s):
from math import modf
try:
h, m, s = s.split(':')
return time(hour=int(h), minute=int(m), second=int(float(s)),
microsecond=int(modf(float(s))[0]*1000000))
except:
return None
def Date_or_None(s):
try: return date(*[ int(x) for x in s.split('-',2)])
except: return None
def DateTime2literal(d, c):
"""Format a DateTime object as an ISO timestamp."""

View File

@@ -2,7 +2,8 @@
MySQLdb Installation
====================
.. contents::
..
Prerequisites
-------------
@@ -11,12 +12,10 @@ Prerequisites
* http://www.python.org/
* Versions lower than 2.2 WON'T WORK.
* 2.2.x MIGHT work, or have partial functionality.
* 2.4 is tested and works.
* Versions lower than 2.3 WON'T WORK.
* 2.4 is the primary test environment.
* Red Hat Linux:
- Make sure you have the Python development headers and libraries
@@ -30,17 +29,16 @@ Prerequisites
* Versions lower than 3.22.19 might not work.
* MySQL-3.22 is deprecated in favor of 3.23, but still supported.
* MySQL-3.22 might work but isn't supported anymore. It's very old.
* MySQL-3.23 is supported, but slightly deprecated.
* MySQL-3.23 ought to work, but it's pretty elderly.
* MySQL-4.0 is supported.
* MySQL-4.0 is supported, but not tested and slightly discouraged.
* MySQL-4.1 is mostly supported; the new prepared statements API
is not yet supported, and probably won't be until MySQLdb-1.3 or
2.0.
* MySQL-4.1 is supported and tested. The prepared statements API is not
supported, and won't be until MySQLdb-1.3 or 2.0.
* MySQL-5.0 and newer are not currently supported, but might work.
* MySQL-5.0 is supported and tested, including stored procedures.
* MaxDB, formerly known as SAP DB (and maybe Adabas D?), is a
completely different animal. Use the sapdb.sql module that comes
@@ -64,10 +62,7 @@ Prerequisites
* Transactions (particularly InnoDB tables) are supported for
MySQL-3.23 and up. You may need a special package from your vendor
with this support turned on. If you have Gentoo Linux, set either
of the berkdb or innodb USE flags on your server, and comment out
"skip-innodb" in /etc/mysql/my.cnf for InnoDB table support.
with this support turned on.
+ zlib
@@ -82,7 +77,9 @@ Prerequisites
+ openssl
* May be needed for MySQL-4.0 or newer, depending on compilation
options.
options. If you need it, you probably already have it.
- you may need openssl-devel on some platforms
+ C compiler
@@ -106,39 +103,34 @@ options, and should work as is on any POSIX-like platform, so long as
mysql_config is in your path.
Depending on which version of MySQL you have, you may have the option
of using three different client libraries:
of using three different client libraries. To select the client library,
edit the [options] section of site.cfg:
mysqlclient
mostly but not guaranteed thread-safe
embedded
use embedded server library (libmysqld) if True; otherwise use
one of the client libraries (default).
mysqlclient_r
thread-safe, use if you can
threadsafe
thread-safe client library (libmysqlclient_r) if True (default);
otherwise use non-thread-safe (libmysqlclient). You should
always use the thread-safe library if you have the option;
otherwise you *may* have problems.
mysqld
embedded server
mysqlclient_r is used by default. To use one of the others, set
the environment variable mysqlclient to the name of the library
you want to use. In a Bourne-style shell, use::
$ export mysqlclient=mysqlclient
Only do this if you don't have the thread-safe library (mysqlclient_r)
or you want to use the embedded server (mysqld).
static
if True, try to link against a static library; otherwise link
against dynamic libraries (default). You may need static linking
to use the embedded server.
Finally, putting it together::
$ tar xfz MySQL-python-1.2.0.tar.gz
$ cd MySQL-python-1.2.0
$ tar xfz MySQL-python-1.2.1.tar.gz
$ cd MySQL-python-1.2.1
$ # edit site.cfg if necessary
$ python setup.py build
$ su # or use sudo
# python setup.py install
$ sudo python setup.py install # or su first
NOTE: You must export environment variables for setup.py to see them.
Depending on what shell you prefer, you may need to use "export" or
"set -x" (bash and other Bourne-like shells) or "setenv" (csh-like
shells).
Windows
.......
@@ -158,6 +150,10 @@ which is the path to your MySQL installation. In theory, it would be
possible to get this information out of the registry, but like I said,
I don't do Windows, but I'll accept a patch that does this.
On Windows, you will definitely have to edit site.cfg since there is
no mysql_config in the MySQL package.
Zope
....
@@ -166,12 +162,6 @@ the python executable that came with Zope. Otherwise, you'll install
into the wrong Python tree and Zope (ZMySQLDA) will not be able to
find _mysql.
With zope.org's Zope-2.5.1-linux2-x86 binary tarball, you'd do
something like this::
$ export ZOPEBIN=".../Zope-2.5.1-linux2-x86/bin" # wherever you unpacked it
$ $ZOPEBIN/python setup.py install # builds and installs
Binary Packages
---------------
@@ -187,17 +177,18 @@ RPMs
If you prefer to install RPMs, you can use the bdist_rpm command with
setup.py. This only builds the RPM; it does not install it. You may
want to use the --python=XXX option, where XXX is the name of the
Python executable, i.e. python, python2, python2.1; the default is
Python executable, i.e. python, python2, python2.4; the default is
python. Using this will incorporate the Python executable name into
the package name for the RPM so you have install the package multiple
times if you need to support more than one version of Python.
times if you need to support more than one version of Python. You can
also set this in setup.cfg.
Red Hat Linux
.............
MySQL-python is pre-packaged in Red Hat Linux 7.x and newer. This
likely includes Fedora Core and Red Hat Enterprise Linux. You can also
includes Fedora Core and Red Hat Enterprise Linux. You can also
build your own RPM packages as described above.
@@ -208,13 +199,22 @@ Packaged as `python-mysqldb`_::
# apt-get install python-mysqldb
Or use Synaptic.
.. _`python-mysqldb`: http://packages.debian.org/python-mysqldb
Ubuntu
......
Same as with Debian.
Gentoo Linux
............
Packaged as `mysql-python`_. Gentoo is also my development platform::
Packaged as `mysql-python`_. Gentoo is also my preferred development platform,
though I have also done some with Ubuntu lately. ::
# emerge sync
# emerge mysql-python

58
MySQLdb/metadata.cfg Normal file
View File

@@ -0,0 +1,58 @@
[metadata]
version: 1.2.1c4
description: Python interface to MySQL
long_description:
=========================
Python interface to MySQL
=========================
MySQLdb is an interface to the popular MySQL_ database server for
Python. The design goals are:
- Compliance with Python database API version 2.0 [PEP-0249]_
- Thread-safety
- Thread-friendliness (threads will not block each other)
MySQL-3.23 through 5.0 and Python-2.3 through 2.4 are currently
supported.
MySQLdb is `Free Software`_.
.. _MySQL: http://www.mysql.com/
.. _`Free Software`: http://www.gnu.org/
.. [PEP-0249] http://www.python.org/peps/pep-0249.html
author: Andy Dustman
author_email: andy@dustman.net
license: GPL
platforms: ALL
url: http://sourceforge.net/projects/mysql-python
download_url: http://prdownloads.sourceforge.net/mysql-python/MySQL-python-%(version)s.tar.gz
classifiers:
Development Status :: 5 - Production/Stable
Environment :: Other Environment
License :: OSI Approved :: GNU General Public License (GPL)
Operating System :: MacOS :: MacOS X
Operating System :: Microsoft :: Windows :: Windows NT/2000
Operating System :: OS Independent
Operating System :: POSIX
Operating System :: POSIX :: Linux
Operating System :: Unix
Programming Language :: C
Programming Language :: Python
Topic :: Database
Topic :: Database :: Database Engines/Servers
py_modules:
_mysql_exceptions
MySQLdb.converters
MySQLdb.connections
MySQLdb.cursors
MySQLdb.times
MySQLdb.constants.CR
MySQLdb.constants.FIELD_TYPE
MySQLdb.constants.ER
MySQLdb.constants.FLAG
MySQLdb.constants.REFRESH
MySQLdb.constants.CLIENT

View File

@@ -1,161 +1,86 @@
#!/usr/bin/env python
"""\
=========================
Python interface to MySQL
=========================
MySQLdb is an interface to the popular MySQL_ database server for
Python. The design goals are:
- Compliance with Python database API version 2.0 [PEP-0249]_
- Thread-safety
- Thread-friendliness (threads will not block each other)
MySQL-3.22 through 4.1 and Python-2.3 through 2.4 are currently
supported.
MySQLdb is `Free Software`_.
.. _MySQL: http://www.mysql.com/
.. _`Free Software`: http://www.gnu.org/
.. [PEP-0249] http://www.python.org/peps/pep-0249.html
"""
class Abort(Exception): pass
import os
import sys
from distutils.core import setup
from distutils.extension import Extension
from ConfigParser import SafeConfigParser
mysqlclient = os.getenv('mysqlclient', 'mysqlclient_r')
mysqlstatic = eval(os.getenv('mysqlstatic', 'False'))
embedded_server = (mysqlclient == 'mysqld')
if sys.version_info < (2, 3):
raise Abort, "Python-2.3 or newer is required"
name = "MySQL-%s" % os.path.basename(sys.executable)
if embedded_server:
name = name + "-embedded"
version = "1.2.1c3"
config = SafeConfigParser()
config.read(['metadata.cfg', 'site.cfg'])
metadata = dict(config.items('metadata'))
options = dict(config.items('options'))
metadata['py_modules'] = filter(None, metadata['py_modules'].split())
metadata['classifiers'] = filter(None, metadata['classifiers'].split())
def mysql_config(what):
from os import popen
f = popen("mysql_config --%s" % what)
data = f.read().strip().split()
if f.close(): data = []
return data
# This dequote() business is required for some older versions
# of mysql_config
def dequote(s):
if (s[0] == "'" or s[0] == '"') and (s[0] == s[-1]):
s = s[1:-1]
return s
def enabled(option):
value = options[option]
s = value.lower()
if s in ('yes','true','1','y'):
return True
elif s in ('no', 'false', '0', 'n'):
return False
else:
raise Abort, "Unknown value %s for option %s" % (value, option)
include_dirs = [ dequote(i[2:])
for i in mysql_config('include')
if i.startswith('-i') ]
extra_objects = []
if sys.platform == "win32":
mysqlroot = os.getenv('mysqlroot', None)
if mysqlroot is None:
print "You need to set the environment variable mysqlroot!"
print "This should be the path to your MySQL installation."
print "Probably C:\Program Files\MySQL 4.1\ or something like that."
sys.exit(1)
include_dirs = [os.path.join(mysqlroot, "include")]
library_dirs = [os.path.join(mysqlroot, "libs")]
libraries = ['zlib', 'msvcrt', 'libcmt', 'wsock32', 'advapi32']
if mysqlstatic:
extra_objects.append(os.path.join(
library_dirs[0], mysqlclient+'.lib'))
else:
libraries.append(mysqlclient)
static = enabled('static')
if enabled('embedded'):
libs = mysql_config("libmysqld_libs")
client = "mysqld"
elif enabled('threadsafe'):
libs = mysql_config("libs_r")
client = "mysqlclient_r"
else:
def config(what):
from os import popen
f = popen("mysql_config --%s" % what)
data = f.read().strip().split()
if f.close(): data = []
return data
libs = mysql_config("libs")
client = "mysqlclient"
# This dequote() business is required for some older versions
# of mysql_config
def dequote(s):
if (s[0] == "'" or s[0] == '"') and (s[0] == s[-1]):
s = s[1:-1]
return s
include_dirs = [ dequote(i[2:]) for i in config('include') if i.startswith('-i') ]
library_dirs = [ dequote(i[2:]) for i in libs if i.startswith("-L") ]
libraries = [ dequote(i[2:]) for i in libs if i.startswith("-l") ]
if mysqlclient == "mysqlclient":
libs = config("libs")
elif mysqlclient == "mysqlclient_r":
libs = config("libs_r")
elif mysqlclient == "mysqld":
libs = config("embedded")
library_dirs = [ dequote(i[2:]) for i in libs if i.startswith("-L") ]
libraries = [ dequote(i[2:]) for i in libs if i.startswith("-l") ]
extra_compile_args = mysql_config("cflags")
# Workaround for a pre-4.1.9 bug
if "z" not in libraries:
libraries.append("z")
extra_compile_args = config("cflags")
if mysqlstatic:
extra_objects.append(os.path.join(
library_dirs[0],'lib%s.a' % mysqlclient))
else:
libraries.append(mysqlclient)
classifiers = """
Development Status :: 5 - Production/Stable
Environment :: Other Environment
License :: OSI Approved :: GNU General Public License (GPL)
Operating System :: MacOS :: MacOS X
Operating System :: Microsoft :: Windows :: Windows NT/2000
Operating System :: OS Independent
Operating System :: POSIX
Operating System :: POSIX :: Linux
Operating System :: Unix
Programming Language :: C
Programming Language :: Python
Topic :: Database
Topic :: Database :: Database Engines/Servers
"""
metadata = {
'name': name,
'version': version,
'description': "Python interface to MySQL",
'long_description': __doc__,
'author': "Andy Dustman",
'author_email': "andy@dustman.net",
'license': "GPL",
'platforms': "ALL",
'url': "http://sourceforge.net/projects/mysql-python",
'download_url': "http://prdownloads.sourceforge.net/mysql-python/" \
"MySQL-python-%s.tar.gz" % version,
'classifiers': [ c for c in classifiers.split('\n') if c ],
'py_modules': [
"_mysql_exceptions",
"MySQLdb.converters",
"MySQLdb.connections",
"MySQLdb.cursors",
"MySQLdb.sets",
"MySQLdb.times",
"MySQLdb.stringtimes",
"MySQLdb.mxdatetimes",
"MySQLdb.pytimes",
"MySQLdb.constants.CR",
"MySQLdb.constants.FIELD_TYPE",
"MySQLdb.constants.ER",
"MySQLdb.constants.FLAG",
"MySQLdb.constants.REFRESH",
"MySQLdb.constants.CLIENT",
],
'ext_modules': [
Extension(
name='_mysql',
sources=['_mysql.c'],
include_dirs=include_dirs,
library_dirs=library_dirs,
libraries=libraries,
extra_compile_args=extra_compile_args,
extra_objects=extra_objects,
),
],
}
if static:
extra_objects.append(os.path.join(
library_dirs[0],'lib%s.a' % client))
ext_mysql_metadata = dict(
name="_mysql",
include_dirs=include_dirs,
library_dirs=library_dirs,
libraries=libraries,
extra_compile_args=extra_compile_args,
extra_objects=extra_objects,
sources=['_mysql.c'],
)
if config.read(['site.cfg']):
ext_mysql_metadata.update([ (k, v.split()) for k, v in config.items('compiler') ])
ext_mysql = Extension(**ext_mysql_metadata)
metadata['ext_modules'] = [ext_mysql]
setup(**metadata)

28
MySQLdb/site.cfg Normal file
View File

@@ -0,0 +1,28 @@
# Options:
#
# embedded: link against the embedded server library
# threadsafe: use the threadsafe client
# static: link against a static library (probably required for embedded)
[options]
embedded = False
threadsafe = True
static = False
# Use the compiler section to add additional options for the extension build.
# In particular, if your platform does not support mysql_config (like
# Windows), you will have to set most of these. Note that each entry is split
# into a list so that each line is one item.
[compiler]
#mysql_root: /usr/local/mysql
#library_dirs: %(mysql_root)s/lib
#include_dirs: %(mysql_root)s/include
#libraries: mysqlclient
# zlib
# msvcrt
# libcmt
# wsock32
# advapi32
#extra_compile_args:
#extra_objects: