Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

moved cross_table to aggregation results; minor fixes

  • Loading branch information...
commit fce13069e8952f24c9fcbce86fd0f1e01e24b019 1 parent 0f385e8
Stefan Urbanek authored
View
23 LICENSE
@@ -1,10 +1,23 @@
Copyright (c) 2011-2012 Stefan Urbanek, see AUTHORS for more details
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
-If your version of the Software supports interaction with it remotely through a computer network, the above
-copyright notice and this permission notice shall be accessible to all users.
+If your version of the Software supports interaction with it remotely through
+a computer network, the above copyright notice and this permission notice
+shall be accessible to all users.
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
View
6 bin/slicer
@@ -128,7 +128,7 @@ def generate_ddl(args):
model = cubes.load_model(args.model)
if args.backend:
- backend = cubes.util.get_backend(args.backend)
+ backend = cubes.workspace.get_backend(args.backend)
else:
backend = cubes.backends.sql.browser
@@ -161,7 +161,7 @@ def run_test(args):
for module in modules:
e = __import__(module)
- context = cubes.util.create_slicer_context(config)
+ context = cubes.workspace.create_slicer_context(config)
backend = context["backend"]
workspace = backend.create_workspace(context["model"],
**context["workspace_options"])
@@ -176,7 +176,7 @@ def run_test(args):
def denormalize(args):
cube_list = args.cube
config = read_config(args.config)
- context = cubes.util.create_slicer_context(config)
+ context = cubes.workspace.create_slicer_context(config)
model = context["model"]
backend = context["backend"]
View
4 cubes/backends/sql/star.py
@@ -572,12 +572,12 @@ def join_expression(self, joins):
master_column = master_table.c[join.master.column]
except:
raise MappingError('Unable to find master key (schema %s) "%s"."%s" ' \
- % join.master)
+ % join.master[0:3])
try:
detail_column = detail_table.c[join.detail.column]
except:
raise MappingError('Unable to find detail key (schema %s) "%s"."%s" ' \
- % join.detail)
+ % join.detail[0:3])
onclause = master_column == detail_column
View
69 cubes/browser.py
@@ -67,6 +67,7 @@ def dimension_object(self, dimension):
* `dimension` - a dimension object or a string, if it is a string,
then dimension object is retrieved from cube
"""
+ # FIXME: depreciate, use cube.dimension(...) directly
if type(dimension) == str:
return self.cube.dimension(dimension)
@@ -98,8 +99,8 @@ def aggregate(self, cell=None, measures=None, drilldown=None, **options):
If there are no more levels to be drilled down, an exception is
raised. Say your model has three levels of the `date` dimension:
- `year`, `month`, `day` and you try to drill down by `date` then
- ``ValueError`` will be raised.
+ `year`, `month`, `day` and you try to drill down by `date` at the next
+ level then ``ValueError`` will be raised.
Retruns a :class:AggregationResult object.
"""
@@ -133,8 +134,9 @@ def report(self, cell, queries):
specifying arguments of the particular query. Each query should
contain at least one required value ``query`` which contains name of
the query function: ``aggregate``, ``facts``, ``fact``, ``values`` and
- cell ``details``. Rest of values are function specific, please refer
- to the respective function documentation for more information.
+ cell ``cell`` (for cell details). Rest of values are function
+ specific, please refer to the respective function documentation for
+ more information.
Example::
@@ -238,10 +240,20 @@ def report(self, cell, queries):
elif query_type == "values":
result = self.values(query_cell, **args)
-
+
elif query_type == "details":
+ # FIXME: depreciate this raw form
result = self.cell_details(query_cell, **args)
+ elif query_type == "cell":
+ details = self.cell_details(query_cell, **args)
+ cell_dict = query_cell.to_dict()
+
+ for cut, detail in zip(cell_dict["cuts"], details):
+ cut["details"] = detail
+
+ result = cell_dict
+
else:
raise ArgumentError("Unknown report query '%s' for '%s'" % (query_type, result_name))
@@ -1147,14 +1159,41 @@ def drilldown_rows(self, dimension, depth=None):
record)
yield row
+ def cross_table(self, onrows, oncolumns, measures=None):
+ """
+ Creates a cross table from result's drilldown. `onrows`
+ contains list of attribute names to be placed at rows and `oncolumns`
+ contains list of attribute names to be placet at columns. `measures` is a
+ list of measures to be put into cells. If measures are not specified, then
+ only ``record_count`` is used.
+
+ Returns a named tuble with attributes:
+
+ * `columns` - labels of columns. The tuples correspond to values of
+ attributes in `oncolumns`.
+ * `rows` - labels of rows as list of tuples. The tuples correspond to
+ values of attributes in `onrows`.
+ * `data` - list of measure data per row. Each row is a list of measure
+ tuples.
+
+ .. warning::
+
+ Experimental implementation. Interface might change - either
+ arguments or result object.
+
+ """
+
+ return cross_table(self.drilldown, onrows, oncolumns, measures)
+
CrossTable = namedtuple("CrossTable", ["columns", "rows", "data"])
-def cross_table(result, onrows, oncolumns, measures=None):
- """Creates a cross table from aggregation `result` drill down. `onrows`
- contains list of attribute names to be placed at rows and `oncolumn`
- contains list of attribute names to be placet at columns. `measures` is a
- list of measures to be put into cells. If measures are not specified, then
- ``record_count`` is used.
+def cross_table(drilldown, onrows, oncolumns, measures=None):
+ """
+ Creates a cross table from a drilldown (might be any list of records).
+ `onrows` contains list of attribute names to be placed at rows and
+ `oncolumns` contains list of attribute names to be placet at columns.
+ `measures` is a list of measures to be put into cells. If measures are not
+ specified, then only ``record_count`` is used.
Returns a named tuble with attributes:
@@ -1164,6 +1203,12 @@ def cross_table(result, onrows, oncolumns, measures=None):
values of attributes in `onrows`.
* `data` - list of measure data per row. Each row is a list of measure
tuples.
+
+ .. warning::
+
+ Experimental implementation. Interface might change - either
+ arguments or result object.
+
"""
matrix = {}
@@ -1172,7 +1217,7 @@ def cross_table(result, onrows, oncolumns, measures=None):
measures = measures or ["record_count"]
- for record in result.drilldown:
+ for record in drilldown:
hrow = tuple(record[f] for f in onrows)
hcol = tuple(record[f] for f in oncolumns)
View
10 cubes/model.py
@@ -169,7 +169,9 @@ def _fix_dict_list(obj, key_name="name", warning=None):
return obj
def _create_dimension(desc):
- """Creates a `Dimension` instance from dictionary description `desc`"""
+ """Creates a `Dimension` instance from dictionary description `desc`."""
+
+ # FIXME: code from Dimension.__init__() should be moved here
return Dimension(**desc)
def _create_cube(desc, dimensions):
@@ -490,7 +492,7 @@ def validate(self):
return results
- def is_valid(self, strict = False):
+ def is_valid(self, strict=False):
"""Check whether model is valid. Model is considered valid if there
are no validation errors. If you want to be sure that there are no
warnings as well, set *strict* to ``True``. If `strict` is ``False``
@@ -1539,6 +1541,7 @@ def __ne__(self, other):
def __str__(self):
return "<level: {name: '%s', key: %s, attributes: %s}>" % (self.name, self.key, self.attributes)
+
def __repr__(self):
return self.__str__()
@@ -1680,6 +1683,9 @@ def __init__(self, name, label=None, locales=None, order=None,
def __str__(self):
return self.name
+
+ def __repr__(self):
+ return str(self.to_dict())
def __eq__(self, other):
if type(other) != Attribute:
View
40 cubes/tutorial/sql.py
@@ -1,5 +1,36 @@
import sqlalchemy
import csv
+import csv, codecs, cStringIO
+
+class UTF8Recoder:
+ """
+ Iterator that reads an encoded stream and reencodes the input to UTF-8
+ """
+ def __init__(self, f, encoding):
+ self.reader = codecs.getreader(encoding)(f)
+
+ def __iter__(self):
+ return self
+
+ def next(self):
+ return self.reader.next().encode("utf-8")
+
+class UnicodeReader:
+ """
+ A CSV reader which will iterate over lines in the CSV file "f",
+ which is encoded in the given encoding.
+ """
+
+ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
+ f = UTF8Recoder(f, encoding)
+ self.reader = csv.reader(f, dialect=dialect, **kwds)
+
+ def next(self):
+ row = self.reader.next()
+ return [unicode(s, "utf-8") for s in row]
+
+ def __iter__(self):
+ return self
def create_table_from_csv(connectable, file_name, table_name, fields, create_id = False, schema = None):
"""Create a table with name `table_name` from a CSV file `file_name` with columns corresponding
@@ -21,8 +52,11 @@ def create_table_from_csv(connectable, file_name, table_name, fields, create_id
table.drop(checkfirst=False)
type_map = { "integer": sqlalchemy.Integer,
- "float":sqlalchemy.Float,
- "string":sqlalchemy.String(256) }
+ "float":sqlalchemy.Numeric,
+ "string":sqlalchemy.String(256),
+ "text":sqlalchemy.Text,
+ "date":sqlalchemy.Text,
+ "boolean": sqlalchemy.Integer }
if create_id:
col = sqlalchemy.schema.Column('id', sqlalchemy.Integer, primary_key=True)
@@ -36,7 +70,7 @@ def create_table_from_csv(connectable, file_name, table_name, fields, create_id
table.create()
- reader = csv.reader(open(file_name))
+ reader = UnicodeReader(open(file_name))
# Skip header
reader.next()
Please sign in to comment.
Something went wrong with that request. Please try again.