desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Replace the current extra filters @param filters: list of tuples (method, expression), or None to remove all extra filters'
def set_extra_filters(self, filters):
self.efilters = [] if filters: add = self.add_extra_filter for (method, expression) in filters: add(method, expression) return self.efilters
'Get the effective DAL query'
def get_query(self):
if (self.query is not None): return self.query resource = self.resource query = reduce((lambda x, y: (x & y)), self.queries, self.mquery) if self.filters: if (self.transformed is None): filters = reduce((lambda x, y: (x & y)), self.filters) transformed = filters.t...
'Get the effective virtual filter'
def get_filter(self):
if (self.query is None): self.get_query() return self.vfltr
'Get the list of extra filters @return: list of tuples (method, expression)'
def get_extra_filters(self):
return list(self.efilters)
'Get the joins required for this filter @param left: get the left joins @param as_list: return a flat list rather than a nested dict'
def get_joins(self, left=False, as_list=True):
if (self.query is None): self.get_query() joins = dict((self.ljoins if left else self.ijoins)) resource = self.resource for q in self.filters: subjoins = q._joins(resource, left=left)[0] joins.update(subjoins) parent = resource.parent if parent: pf = parent.rfilte...
'Get all field selectors in this filter'
def get_fields(self):
if (self.query is None): self.get_query() if self.vfltr: return self.vfltr.fields() else: return []
'Filter a set of rows by the effective virtual filter @param rows: a Rows object @param start: index of the first matching record to select @param limit: maximum number of records to select'
def __call__(self, rows, start=None, limit=None):
vfltr = self.get_filter() if ((rows is None) or (vfltr is None)): return rows resource = self.resource if (start is None): start = 0 first = start if (limit is not None): last = (start + limit) if (last < first): (first, last) = (last, first) i...
'Apply all extra filters on a list of record ids @param ids: the pre-filtered set of record IDs @param limit: the maximum number of matching IDs to establish, None to find all matching IDs @return: a sequence of matching IDs'
def apply_extra_filters(self, ids, start=None, limit=None):
resource = self.resource efilters = self.efilters methods = self.extra_filter_methods filters = [] append = filters.append for (method, expression) in efilters: if callable(method): append((method, expression)) else: method = methods.get(method) ...
'Get the total number of matching records @param left: left outer joins @param distinct: count only distinct rows'
def count(self, left=None, distinct=False):
distinct |= self.distinct resource = self.resource if (resource is None): return 0 table = resource.table vfltr = self.get_filter() if ((vfltr is None) and (not distinct)): tablename = table._tablename ijoins = S3Joins(tablename, self.get_joins(left=False)) ljoins...
'String representation of the instance'
def __repr__(self):
resource = self.resource inner_joins = self.get_joins(left=False) if inner_joins: inner = S3Joins(resource.tablename, inner_joins) ijoins = ', '.join([str(j) for j in inner.as_list()]) else: ijoins = None left_joins = self.get_joins(left=True) if left_joins: le...
'Generate a Query from a URL boundary box query; supports multiple bboxes, but optimised for the usual case of just 1 @param resource: the resource @param get_vars: the URL GET vars'
@staticmethod def parse_bbox_query(resource, get_vars):
tablenames = ('gis_location', 'gis_feature_query', 'gis_layer_shapefile') POLYGON = 'POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))' query = None joins = {} if get_vars: table = resource.table tablename = resource.tablename fields = table.fields ...
'Serialize this filter as URL query @return: a Storage of URL GET variables'
def serialize_url(self):
resource = self.resource url_vars = Storage() for f in self.filters: sub = f.serialize_url(resource=resource) url_vars.update(sub) return url_vars
'Constructor, extracts (and represents) data from a resource @param resource: the resource @param fields: the fields to extract (selector strings) @param start: index of the first record @param limit: maximum number of records @param left: additional left joins required for custom filters @param orderby: orderby-expres...
def __init__(self, resource, fields, start=0, limit=None, left=None, orderby=None, groupby=None, distinct=False, virtual=True, count=False, getids=False, as_rows=False, represent=False, show_links=True, raw_data=False):
self.resource = resource self.table = table = resource.table self.aqueries = aqueries = {} parent = resource.parent if (parent and (parent.accessible_query is not None)): method = [] if parent._approved: method.append('read') if parent._unapproved: met...
'Initialize field data and effort estimates for representation Field data: allow representation per unique value (rather than record by record), together with bulk-represent this can reduce the total lookup effort per field to a single query Effort estimates: if no bulk-represent is available for a list:reference, then...
def init_field_data(self, rfields):
table = self.resource.table tablename = table._tablename pkey = str(table._id) field_data = {pkey: ({}, {}, False, False, False, False)} effort = {pkey: 0} for dfield in rfields: colname = dfield.colname effort[colname] = 0 ftype = dfield.ftype[:4] field_data[coln...
'Resolve the ORDERBY expression. @param orderby: the orderby expression from the caller @return: tuple (expr, aggr, fields, tables): expr: the orderby expression (resolved into Fields) aggr: the orderby expression with aggregations fields: the fields in the orderby tables: the tables required for the orderby @note: for...
def resolve_orderby(self, orderby):
table = self.resource.table tablename = table._tablename pkey = str(table._id) ljoins = self.ljoins ijoins = self.ijoins tables = set() adapter = S3DAL() if orderby: db = current.db items = self.resolve_expression(orderby) expr = [] aggr = [] field...
'Execute a query to determine the number/record IDs of all matching rows @param query: the query to execute @param join: the inner joins for this query @param left: the left joins for this query @param getids: also extract the IDs if all matching records @param orderby: ORDERBY expression for this query @return: tuple ...
def filter_query(self, query, join=None, left=None, getids=False, orderby=None):
db = current.db table = self.table if getids: field = table._id groupby = field else: field = table._id.count() groupby = None orderby = None vf = table.virtualfields osetattr(table, 'virtualfields', []) rows = db(query).select(field, join=join, left=l...
'Find all tables and fields to retrieve in the master query @param dfields: the requested fields (S3ResourceFields) @param vfields: the virtual filter fields @param joined_tables: the tables joined in the master query @param as_rows: whether to produce web2py Rows @param groupby: the GROUPBY expression from the caller ...
def master_fields(self, dfields, vfields, joined_tables, as_rows=False, groupby=None):
db = current.db tablename = self.resource.table._tablename tables = set() fields = {} extract = set() if groupby: items = self.resolve_expression(groupby) groupby = [] groupby_append = groupby.append for item in items: tname = None if isins...
'Determine which fields in joined tables haven\'t been retrieved in the master query @param all_fields: all requested fields (list of S3ResourceFields) @param master_fields: all fields in the master query, a dict {ColumnName: Field} @return: a nested dict {TableName: {ColumnName: Field}}, additionally required left joi...
def joined_fields(self, all_fields, master_fields):
resource = self.resource table = resource.table tablename = table._tablename fields = {} for rfield in all_fields: colname = rfield.colname if ((colname in master_fields) or (rfield.tname == tablename)): continue tname = rfield.tname if (tname not in field...
'Extract additional fields from a joined table: if there are fields in joined tables which haven\'t been extracted in the master query, then we perform a separate query for each joined table (this is faster than building a multi-table-join) @param tablename: name of the joined table @param query: the Query @param field...
def joined_query(self, tablename, query, fields, records, represent=False):
s3db = current.s3db ljoins = self.ljoins table = self.resource.table pkey = str(table._id) sresource = s3db.resource(tablename) (efields, ejoins, l, d) = sresource.resolve_selectors([]) tnames = (ljoins.extend(l) + list(fields['_left'].tables)) sjoins = ljoins.as_list(tablenames=tnames, ...
'Extract the data from rows and store them in self.field_data @param rows: the rows @param pkey: the primary key @param columns: the columns to extract @param join: the rows are the result of a join query @param records: the records dict to merge the data into @param represent: collect unique values per field and estim...
def extract(self, rows, pkey, columns, join=True, records=None, represent=False):
field_data = self.field_data effort = self.effort if (records is None): records = {} def get(key): (t, f) = key.split('.', 1) if join: return (lambda row, t=t, f=f: ogetattr(ogetattr(row, t), f)) else: return (lambda row, f=f: ogetattr(row, f)) ...
'Render the representations of the values for rfield in all records in the result @param rfield: the field (S3ResourceField) @param results: the output dict to update with the representations, structure: {RecordID: {ColumnName: Representation}}, the raw data will be a special item "_row" in the inner dict holding a Sto...
def render(self, rfield, results, none='-', raw_data=False, show_links=True):
colname = rfield.colname field_data = self.field_data (fvalues, frecords, joined, list_type, virtual, json_type) = field_data[colname] renderer = rfield.represent if (not callable(renderer)): renderer = (lambda v: (s3_unicode(v) if (v is not None) else none)) if ((not show_links) and has...
'Helper method to access the results as dict items, for backwards-compatibility @param key: the key @todo: migrate use-cases to .<key> notation, then deprecate'
def __getitem__(self, key):
if (key in ('rfields', 'numrows', 'ids', 'rows')): return getattr(self, key) else: raise AttributeError
'Extract all unique record IDs from rows, preserving the order by first match @param rows: the Rows @param pkey: the primary key @return: list of unique record IDs'
def getids(self, rows, pkey):
x = set() seen = x.add result = [] append = result.append for row in rows: row_id = row[pkey] if (row_id not in x): seen(row_id) append(row_id) return result
'Select a subset of rows by their record IDs @param rows: the Rows @param ids: the record IDs @param pkey: the primary key @return: the subset (Rows)'
def getrows(self, rows, ids, pkey):
if ids: ids = set(ids) subset = (lambda row: (row[pkey] in ids)) else: subset = (lambda row: False) return rows.find(subset)
'Build a subset [start:limit] from rows and ids @param rows: the Rows @param ids: all matching record IDs @param start: start index of the page @param limit: maximum length of the page @param has_id: whether the Rows contain the primary key @return: tuple (rows, page), with: rows = the Rows in the subset, in order page...
def subset(self, rows, ids, start=None, limit=None, has_id=True):
if (limit and (start is None)): start = 0 if ((start is not None) and (limit is not None)): rows = rows[start:(start + limit)] page = ids[start:(start + limit)] elif (start is not None): rows = rows[start:] page = ids[start:] else: page = ids return (r...
'Get the names of all tables that need to be joined for a field @param rfield: the field (S3ResourceField) @return: a set of tablenames'
@staticmethod def rfield_tables(rfield):
left = rfield.left if left: tablenames = set((j.first._tablename for tn in left for j in left[tn])) else: tablenames = set([rfield.tname]) return tablenames
'Resolve an orderby or groupby expression into its items @param expr: the orderby/groupby expression'
@staticmethod def resolve_expression(expr):
if isinstance(expr, str): items = expr.split(',') elif (not isinstance(expr, (list, tuple))): items = [expr] else: items = expr return items
'Configure the task table for interactive CRUD, setting defaults, widgets and hiding unnecessary fields @param task: the task name (will use a UUID if omitted) @param function: the function name (won\'t hide if omitted) @param args: the function position arguments @param vars: the function named arguments'
def configure_tasktable_crud(self, task=None, function=None, args=None, vars=None, period=3600):
if (args is None): args = [] if (vars is None): vars = {} T = current.T NONE = current.messages['NONE'] UNLIMITED = T('unlimited') tablename = self.TASK_TABLENAME table = current.db[tablename] table.uuid.readable = table.uuid.writable = False table.prevent_drift.reada...
'Wrapper to call an asynchronous task. - run from the main request @param task: The function which should be run - async if a worker is alive @param args: The list of unnamed args to send to the function @param vars: The list of named vars to send to the function @param timeout: The length of time available for the tas...
def async(self, task, args=None, vars=None, timeout=300):
if (args is None): args = [] if (vars is None): vars = {} tasks = current.response.s3.tasks if (not tasks): return False if (task not in tasks): return False if (not self._is_alive()): _args = [] for arg in args: if isinstance(arg, (int...
'Schedule a task in web2py Scheduler @param task: name of the function/task to be scheduled @param args: args to be passed to the scheduled task @param vars: vars to be passed to the scheduled task @param function_name: function name (if different from task name) @param start_time: start_time for the scheduled task @pa...
def schedule_task(self, task, args=None, vars=None, function_name=None, start_time=None, next_run_time=None, stop_time=None, repeats=None, period=None, timeout=None, enabled=None, group_name=None, ignore_duplicate=False, sync_output=0):
if (args is None): args = [] if (vars is None): vars = {} if ((not ignore_duplicate) and self._duplicate_task_exists(task, args, vars)): current.log.warning('Duplicate Task, Not Inserted', value=task) return False kwargs = {} if (function_name is None): ...
'Checks if given task already exists in the Scheduler and both coincide with their execution time @param task: name of the task function @param args: the job position arguments (list) @param vars: the job named arguments (dict)'
def _duplicate_task_exists(self, task, args, vars):
db = current.db ttable = db.scheduler_task _args = json.dumps(args) query = (((ttable.function_name == task) & (ttable.args == _args)) & ttable.status.belongs(['RUNNING', 'QUEUED', 'ALLOCATED'])) jobs = db(query).select(ttable.vars) for job in jobs: job_vars = json.loads(job.vars) ...
'Returns True if there is at least 1 active worker to run scheduled tasks - run from the main request NB Can\'t run this 1/request at the beginning since the tables only get defined in zz_last'
def _is_alive(self):
db = current.db cache = current.response.s3.cache now = datetime.datetime.now() offset = datetime.timedelta(minutes=1) table = db.scheduler_worker query = (table.last_heartbeat > (now - offset)) worker_alive = db(query).select(table.id, limitby=(0, 1), cache=cache).first() if worker_aliv...
'Reset the status of a task to QUEUED after FAILED @param task_id: the task record ID'
@staticmethod def reset(task_id):
db = current.db ttable = db.scheduler_task query = ((ttable.id == task_id) & (ttable.status == 'FAILED')) task = db(query).select(ttable.id, limitby=(0, 1)).first() if task: task.update_record(status='QUEUED')
'Activate the authentication passed from the caller to this new request - run from within the task NB This is so simple that we don\'t normally run via this API - this is just kept as an example of what needs to happen within the task'
def authenticate(self, user_id):
current.auth.s3_impersonate(user_id)
'S3DataTable constructor @param rfields: A list of S3Resourcefield @param data: A list of Storages the key is of the form table.field The value is the data to be displayed in the dataTable @param start: the first row to return from the data @param limit: the (maximum) number of records to return @param filterString: Th...
def __init__(self, rfields, data, start=0, limit=None, filterString=None, orderby=None, empty=False):
self.data = data self.rfields = rfields self.empty = empty colnames = [] heading = {} append = colnames.append for rfield in rfields: colname = rfield.colname heading[colname] = rfield.label append(colname) self.colnames = colnames self.heading = heading d...
'Method to render the dataTable into html @param totalrows: The total rows in the unfiltered query. @param filteredrows: The total rows in the filtered query. @param id: The id of the table these need to be unique if more than one dataTable is to be rendered on the same page. If this is not passed in then a unique id w...
def html(self, totalrows, filteredrows, id=None, draw=1, **attr):
flist = self.colnames if (not id): id = ('list_%s' % self.id_counter) self.id_counter += 1 self.id = id bulkActions = attr.get('dt_bulk_actions', None) bulkCol = attr.get('dt_bulk_col', 0) if (bulkCol > len(flist)): bulkCol = len(flist) action_col = attr.get('dt_actio...
'Return the i18n strings needed by dataTables - called by views/dataTables.html'
@staticmethod def i18n():
T = current.T scripts = [('i18n.sortAscending="%s"' % T('activate to sort column ascending')), ('i18n.sortDescending="%s"' % T('activate to sort column descending')), ('i18n.first="%s"' % T('First')), ('i18n.last="%s"' % T('Last')), ('i18n.next="%s"' % T('Next')), ('i18n.previous="%s"' %...
'Method to render the data into a json object @param totalrows: The total rows in the unfiltered query. @param displayrows: The total rows in the filtered query. @param id: The id of the table for which this ajax call will respond to. @param draw: An unaltered copy of draw sent from the client used by dataTables as a d...
def json(self, totalrows, displayrows, id, draw, stringify=True, **attr):
flist = self.colnames action_col = attr.get('dt_action_col', 0) if (action_col != 0): if ((action_col == (-1)) or (action_col >= len(flist))): action_col = (len(flist) - 1) flist = ((flist[1:(action_col + 1)] + [flist[0]]) + flist[(action_col + 1):]) bulkActions = attr.get('d...
'Method to extract the configuration data from S3 globals and store them as an attr variable. - used by Survey module @return: dictionary of attributes which can be passed into html() @param attr: dictionary of attributes which can be passed in dt_pageLength : The default number of records that will be shown dt_paginat...
@staticmethod def getConfigData():
s3 = current.response.s3 attr = Storage() if s3.datatable_ajax_source: attr.dt_ajax_url = s3.datatable_ajax_source if s3.actions: attr.dt_actions = s3.actions if s3.dataTableBulkActions: attr.dt_bulk_actions = s3.dataTableBulkActions if s3.dataTable_pageLength: at...
'Calculate the export formats that can be added to the table @param id: the unique dataTable ID @param rfields: optional list of field selectors for exports @param permalink: search result URL @param base_url: the base URL of the datatable (without method or query vars) to construct format URLs'
@staticmethod def export_formats(rfields=None, permalink=None, base_url=None):
T = current.T s3 = current.response.s3 request = current.request if (base_url is None): base_url = request.url if s3.datatable_ajax_source: default_url = s3.datatable_ajax_source else: default_url = base_url default_url = re.sub('(\\/[a-zA-Z0-9_]*)(\\.[a-zA-Z]*)', '\\...
'Configure default action buttons @param resource: the resource @param r: the request, if specified, all action buttons will be linked to the controller/function of this request rather than to prefix/name of the resource @param custom_actions: custom actions as list of dicts like {"label":label, "url":url, "_class":cla...
@staticmethod def defaultActionButtons(resource, custom_actions=None, r=None):
from s3crud import S3CRUD s3 = current.response.s3 auth = current.auth actions = s3.actions = None table = resource.table has_permission = auth.s3_has_permission ownership_required = auth.permission.ownership_required labels = s3.crud_labels args = ['[id]'] if (r is not None): ...
'Method to wrap the html for a dataTable in a form, add the export formats and the config details required by dataTables @param html: The html table @param id: The id of the table @param orderby: the sort details see http://datatables.net/reference/option/order @param rfields: The list of resource fields @param attr: d...
@staticmethod def htmlConfig(html, id, orderby, rfields=None, cache=None, **attr):
from gluon.serializers import json as jsons s3 = current.response.s3 settings = current.deployment_settings dataTableID = s3.dataTableID if ((not dataTableID) or (not isinstance(dataTableID, list))): dataTableID = s3.dataTableID = [id] elif (id not in dataTableID): dataTableID.ap...
'Method to render the data as an html table. This is of use if an html table is required without the dataTable goodness. However if you want html for a dataTable then use the html() method @param id: The id of the table @param flist: The list of fields @param action_col: The column where action columns will be displaye...
def table(self, id, flist=None, action_col=0):
data = self.data heading = self.heading start = self.start end = self.end if (not flist): flist = self.colnames header = THEAD() tr = TR() for field in flist: if (field == 'BULK'): tr.append(TH('')) else: tr.append(TH(heading[field])) h...
'Method to render the data into a json object @param totalrows: The total rows in the unfiltered query. @param displayrows: The total rows in the filtered query. @param id: The id of the table for which this ajax call will respond to. @param draw: An unaltered copy of draw sent from the client used by dataTables as a d...
def aadata(self, totalrows, displayrows, id, draw, flist, stringify=True, action_col=None, **attr):
data = self.data if (not flist): flist = self.colnames start = self.start end = self.end if (action_col is None): action_col = attr.get('dt_action_col', 0) structure = {} aadata = [] for i in xrange(start, end): row = data[i] details = [] for field...
'Constructor @param resource: the S3Resource @param list_fields: the list fields (list of field selector strings) @param records: the records @param start: index of the first item @param limit: maximum number of items @param total: total number of available items @param list_id: the HTML ID for this list @param layout:...
def __init__(self, resource, list_fields, records, start=None, limit=None, total=None, list_id=None, layout=None, row_layout=None):
self.resource = resource self.list_fields = list_fields self.records = records if (list_id is None): self.list_id = 'datalist' else: self.list_id = list_id if (layout is not None): self.layout = layout else: self.layout = S3DataListLayout() self.row_layout...
'Render list data as HTML (nested DIVs) @param start: index of the first item (in this page) @param limit: total number of available items @param pagesize: maximum number of items per page @param rowsize: number of items per row @param ajaxurl: the URL to Ajax-update the datalist @param empty: message to display if the...
def html(self, start=None, limit=None, pagesize=None, rowsize=None, ajaxurl=None, empty=None, popup_url=None, popup_title=None):
T = current.T resource = self.resource list_fields = self.list_fields rfields = resource.resolve_selectors(list_fields)[0] list_id = self.list_id render = self.layout render_row = self.row_layout if (not rowsize): rowsize = 1 pkey = str(resource._id) records = self.record...
'Iterator to group data list items into rows @param iterable: the items iterable @param length: the number of items per row'
@staticmethod def groups(iterable, length):
iterable = iter(iterable) group = list(islice(iterable, length)) while group: (yield group) group = list(islice(iterable, length)) raise StopIteration
'Constructor @param profile: table name of the master resource of the profile page (if used for a profile), can be used in popup URLs to indicate the master resource'
def __init__(self, profile=None):
self.profile = profile
'Wrapper for render_item. @param list_id: the HTML ID of the list @param item_id: the HTML ID of the item @param resource: the S3Resource to render @param rfields: the S3ResourceFields to render @param record: the record as dict'
def __call__(self, list_id, item_id, resource, rfields, record):
item = DIV(_id=item_id, _class=self.item_class) header = self.render_header(list_id, item_id, resource, rfields, record) if (header is not None): item.append(header) body = self.render_body(list_id, item_id, resource, rfields, record) if (body is not None): item.append(body) retu...
'@todo: Render the card header @param list_id: the HTML ID of the list @param item_id: the HTML ID of the item @param resource: the S3Resource to render @param rfields: the S3ResourceFields to render @param record: the record as dict'
def render_header(self, list_id, item_id, resource, rfields, record):
return None
'Render the card body @param list_id: the HTML ID of the list @param item_id: the HTML ID of the item @param resource: the S3Resource to render @param rfields: the S3ResourceFields to render @param record: the record as dict'
def render_body(self, list_id, item_id, resource, rfields, record):
pkey = str(resource._id) body = DIV(_class='media-body') render_column = self.render_column for rfield in rfields: if ((not rfield.show) or (rfield.colname == pkey)): continue column = render_column(item_id, rfield, record) if (column is not None): table_c...
'@todo: Render a body icon @param list_id: the HTML ID of the list @param resource: the S3Resource to render'
def render_icon(self, list_id, resource):
return None
'@todo: Render the toolbox @param list_id: the HTML ID of the list @param resource: the S3Resource to render @param record: the record as dict'
def render_toolbox(self, list_id, resource, record):
return None
'Render a data column. @param item_id: the HTML element ID of the item @param rfield: the S3ResourceField for the column @param record: the record (from S3Resource.select)'
def render_column(self, item_id, rfield, record):
colname = rfield.colname if (colname not in record): return None value = record[colname] value_id = ('%s-%s' % (item_id, rfield.colname.replace('.', '_'))) label = LABEL(('%s:' % rfield.label), _for=value_id, _class='dl-field-label') value = SPAN(value, _id=value_id, _class='dl-field-val...
'Constructor'
def __init__(self, name, type=None):
if ((not isinstance(name, basestring)) or (not name)): raise SyntaxError('name required') self.name = str(name) self.type = type self.op = None
'Extract a value from a Row @param resource: the resource @param row: the Row @param field: the field @return: field if field is not a Field/S3FieldSelector instance, the value from the row otherwise'
@classmethod def extract(cls, resource, row, field):
error = (lambda fn: KeyError(('Field not found: %s' % fn))) t = type(field) if isinstance(field, Field): colname = str(field) (tname, fname) = colname.split('.', 1) elif (t is S3FieldSelector): rfield = S3ResourceField(resource, field.name) colname = rfield.colna...
'Resolve this field against a resource @param resource: the resource'
def resolve(self, resource):
return S3ResourceField(resource, self.name)
'Resolve a selector (=field path) against a resource @param resource: the S3Resource to resolve against @param selector: the field selector string @param tail: tokens to append to the selector The general syntax for a selector is: selector = {[alias].}{[key]$}[field|selector] (Parts in {} are optional, | indicates alte...
@classmethod def resolve(cls, resource, selector, tail=None):
if (not selector): raise SyntaxError(('Invalid selector: %s' % selector)) tokens = re.split('(\\.|\\$)', selector) if tail: tokens.extend(tail) parser = cls(resource, None, tokens) parser.original = selector return parser
'Constructor - not to be called directly, use resolve() instead @param resource: the S3Resource @param table: the table @param tokens: the tokens as list'
def __init__(self, resource, table, tokens):
s3db = current.s3db if (table is None): table = resource.table self.original = None tname = self.tname = table._tablename self.fname = None self.field = None self.method = None self.ftype = None self.virtual = False self.colname = None self.joins = {} self.distinc...
'Resolve a field name against the table, recognizes "id" as table._id.name, and "uid" as current.xml.UID. @param table: the Table @param fieldname: the field name @return: tuple (Field, Field.Method)'
@staticmethod def _resolve_field(table, fieldname):
method = None if (fieldname == 'uid'): fieldname = current.xml.UID if (fieldname == 'id'): field = table._id elif (fieldname in table.fields): field = ogetattr(table, fieldname) else: field = None try: method = ogetattr(table, fieldname) ex...
'Resolve a foreign key into the referenced table and the join and left join between the current table and the referenced table @param table: the current Table @param fieldname: the fieldname of the foreign key @return: tuple of (referenced table, join, left join) @raise: AttributeError is either the field or the refere...
@staticmethod def _resolve_key(table, fieldname):
if (fieldname in table.fields): f = table[fieldname] else: raise AttributeError(('key not found: %s' % fieldname)) (ktablename, pkey, multiple) = s3_get_foreign_key(f, m2m=False) if (not ktablename): raise SyntaxError(('%s is not a foreign key' % f)) k...
'Resolve a table alias into the linked table (component, linktable or free join), and the joins and left joins between the current resource and the linked table. @param resource: the current S3Resource @param alias: the alias @return: tuple of (linked table, joins, left joins, multiple, distinct), the two latter being ...
@staticmethod def _resolve_alias(resource, alias):
if (alias in ('~', resource.alias)): return (resource.table, None, False, False) multiple = True linked = resource.linked if (linked and (linked.alias == alias)): linktable = resource.table ktable = linked.table join = [ktable.on((ktable[linked.fkey] == linktable[linked.r...
'Constructor @param resource: the resource @param selector: the field selector (string)'
def __init__(self, resource, selector, label=None):
self.resource = resource self.selector = selector lf = S3FieldPath.resolve(resource, selector) self.tname = lf.tname self.fname = lf.fname self.colname = lf.colname self._joins = lf.joins self.distinct = lf.distinct self.multiple = lf.multiple self._join = None self.field = l...
'String representation of this instance'
def __repr__(self):
return ("<S3ResourceField selector='%s' label='%s' table='%s' field='%s' type='%s'>" % (self.selector, self.label, self.tname, self.fname, self.ftype))
'Implicit join (Query) for this field, for backwards-compatibility'
@property def join(self):
if (self._join is not None): return self._join join = self._join = {} for (tablename, joins) in self._joins.items(): query = None for expression in joins: if (query is None): query = expression.second else: query &= expression.s...
'The left joins for this field, for backwards-compability'
@property def left(self):
return self._joins
'Extract the value for this field from a row @param row: the Row @param represent: render a text representation for the value @param lazy: return a lazy representation handle if available'
def extract(self, row, represent=False, lazy=False):
tname = self.tname fname = self.fname colname = self.colname error = ('Field not found in Row: %s' % colname) if (type(row) is Row): try: if (tname in row.__dict__): value = ogetattr(ogetattr(row, tname), fname) else: val...
'Check whether the field type is a fixed set lookup (IS_IN_SET) @return: True if field type is a fixed set lookup, else False'
@property def is_lookup(self):
is_lookup = self._is_lookup if (is_lookup is None): is_lookup = False ftype = self.ftype field = self.field if field: requires = field.requires if requires: if (not isinstance(requires, (list, tuple))): requires = [requi...
'Check whether the field type is numeric (lazy property) @return: True if field type is integer or double, else False'
@property def is_numeric(self):
is_numeric = self._is_numeric if (is_numeric is None): ftype = self.ftype field = self.field if ((ftype == 'integer') and self.is_lookup): is_numeric = False else: is_numeric = (ftype in ('integer', 'double')) self._is_numeric = is_numeric retu...
'Check whether the field type is a string type (lazy property) @return: True if field type is string or text, else False'
@property def is_string(self):
is_string = self._is_string if (is_string is None): is_string = (self.ftype in ('string', 'text')) self._is_string = is_string return is_string
'Check whether the field type is date/time (lazy property) @return: True if field type is datetime, date or time, else False'
@property def is_datetime(self):
is_datetime = self._is_datetime if (is_datetime is None): is_datetime = (self.ftype in ('datetime', 'date', 'time')) self._is_datetime = is_datetime return is_datetime
'Check whether the field type is a reference (lazy property) @return: True if field type is a reference, else False'
@property def is_reference(self):
is_reference = self._is_reference if (is_reference is None): is_reference = (self.ftype[:9] == 'reference') self._is_reference = is_reference return is_reference
'Check whether the field type is a list (lazy property) @return: True if field type is a list, else False'
@property def is_list(self):
is_list = self._is_list if (is_list is None): is_list = (self.ftype[:5] == 'list:') self._is_list = is_list return is_list
'Constructor @param tablename: the name of the master table @param joins: list of joins'
def __init__(self, tablename, joins=None):
self.tablename = tablename self.joins = {} self.tables = set() self.add(joins)
'Iterate over the names of all joined tables in the collection'
def __iter__(self):
return self.joins.__iter__()
'Get the list of joins for a table @param tablename: the tablename'
def __getitem__(self, tablename):
return self.joins.__getitem__(tablename)
'Update the joins for a table @param tablename: the tablename @param joins: the list of joins for this table'
def __setitem__(self, tablename, joins):
master = self.tablename joins_dict = self.joins tables = current.db._adapter.tables joins_dict[tablename] = joins if (len(joins) > 1): for join in joins: try: tname = join.first._tablename except AttributeError: tname = str(join.first) ...
'Return the number of tables in the join, for boolean test of this instance ("if joins:")'
def __len__(self):
return len(self.tables)
'Get a list of names of all joined tables'
def keys(self):
return self.joins.keys()
'Get a list of tuples (tablename, [joins]) for all joined tables'
def items(self):
return self.joins.items()
'Get a list of joins for all joined tables @return: a nested list like [[join, join, ...], ...]'
def values(self):
return self.joins.values()
'Add joins to this collection @param joins: a join or a list/tuple of joins @return: the list of names of all tables for which joins have been added to the collection'
def add(self, joins):
tablenames = set() if joins: if (not isinstance(joins, (list, tuple))): joins = [joins] for join in joins: tablename = join.first._tablename self[tablename] = [join] tablenames.add(tablename) return list(tablenames)
'Extend this collection with the joins from another collection @param other: the other collection (S3Joins), or a dict like {tablename: [join, join]} @return: the list of names of all tables for which joins have been added to the collection'
def extend(self, other):
if (type(other) is S3Joins): add = self.tables.add else: add = None joins = (self.joins if (type(other) is S3Joins) else self) for tablename in other: if (tablename not in self.joins): joins[tablename] = other[tablename] if add: add(tablena...
'String representation of this collection'
def __repr__(self):
return ('<S3Joins %s>' % str([str(j) for j in self.as_list()]))
'Return joins from this collection as list @param tablenames: the names of the tables for which joins shall be returned, defaults to all tables in the collection. Dependencies will be included automatically (if available) @param aqueries: dict of accessible-queries {tablename: query} to include in the joins; if there i...
def as_list(self, tablenames=None, aqueries=None, prefer=None):
accessible_query = current.auth.s3_accessible_query if (tablenames is None): tablenames = self.tables else: tablenames = set(tablenames) skip = set() if prefer: preferred_joins = prefer.as_list(tablenames=tablenames) for join in preferred_joins: try: ...
'Sort a list of left-joins by their interdependency @param joins: the list of joins'
@classmethod def sort(cls, joins):
if (len(joins) <= 1): return joins r = list(joins) tables = current.db._adapter.tables append = r.append head = None for i in xrange(len(joins)): join = r.pop(0) head = join tablenames = tables(join.second) for j in r: try: tn =...
'Constructor'
def __init__(self, op, left=None, right=None):
if (op not in self.OPERATORS): raise SyntaxError(('Invalid operator: %s' % op)) self.op = op self.left = left self.right = right
'AND'
def __and__(self, other):
return S3ResourceQuery(self.AND, self, other)
'OR'
def __or__(self, other):
return S3ResourceQuery(self.OR, self, other)
'NOT'
def __invert__(self):
if (self.op == self.NOT): return self.left else: return S3ResourceQuery(self.NOT, self)
'Get all field selectors involved with this query'
def fields(self):
op = self.op l = self.left r = self.right if (op in (self.AND, self.OR)): lf = l.fields() rf = r.fields() return (lf + rf) elif (op == self.NOT): return l.fields() elif isinstance(l, S3FieldSelector): return [l.name] else: return []
'Split this query into a real query and a virtual one (AND) @param resource: the S3Resource @return: tuple (DAL-translatable sub-query, virtual filter), both S3ResourceQuery instances'
def split(self, resource):
op = self.op l = self.left r = self.right if (op == self.AND): (lq, lf) = (l.split(resource) if isinstance(l, S3ResourceQuery) else (l, None)) (rq, rf) = (r.split(resource) if isinstance(r, S3ResourceQuery) else (r, None)) q = lq if (rq is not None): if (q is ...
'Placeholder for transformation method @param resource: the S3Resource'
def transform(self, resource):
return self
'Convert this S3ResourceQuery into a DAL query, ignoring virtual fields (the necessary joins for this query can be constructed with the joins() method) @param resource: the resource to resolve the query against'
def query(self, resource):
op = self.op l = self.left r = self.right if (op == self.AND): l = (l.query(resource) if isinstance(l, S3ResourceQuery) else l) r = (r.query(resource) if isinstance(r, S3ResourceQuery) else r) if ((l is None) or (r is None)): return None elif ((l is False) or ...
'Translate a filter expression into a DAL query @param op: the operator @param l: the left operand @param r: the right operand'
def _query_bare(self, op, l, r):
if (op == self.CONTAINS): q = l.contains(r, all=True) elif (op == self.ANYOF): q = l.contains(r, all=False) elif (op == self.BELONGS): q = self._query_belongs(l, r) elif (op == self.TYPEOF): q = self._query_typeof(l, r) elif (op == self.LIKE): if current.deplo...
'Translate TYPEOF into DAL expression @param l: the left operand @param r: the right operand'
def _query_typeof(self, l, r):
(hierarchy, field, nodeset, none) = self._resolve_hierarchy(l, r) if (not hierarchy): return self._query_belongs(l, r) if (not field): return None list_type = (str(field.type)[:5] == 'list:') if nodeset: if list_type: q = field.contains(list(nodeset)) elif...
'Resolve the hierarchical lookup in a typeof-query @param l: the left operand @param r: the right operand'
@classmethod def _resolve_hierarchy(cls, l, r):
from s3hierarchy import S3Hierarchy tablename = l.tablename hierarchy = S3Hierarchy(tablename) if (hierarchy.config is None): (ktablename, key) = s3_get_foreign_key(l)[:2] if ktablename: hierarchy = S3Hierarchy(ktablename) else: key = None list_type = (str(l.t...
'Resolve BELONGS into a DAL expression (or S3ResourceQuery if field is an S3FieldSelector) @param l: the left operand @param r: the right operand @param field: alternative left operand'
@staticmethod def _query_belongs(l, r, field=None):
if (field is None): field = l expr = None none = False if (not isinstance(r, (list, tuple, set))): items = [r] else: items = r if (None in items): none = True items = [item for item in items if (item is not None)] wildcard = False if (str(l.type) i...
'Resolve INTERSECTS into a DAL expression; will be ignored for non-spatial DBs @param l: the left operand (Field) @param r: the right operand'
def _query_intersects(self, l, r):
if current.deployment_settings.get_gis_spatialdb(): expr = None if (str(l.type)[:3] == 'geo'): if isinstance(r, basestring): from shapely.wkt import loads as wkt_loads try: wkt_loads(r) except Exception: ...
'Probe whether the row matches the query @param resource: the resource to resolve the query against @param row: the DB row @param virtual: execute only virtual queries'
def __call__(self, resource, row, virtual=True):
if (self.op == self.AND): l = self.left(resource, row, virtual=False) r = self.right(resource, row, virtual=False) if (l is None): return r if (r is None): return l return (l and r) elif (self.op == self.OR): l = self.left(resource, row, vi...