The htsql package

htsql

copyright:2006-2011, Prometheus Research, LLC
authors:Clark C. Evans <cce@clarkevans.com>, Kirill Simonov <xi@resolvent.net>; see AUTHORS file in the source distribution for the full list of contributors
license:See LICENSE file in the source distribution

This package provides HTSQL, a query language for the accidental programmer.

HTSQL is implemented as a WSGI application. To create an application, run:

>>> from htsql import HTSQL
>>> app = HTSQL(db)

where db is a connection URI, a string of the form:

engine://username:password@host:port/database
engine
The type of the database server; pgsql or sqlite.
username:password
Used for authentication; optional.
host:port
The server address; optional.
database
The name of the database; for SQLite, the path to the database file.

To execute a WSGI request, run

>>> app(environ, start_response)
class htsql.HTSQLAddon(app, attributes)

Declares the htsql addon.

htsql.adapter

This module provides a mechanism for pluggable extensions.

class htsql.adapter.Component

A unit of extension in the HTSQL component architecture.

HTSQL component architecture allows you to:

  • declare interfaces that provide various services;
  • define components implementing the interfaces;
  • given an interface and a dispatch key, produce a component which implements the interface for the given key.

Three types of interfaces are supported: utilities, adapters and protocols; see Utility, Adapter, Protocol respectively.

static components()

Produce a list of all components of the active application.

classmethod implementations(interface)

Produces a list of all components implementing the interface.

classmethod realize(interface, dispatch_key)

Produces a realization of the interface for the given dispatch key.

classmethod implements(component, interface)

Tests if the component implements the interface.

classmethod dominates(component, other)

Tests if the component dominates another component.

classmethod matches(component, dispatch_key)

Tests if the component matches a dispatch key.

classmethod dispatch(interface, *args, **kwds)

Extract the dispatch key from the constructor arguments.

class htsql.adapter.Realization

A realization of an interface for some dispatch key.

class htsql.adapter.Utility

Implements utility interfaces.

An utility is an interface with a single realization.

This is an abstract class; to declare an utility interface, create a subclass of Utility. To add an implementation of the interface, create a subclass of the interface class.

The following example declared an interface SayHello and provide an implementation PrintHello that prints 'Hello, World! to the standard output:

class SayHello(Utility):
    def __call__(self):
        raise NotImplementedError("interface is not implemented")

class PrintHello(SayHello):
    def __call__(self):
        print "Hello, World!"

def hello():
    hello = SayHello()
    hello()

>>> hello()
Hello, World!
class htsql.adapter.Adapter

Implements adapter interfaces.

An adapter interface provides mechanism for polymorphic dispatch based on the types of the arguments.

This is an abstract class; to declare an adapter interface, create a subclass of Adapter and indicate the most generic type signature of the polymorphic arguments using function adapts().

To add an implementation of an adapter interface, create a subclass of the interface class and indicate the matching type signatures using functions adapts(), adapts_many(), or adapts_none().

Class attributes:

types (a list of type signatures)
List of signatures that the component matches.
arity (an integer)
Number of polymorphic arguments.

The following example declares an adapter interface Format and implements it for several data types:

class Format(Adapter):
    adapts(object)
    def __init__(self, value):
        self.value = value
    def __call__(self):
        # The default implementation.
        return str(self.value)

class FormatString(Format):
    adapts(str)
    def __call__(self):
        # Display alphanumeric values unquoted, the others quoted.
        if self.value.isalnum():
            return self.value
        else:
            return repr(self.value)

class FormatList(Format):
    adapts(list)
    def __call__(self):
        # Apply `format` to the list elements.
        return "[%s]" % ",".join(format(item) for item in self.value)

def format(value):
    format = Format(value)
    return format()

>>> print format(123)
123
>>> print format("ABC")
ABC
>>> print format("Hello, World!")
'Hello, World!'
>>> print format([123, "ABC", "Hello, World!"])
[123, ABC, 'Hello, World!']
htsql.adapter.adapts(*type_vector)

Specifies the adapter signature.

The component matches the specified or any more specific signature.

Use it in the namespace of the component, for example:

class DoSmth(Adapter):

    adapts(T1, T2, ...)
htsql.adapter.adapts_none()

Indicates that the adapter does not match any signatures.

Use it in the namespace of the adapter, for example:

class DoSmth(Adapter):

    adapts_none()
htsql.adapter.adapts_many(*type_vectors)

Specifies signatures of the adapter.

The component matches any of the specified signatures as well all more specific signatures.

Use it in the namespace of the adapter, for example:

class DoSmth(Adapter):

    adapts_many((T11, T12, ...),
                (T21, T22, ...),
                ...)
class htsql.adapter.Protocol

Implements protocol interfaces.

A protocol interface provides mechanism for name-based dispatch.

This is an abstract class; to declare a protocol interface, create a subclass of Protocol.

To add an implementation of a protocol interface, create a subclass of the interface class and specify its name using function named().

Class attributes:

names (a list of strings)
List of names that the component matches.

The following example declares a protocol interface Weigh and adds several implementations:

class Weigh(Protocol):
    def __init__(self, name):
        self.name = name
    def __call__(self):
        # The default implementation.
        return -1

class WeighAlice(Weigh):
    named("Alice")
    def __call__(self):
        return 150

class WeighBob(Weigh):
    named("Bob")
    def __call__(self):
        return 160

def weigh(name):
    weigh = Weigh(name)
    return weigh()

>>> weigh("Alice")
150
>>> weigh("Bob")
160
>>> weigh("Clark")
-1
htsql.adapter.named(*names)

Specifies the names of the protocol.

Use it in the namespace of the protocol, for example:

class DoSmth(Protocol):

    named("...")
class htsql.adapter.ComponentRegistry

Contains cached components and realizations.

htsql.addon

This module declares HTSQL addons.

class htsql.addon.Addon(app, attributes)

Implements an addon for HTSQL applications.

This is an abstract class; to add a new addon, create a subclass of Addon.

classmethod get_hint()

Returns a short one-line description of the addon.

classmethod get_help()

Returns a long description of the addon.

htsql.application

This module implements an HTSQL application.

class htsql.application.Application(db, *extensions)

Implements an HTSQL application.

db
The connection URI.
extensions
List of addons activated with the application.

htsql.connect

This module declares the database connection adapter.

exception htsql.connect.DBError(message)

Raised when a database error occurred.

message (a string)
The error message.
class htsql.connect.ErrorGuard

Guards against DBAPI exception.

This class converts DBAPI exceptions to DBError. It is designed to be used in a with clause.

Usage:

connect = Connect()
try:
    with ErrorGuard():
        connection = connect.open_connection()
        cursor = connection.cursor()
        ...
except DBError:
    ...
class htsql.connect.ConnectionProxy(connection, guard)

Wraps a DBAPI connection object.

The proxy supports common DBAPI methods by passing them to the connection object. Any exceptions raised when the executing DBAPI methods are converted to DBError.

connection
A raw DBAPI connection object.
guard (ErrorGuard)
A DBAPI exception guard.
cursor()

Returns a database cursor.

This method actually produces a CursorProxy instance.

commit()

Commit the current transaction.

rollback()

Rollback the current transaction.

close()

Close the connection.

class htsql.connect.CursorProxy(cursor, guard)

Wraps a DBAPI cursor object.

The proxy supports common DBAPI methods by passing them to the cursor object. Any exceptions raised when the executing DBAPI methods are converted to DBError.

cursor
A raw DBAPI cursor object.
guard (ErrorGuard)
A DBAPI exception guard.
description

The format of the result rows.

rowcount

The number of rows produced or affected by the last statement.

execute(statement, *parameters)

Execute one SQL statement.

executemany(statement, *parameters)

Execute an SQL statement against all parameters.

fetchone()

Fetch the next row of the result.

fetchmany(*size)

Fetch the next set of rows of the result.

fetchall()

Fetch all remaining rows of the result.

close()

Close the cursor.

class htsql.connect.Connect(with_autocommit=False)

Declares the connection interface.

The connection interface is a utility to open database connections.

Usage:

connect = Connect()
try:
    connection = connect()
    cursor = connection.cursor()
    cursor.execute(...)
    cursor.fetchall()
    ...
except DBError:
    ...
open()

Returns a raw DBAPI connection object.

with_autocommit (Boolean)
If set, the connection is opened in the autocommit mode.

htsql.context

This module keeps the active HTSQL application in a thread-local variable.

This module exports one global variable:

context (ThreadContext)
A thread-local variable that holds the active application.
class htsql.context.ThreadContext

Keeps the active HTSQL application.

app

Returns the active HTSQL application.

This property never returns None; when there is no active application, it raises an exception.

htsql.domain

This module defines HTSQL domains.

class htsql.domain.Domain

Represents an HTSQL domain (data type).

A domain indicates the type of an object. Most HTSQL domains correspond to SQL data types; some domains are special and used when the actual SQL data type is unknown or nonsensical.

A value of a specific domain could be represented in two forms:

  • as an HTSQL literal;
  • as a native Python object.

Methods parse() and dump() translate values from one form to the other.

parse(data)

Converts an HTSQL literal to a native Python object.

Raises ValueError if the literal is not in a valid format.

data (a Unicode string or None)
An HTSQL literal representing a value of the given domain.

Returns a native Python object representing the same value.

dump(value)

Converts a native Python object to an HTSQL literal.

value (acceptable types depend on the domain)
A native Python object representing a value of the given domain.

Returns an HTSQL literal representing the same value.

class htsql.domain.VoidDomain

Represents a domain without any valid values.

This domain is assigned to objects when the domain is structurally required, but does not have any semantics.

class htsql.domain.UntypedDomain

Represents an unknown type.

This domain is assigned to HTSQL literals temporarily until the actual domain could be derived from the context.

class htsql.domain.TupleDomain

Represents a table domain.

This domain is assigned to table expressions.

class htsql.domain.BooleanDomain

Represents Boolean data type.

Valid literal values: true, false.

Valid native values: bool objects.

class htsql.domain.NumberDomain

Represents a numeric data type.

This is an abstract data type, see IntegerDomain, FloatDomain, DecimalDomain for concrete subtypes.

Class attributes:

is_exact (Boolean)
Indicates whether the domain represents exact values.
radix (2 or 10)
Indicates whether the values are stored in binary or decimal form.
class htsql.domain.IntegerDomain(size=None)

Represents a binary integer data type.

Valid literal values: integers (in base 2) with an optional sign.

Valid native values: int or long objects.

size (an integer or None)
Number of bits used to store a value; None if not known.
class htsql.domain.FloatDomain(size=None)

Represents an IEEE 754 float data type.

Valid literal values: floating-point numbers in decimal or scientific format.

Valid native values: float objects.

size (an integer or None)
Number of bits used to store a value; None if not known.
class htsql.domain.DecimalDomain(precision=None, scale=None)

Represents an exact decimal data type.

Valid literal values: floating-point numbers in decimal or scientific format.

Valid native values: decimal.Decimal objects.

precision (an integer or None)
Number of significant digits; None if infinite or not known.
scale (an integer or None)
Number of significant digits in the fractional part; zero for integers, None if infinite or not known.
class htsql.domain.StringDomain(length=None, is_varying=True)

Represents a string data type.

Valid literal values: all literal values.

Valid native values: unicode objects; the NUL character is not allowed.

length (an integer or None)
The maximum length of the value; None if infinite or not known.
is_varying (Boolean)
Indicates whether values are fixed-length or variable-length.
class htsql.domain.EnumDomain(labels)

Represents an enumeration data type.

An enumeration domain has a predefined set of valid string values.

labels (a list of Unicode strings)
List of valid values.
class htsql.domain.DateDomain

Represents a date data type.

Valid literal values: valid date values in the form YYYY-MM-DD.

Valid native values: datetime.date objects.

class htsql.domain.TimeDomain

Represents a time data type.

Valid literal values: valid time values in the form HH:MM[:SS[.SSSSSS]].

Valid native values: datetime.time objects.

class htsql.domain.DateTimeDomain

Represents a date and time data type.

Valid literal values: valid date and time values in the form YYYY-MM-DD HH:MM[:SS[.SSSSSS]].

Valid native values: datetime.datetime objects.

class htsql.domain.OpaqueDomain

Represents an unsupported SQL data type.

Note: this is the only SQL domain with values that cannot be serialized using dump().

htsql.entity

This module implements the HTSQL catalog and catalog entities.

class htsql.entity.Join(origin, target, origin_columns, target_columns, is_expanding, is_contracting, equality_vector)

Represents a join condition between two tables.

This is an abstract case class with two subclasses: DirectJoin and ReverseJoin.

Class attributes:

is_direct (Boolean)
Indicates that the join follows a foreign key (set for an instance of DirectJoin).
is_reverse (Boolean)
Indicates that the join follows the opposite direction to a foreign key (set for an instance of ReverseJoin).

Attributes:

origin (TableEntity)
The origin table of the join.
target (TableEntity)
The target table of the join.
is_expanding (Boolean)
Indicates that for each row of the origin table there is at least one row of the target table that satisfies the join condition.
is_contracting (Boolean)
Indicates that for each row of the origin table there is no more than one row of the target table that satisfies the join condition.
class htsql.entity.DirectJoin(foreign_key)

Represents a join condition corresponding to a foreign key.

foreign_key (ForeignKeyEntity)
The foreign key that generates the join condition.
class htsql.entity.ReverseJoin(foreign_key)

Represents a join condition that joins tables in the opposite direction to some foreign key.

foreign_key (ForeignKeyEntity)
The foreign key that generates the join condition.

htsql.error

This module implements generic HTSQL exceptions.

exception htsql.error.HTTPError(detail)

An error associated with an HTSQL query.

An instance of HTTPError contains a pointer to an HTSQL expression that caused the error. The traceback produced by the exception includes the original HTSQL query and a pointer to the erroneous expression.

An instance of HTTPError could also serve as a simple WSGI application generating an appropriate HTTP error code and displaying the error message.

This is an abstract exception class. To implement a concrete exception, add a subclass of HTTPError and override the following class attributes:

code
The HTTP status line.
kind
The description of the error class.

The constructor of HTTPError accepts the following parameters:

detail (a string)
The description of the error.
exception htsql.error.BadRequestError(detail)

Represents 400 Bad Request.

exception htsql.error.ForbiddenError(detail)

Represents 403 Forbidden.

exception htsql.error.NotFoundError(detail)

Represents 404 Not Found.

exception htsql.error.ConflictError(detail)

Represents 409 Conflict.

exception htsql.error.InternalServerError(detail)

Represents 500 Internal Server Error.

exception htsql.error.NotImplementedError(detail)

Represents 501 Not Implemented.

exception htsql.error.InvalidSyntaxError(detail)

Represents an invalid syntax error.

This exception is raised by the scanner when it cannot tokenize the query, or by the parser when it finds an unexpected token.

htsql.introspect

This module declares the database introspector adapter.

class htsql.introspect.Introspect

Declares the introspection interface.

An introspector analyzes the database meta-data and generates an HTSQL catalog.

htsql.mark

This module implements a Mark object.

class htsql.mark.Mark(input, start, end)

A slice of an HTSQL query.

In the process of translation of an HTSQL query to SQL, intermediary nodes of different kinds are generated. Most of the nodes have a mark attribute that points to the original HTSQL expression from which the node was derived.

Note that a Mark object should only be used for presentational purposes such as error reporting. There is no guarantee that the slice mark.value[mark.start:mark.end] would represent a valid HTSQL expression.

input (a Unicode string)
The HTSQL query.
start (an integer)
The beginning of the slice.
end (an integer)
The end of the slice.
classmethod union(*nodes)

Generates a new Mark object from a collection of separate marks. The returned mark will cover all the given marks.

nodes (a list)
A list of objects having a mark attribute. The list may also include None.
excerpt()

Returns a list of lines that consists an except of the original query with ^ characters underlining the mark.

htsql.request

This module implements the request utility.

htsql.split_sql

This module declares the SQL splitter adapter.

class htsql.split_sql.SQLToken(pattern, min_level=None, max_level=None, only_level=None, delta=0, is_junk=False, is_end=False)

Declares a regular expression pattern to be used by the SQL splitter.

pattern (a string)
A regular expression in the verbose format. The expression will be compiled using re.X|re.S flags.
min_level (an integer or None)
The minimal level at which the pattern activates.
max_level (an integer or None)
The maximum level at which the pattern activates.
only_level (an integer or None)
The level at which the pattern activates.
delta (an integer)
When a token is detected, change the current level by delta.
is_junk (Boolean)
Ignore the token value.
is_end (Boolean)
If set, indicates that the splitter should stop when a token is detected.
class htsql.split_sql.SplitSQL

Declares the SQL splitter interface.

A SQL splitter takes a string containing one or more SQL statements separated by ; and produces a sequence of SQL statements.

Usage:

try:
    split_sql = SplitSQL()
    for sql in split_sql(input):
        cursor.execute(sql)
except ValueError:
    ...

This is an abstract utility. To add a new splitter, create a subclass of SplitSQL and override the class variable tokens:

tokens (a list of SQLToken instances)
The tokens recognized by the splitter.

htsql.util

This module provides various hard-to-categorize utilities.

class htsql.util.DB(engine, username, password, host, port, database, options=None)

Represents parameters of a database connection.

engine
The type of the database server; currently supported are 'pgsql' and 'sqlite'.
username
The user name used to authenticate; None to use the default.
password
The password used to authenticate; None to authenticate without providing a password.
host
The host address; None to use the default.
port
The port number; None to use the default.
database

The database name.

For SQLite, the path to the database file.

options

A dictionary containing extra connection parameters.

Currently ignored by all engines.

The parameters username, password, host, port are ignored by the SQLite engine.

classmethod parse(value)

Parses a connection URI and returns a corresponding DB instance.

A connection URI is a string of the form:

engine://username:password@host:port/database?options
engine
The type of the database server; supported values are pgsql and sqlite.
username:password
Used for authentication.
host:port
The server address.
database

The name of the database.

For SQLite, the path to the database file.

options
A string of the form key=value&... providing extra connection parameters.

The parameters engine and database are required, all the other parameters are optional.

If a parameter contains a character which cannot be represented literally (such as :, /, @ or ?), it should be escaped using %-encoding.

If the connection URI is not in a valid format, ValueError is raised.

Besides a connection URI, the function also accepts instances of DB and dictionaries. An instance of DB is returned as is. A dictionary is assumed to contain connection parameters. The corresponding instance of DB is returned.

class htsql.util.maybe(value_type)

Checks if a value is either None or an instance of the specified type.

Usage:

isinstance(value, maybe(T))
class htsql.util.oneof(*value_types)

Checks if a value is an instance of one of the specified types.

Usage:

isinstance(value, oneof(T1, T2, ...))
class htsql.util.listof(item_type)

Checks if a value is a list containing elements of the specified type.

Usage:

isinstance(value, listof(T))
class htsql.util.setof(item_type)

Checks if a value is a set containing elements of the specified type.

Usage:

isinstance(value, setof(T))
class htsql.util.tupleof(*item_types)

Checks if a value is a tuple with the fixed number of elements of the specified types.

Usage:

isinstance(value, tupleof(T1, T2, ..., TN))
class htsql.util.dictof(key_type, item_type)

Checks if a value is a dictionary with keys and elements of the specified types.

Usage:

isinstance(value, dictof(T1, T2))
class htsql.util.subclassof(class_type)

Check if a value is a subclass of the specified class.

Usage:

isinstance(value, subclassof(T))
class htsql.util.filelike

Checks if a value is a file or a file-like object.

Usage:

isinstance(value, filelike())
htsql.util.aresubclasses(subclasses, superclasses)

Takes two lists; checks if each element of the first list is a subclass of the corresponding element in the second list.

subclasses (a sequence of types)
A list of potential subclasses.
superclasses (a sequence of types)
A list of potential superclasses.

Returns True if the check succeeds; False otherwise.

htsql.util.trim_doc(doc)

Unindent and remove leading and trailing blank lines.

Useful for stripping indentation from docstrings.

htsql.util.toposort(elements, order, is_total=False)

Implements topological sort.

Takes a list of elements and a partial order relation. Returns the elements reordered to satisfy the given order.

A (finite) order relation is an acyclic directed graph.

elements (a list)
A list of elements.
order (a callable)
A function order(element) -> [list of elements] representing the partial order relation. For an element x, order(x) must produce a list of elements less than x.
is_total (Boolean)
Ensures that the given partial order is, in fact, a total order.

This function raises RuntimeError if order is not a valid partial order (contains loops) or if is_total is set and order is not a valid total order.

class htsql.util.Printable

Implements default string representation.

class htsql.util.Clonable

Implements an immutable clonable object.

clone(**replacements)

Clones the node assigning new values to selected attributes.

Returns a new object of the same type keeping original attributes except those for which new values are specified.

replacements (a dictionary)
A mapping: attribute -> value containing new attribute values.
clone_to(clone_type, **replacements)

Clones the node changing its type and assigning new values to selected attributes.

Returns a new object of the specified type which keeps the attributes of the original objects except those for which new values are specified.

clone_type (a type)
The type of the cloned node.
replacements (a dictionary)
A mapping: attribute -> value containing new attribute values.
class htsql.util.Comparable(equality_vector=None)

Implements an object with by-value comparison semantics.

The constructor arguments:

equality_vector (an immutable tuple or None)
Encapsulates all essential attributes of an object. Two instances of Comparable are considered equal if they are of the same type and their equality vectors are equal. If None, the object is to be compared by identity.

Other attributes:

hash (an integer)
The hash of the equality vector; if two objects are equal, their hashes are also equal.
htsql.util.autoimport(name)

Imports all modules (including subpackages) in a package.

name (a string)
The package name.

htsql.validator

This module provides utilities for data validation and conversion.

class htsql.validator.Validator

Validators check if a given value conforms the specified format.

A validator acts as function that takes a value, checks if it conforms the format, normalizes and returns the value. Example:

validator = IntVal()
value = validator(value)

If the value does not conform the format, ValueError is raised.

Attribute hint gives a short textual description of the format.

Validator is the base abstract class for validators. Its subclasses provide validators for specific formats.

To create a validator for a new format, create a subclass of Validator and override the __call__() method. The method should accept values of any type. If the value does not conform to the format, ValueError should be raised; otherwise the value should be normalized and returned.

Example:

class IntVal(Validator):

    hint = "an integer"

    def __call__(self, value):
        if isinstance(value, str):
            value = int(value)
        if not isinstance(value, int):
            raise ValueError("an integer is expected")
        return value
class htsql.validator.AnyVal

A no-op validator.

class htsql.validator.StrVal(pattern=None, is_nullable=False)

Verifies if the value is a UTF-8 encoded string.

pattern (a regular expression or None)
Checks if the string matches the given regular expression.
is_nullable (Boolean)
If set, None values are permitted.
class htsql.validator.WordVal(is_nullable=False)

Verifies if the value is a word.

A word is a string containing alphanumeric characters, dashes, underscores, or spaces. In the normalized form, underscores and spaces are replaced with dashes.

is_nullable (Boolean)
If set, None values are permitted.
class htsql.validator.ChoiceVal(choices, is_nullable=False)

Verifies if the value belongs to a specified set of string constants.

choices (a list of strings)
List of valid choices.
is_nullable (Boolean)
If set, None values are permitted.
class htsql.validator.BoolVal(is_nullable=False)

Verifies if the value is Boolean.

Besides True and False constants, the following values are accepted:

  • 1, '1', 'true' (as True);
  • 0, '', '0', 'false' (as False).
is_nullable (Boolean)
If set, None values are permitted.
class htsql.validator.IntVal(min_bound=None, max_bound=None, is_nullable=False)

Verifies if the value is an integer.

Strings containing numeric characters are also accepted.

min_bound (integer or None)
If set, check that the value is greater or equal to min_bound.
max_bound (integer or None)
If set, check that the value is less or equal to max_bound.
is_nullable (Boolean)
If set, None values are permitted.
class htsql.validator.UIntVal(max_bound=None, is_nullable=False)

Verifies if the value is a non-negative integer.

class htsql.validator.PIntVal(max_bound=None, is_nullable=False)

Verifies if the value is a positive integer.

class htsql.validator.FloatVal(min_bound=None, max_bound=None, is_nullable=False)

Verifies if the value is an integer.

Strings representing numeric values in a decimal or a scientific format are also accepted.

min_bound (float or None)
If set, check that the value is greater or equal to min_bound.
max_bound (float or None)
If set, check that the value is less or equal to max_bound.
is_nullable (Boolean)
If set, None values are permitted.
class htsql.validator.UFloatVal(max_bound=None, is_nullable=False)

Verifies if the value is a non-negative float number.

class htsql.validator.SeqVal(item_validator, length=None, is_nullable=False)

Verifies if the value is a list with each list item conforming the specified format.

Also accepted are strings that agree with the following grammar:

value ::= <empty> | item ( [,] value )*
item  ::= <any non-space character or comma>+
        | ['] ( <any non-quote character> | [']['] )* [']

That is, the string must represent a comma-separated list of elements. If an element contains no whitespace characters and no commas, it could be represented literally; otherwise it should be quited with ' and any single quote character should be duplicated.

item_validator (Validator)
Validator for the sequence elements.
length (an integer or None)
If set, check that the length of the sequence is equal to length.
is_nullable (Boolean)
If set, None values are permitted.
class htsql.validator.MapVal(key_validator, item_validator, is_nullable=False)

Verifies if the value is a dictionary with keys and items conforming the specified formats.

Also accepted are strings that agree with the following grammar:

value     ::= <empty> | key ( [:] | [=] ) item ( [,] value )*
key, item ::= <any non-space character except for [:], [=] or [,]>+
            | ['] ( <any non-quote character> | [']['] )* [']

That is, the string must represent a comma-separated list of key=item pairs. The key and the item could be quoted or unquoted. An unquoted element contains no whitespace, :, =, , characters. A quoted element is enclosed with ' and has any single quote character duplicated.

key_validator (Validator)
Validator for the mapping keys.
item_validator (Validator)
Validator for the mapping values.
is_nullable (Boolean)
If set, None values are permitted.
class htsql.validator.ClassVal(class_type, is_nullable=False)

Verifies if the value is an instance of the specified class.

class_type
A class or a type object.
is_nullable (Boolean)
If set, None values are permitted.
class htsql.validator.DBVal(is_nullable=False)

Verifies if the value is a connection URI.

For description of the connection URI format, see htsql.util.DB.parse().

is_nullable (Boolean)
If set, None values are permitted.

htsql.wsgi

This module provides a handler for WSGI requests.

class htsql.wsgi.WSGI

Declares the WSGI interface.

The WSGI interface is a utility to handle WSGI requests.

Usage:

wsgi = WSGI()
body = wsgi(environ, start_response)