htsql / src / htsql / fmt / spreadsheet.py

#
# Copyright (c) 2006-2011, Prometheus Research, LLC
# Authors: Clark C. Evans <cce@clarkevans.com>,
#          Kirill Simonov <xi@resolvent.net>
#


"""
:mod:`htsql.fmt.spreadsheet`
============================

This module implements the CSV renderer.
"""


from ..adapter import adapts
from .format import Format, Formatter, Renderer
from ..domain import (Domain, BooleanDomain, NumberDomain, FloatDomain,
                      StringDomain, EnumDomain, DateDomain, TimeDomain,
                      DateTimeDomain)
from .entitle import entitle
import csv
import cStringIO


class CSVRenderer(Renderer):

    name = 'text/csv'
    aliases = ['csv']
    content_type = name
    extension = 'csv'

    def render(self, product):
        status = self.generate_status(product)
        headers = self.generate_headers(product)
        body = self.generate_body(product)
        return status, headers, body

    def generate_status(self, product):
        return "200 OK"

    def generate_headers(self, product):
        filename = str(product.profile.segment.syntax)
        filename = filename.replace('\\', '\\\\').replace('"', '\\"')
        return [('Content-Type', '%s; charset=UTF-8' % self.content_type),
                ('Content-Disposition',
                 'attachment; filename="(%s).%s"' % (filename, self.extension))]

    def get_writer(self, output):
        return csv.writer(output)

    def generate_body(self, product):
        if not product:
            return
        titles = [entitle(element.binding)
                  for element in product.profile.segment.elements]
        domains = [element.domain
                   for element in product.profile.segment.elements]
        tool = Formatter(self)
        formats = [Format(self, domain, tool) for domain in domains]
        output = cStringIO.StringIO()
        writer = self.get_writer(output)
        writer.writerow(titles)
        yield output.getvalue()
        output.seek(0)
        output.truncate()
        for record in product:
            items = [format(value)
                     for format, value in zip(formats, record)]
            writer.writerow(items)
            yield output.getvalue()
            output.seek(0)
            output.truncate()

class TSVRenderer(CSVRenderer):

    name = 'text/tsv'
    aliases = ['tsv']
    content_type = name
    extension = 'tsv'

    def get_writer(self, output):
        return csv.writer(output, dialect='excel-tab')

class CSVFormatter(Formatter):

    adapts(CSVRenderer)

class TSVFormatter(Formatter):

    adapts(TSVRenderer)

class FormatDomain(Format):

    adapts(CSVRenderer, Domain)

    def __call__(self, value):
        if value is None:
            return ""
        if isinstance(value, unicode):
            value = value.encode('utf-8')
        value = str(value)
        try:
            value.decode('utf-8')
        except UnicodeDecodeError:
            value = repr(value)
        return value


class FormatBoolean(Format):

    adapts(CSVRenderer, BooleanDomain)

    def __call__(self, value):
        if value is None:
            return ""
        if value is True:
            return "true"
        if value is False:
            return "false"


class FormatNumber(Format):

    adapts(CSVRenderer, NumberDomain)

    def __call__(self, value):
        if value is None:
            return ""
        return str(value)


class FormatFloat(Format):

    adapts(CSVRenderer, FloatDomain)

    def __call__(self, value):
        if value is None:
            return ""
        return repr(value)


class FormatString(Format):

    adapts(CSVRenderer, StringDomain)

    def __call__(self, value):
        if value is None:
            return ""
        return value

class FormatEnum(Format):

    adapts(CSVRenderer, EnumDomain)

    def __call__(self, value):
        if value is None:
            return ""
        return value


class FormatDate(Format):

    adapts(CSVRenderer, DateDomain)

    def __call__(self, value):
        if value is None:
            return ""
        return str(value)


class FormatTime(Format):

    adapts(CSVRenderer, TimeDomain)

    def __call__(self, value):
        if value is None:
            return ""
        return str(value)


class FormatDateTime(Format):

    adapts(CSVRenderer, DateTimeDomain)

    def __call__(self, value):
        if value is None:
            return ""
        if not value.time():
            return str(value.date())
        return str(value)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.