relational/ 0000755 0001750 0001750 00000000000 12757112451 012247 5 ustar salvo salvo relational/relational.desktop 0000644 0001750 0001750 00000000552 12757112451 015776 0 ustar salvo salvo [Desktop Entry]
Name=Relational
GenericName=Relational Algebra
GenericName[it]=Algebra Relazionale
Comment=Learn and experiment relational algebra
Comment[it]=Impara l'algebra relazionale
Exec=relational %F
Icon=relational
Terminal=false
Type=Application
Categories=Education;
Keywords=database;relational;algebra;educational;learn;educativo;relazionale;impara;
relational/setup/ 0000755 0001750 0001750 00000000000 12757112451 013407 5 ustar salvo salvo relational/setup/python3-relational.setup.py 0000644 0001750 0001750 00000001516 12757112451 020657 0 ustar salvo salvo # -*- coding: utf-8 -*-
# Relational
# Copyright (C) 2008-2011 Salvo "LtWorf" Tomaselli
#
# Relational is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
import installer_common
installer_common.c_setup('relational')
relational/setup/installer_common.py 0000644 0001750 0001750 00000002201 12757112451 017321 0 ustar salvo salvo # Relational
# Copyright (C) 2008-2016 Salvo "LtWorf" Tomaselli
#
# Relational is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
from distutils.core import setup
def c_setup(name):
setup(
version='2.5',
name=name,
packages=(name,),
author="Salvo 'LtWorf' Tomaselli",
author_email='tiposchi@tiscali.it',
maintainer="Salvo 'LtWorf' Tomaselli",
maintainer_email='tiposchi@tiscali.it',
url='http://ltworf.github.io/relational/',
license='GPL3',
)
relational/setup/relational.setup.py 0000644 0001750 0001750 00000001472 12757112451 017256 0 ustar salvo salvo # Relational
# Copyright (C) 2008-2011 Salvo "LtWorf" Tomaselli
#
# Relational is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
import installer_common
installer_common.c_setup('relational_gui')
relational/setup/__pycache__/ 0000755 0001750 0001750 00000000000 12757112451 015617 5 ustar salvo salvo relational/setup/relational-cli.setup.py 0000644 0001750 0001750 00000001527 12757112451 020024 0 ustar salvo salvo # -*- coding: utf-8 -*-
# Relational
# Copyright (C) 2008-2011 Salvo "LtWorf" Tomaselli
#
# Relational is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
import installer_common
installer_common.c_setup('relational_readline')
relational/CREDITS 0000644 0001750 0001750 00000000276 12757112451 013274 0 ustar salvo salvo Ori Avtalion for suggesting some improvements
Chris Lamb for being interested
Emilio Di Prima for the windows port
Konstantin Lepa (for the termcolor module)
relational/relational_readline/ 0000755 0001750 0001750 00000000000 12757112451 016244 5 ustar salvo salvo relational/relational_readline/__init__.py 0000644 0001750 0001750 00000000000 12757112451 020343 0 ustar salvo salvo relational/relational_readline/linegui.py 0000644 0001750 0001750 00000024635 12757112451 020264 0 ustar salvo salvo # Relational
# Copyright (C) 2010-2016 Salvo "LtWorf" Tomaselli
#
# Relational is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
# Initial readline code from
# http://www.doughellmann.com/PyMOTW/readline/index.html
import readline
import logging
import os.path
import os
import sys
from relational import relation, parser, rtypes
from relational import maintenance
from xtermcolor import colorize
PROMPT_COLOR = 0xffff00
ERROR_COLOR = 0xff0000
TTY = os.isatty(0) and os.isatty(1)
def printtty(*args, **kwargs):
'''
Prints only if stdout and stdin are a tty
'''
if TTY:
print(*args,**kwargs)
class SimpleCompleter(object):
'''Handles completion'''
def __init__(self, options):
'''Takes a list of valid completion options'''
self.options = sorted(options)
return
def add_completion(self, option):
'''Adds one string to the list of the valid completion options'''
if option not in self.options:
self.options.append(option)
self.options.sort()
def remove_completion(self, option):
'''Removes one completion from the list of the valid completion options'''
if option in self.options:
self.options.remove(option)
pass
def complete(self, text, state):
response = None
if state == 0:
# This is the first time for this text, so build a match list.
if text:
self.matches = [s
for s in self.options
if s and s.startswith(text)]
# Add the completion for files here
try:
d = os.path.dirname(text)
listf = os.listdir(d)
d += "/"
except:
d = ""
listf = os.listdir('.')
for i in listf:
i = (d + i).replace('//', '/')
if i.startswith(text):
if os.path.isdir(i):
i = i + "/"
self.matches.append(i)
logging.debug('%s matches: %s', repr(text), self.matches)
else:
self.matches = self.options[:]
logging.debug('(empty input) matches: %s', self.matches)
# Return the state'th item from the match list,
# if we have that many.
try:
response = self.matches[state]
except IndexError:
response = None
logging.debug('complete(%s, %s) => %s',
repr(text), state, repr(response))
return response
relations = {}
completer = SimpleCompleter(
['SURVEY', 'LIST', 'LOAD ', 'UNLOAD ', 'HELP ', 'QUIT', 'SAVE ', '_PRODUCT ', '_UNION ', '_INTERSECTION ',
'_DIFFERENCE ', '_JOIN ', '_LJOIN ', '_RJOIN ', '_FJOIN ', '_PROJECTION ', '_RENAME_TO ', '_SELECTION ', '_RENAME ', '_DIVISION '])
def load_relation(filename, defname=None):
if not os.path.isfile(filename):
print (colorize(
"%s is not a file" % filename, ERROR_COLOR), file=sys.stderr)
return None
f = filename.split('/')
if defname == None:
defname = f[len(f) - 1].lower()
if defname.endswith(".csv"): # removes the extension
defname = defname[:-4]
if not rtypes.is_valid_relation_name(defname):
print (colorize(
"%s is not a valid relation name" % defname, ERROR_COLOR), file=sys.stderr)
return
try:
relations[defname] = relation.relation(filename)
completer.add_completion(defname)
printtty(colorize("Loaded relation %s" % defname, 0x00ff00))
return defname
except Exception as e:
print (colorize(e, ERROR_COLOR), file=sys.stderr)
return None
def survey():
'''performs a survey'''
post = {'software': 'Relational algebra (cli)', 'version': version}
fields = ('System', 'Country', 'School', 'Age', 'How did you find',
'email (only if you want a reply)', 'Comments')
for i in fields:
a = input('%s: ' % i)
post[i] = a
maintenance.send_survey(post)
def help(command):
'''Prints help on the various functions'''
p = command.split(' ', 1)
if len(p) == 1:
print ('HELP command')
print (
'To execute a query:\n[relation =] query\nIf the 1st part is omitted, the result will be stored in the relation last_.')
print (
'To prevent from printing the relation, append a ; to the end of the query.')
print (
'To insert relational operators, type _OPNAME, they will be internally replaced with the correct symbol.')
print (
'Rember: the tab key is enabled and can be very helpful if you can\'t remember something.')
return
cmd = p[1]
if cmd == 'QUIT':
print ('Quits the program')
elif cmd == 'LIST':
print ('Lists the relations loaded')
elif cmd == 'LOAD':
print ('LOAD filename [relationame]')
print ('Loads a relation into memory')
elif cmd == 'UNLOAD':
print ('UNLOAD relationame')
print ('Unloads a relation from memory')
elif cmd == 'SAVE':
print ('SAVE filename relationame')
print ('Saves a relation in a file')
elif cmd == 'HELP':
print ('Prints the help on a command')
elif cmd == 'SURVEY':
print ('Fill and send a survey')
else:
print ('Unknown command: %s' % cmd)
def exec_line(command):
command = command.strip()
if command.startswith(';'):
return
elif command == 'QUIT':
sys.exit(0)
elif command.startswith('HELP'):
help(command)
elif command == 'LIST': # Lists all the loaded relations
for i in relations:
if not i.startswith('_'):
print (i)
elif command == 'SURVEY':
survey()
elif command.startswith('LOAD '): # Loads a relation
pars = command.split(' ')
if len(pars) == 1:
print (colorize("Missing parameter", ERROR_COLOR))
return
filename = pars[1]
if len(pars) > 2:
defname = pars[2]
else:
defname = None
load_relation(filename, defname)
elif command.startswith('UNLOAD '):
pars = command.split(' ')
if len(pars) < 2:
print (colorize("Missing parameter", ERROR_COLOR))
return
if pars[1] in relations:
del relations[pars[1]]
completer.remove_completion(pars[1])
else:
print (colorize("No such relation %s" % pars[1], ERROR_COLOR))
pass
elif command.startswith('SAVE '):
pars = command.split(' ')
if len(pars) != 3:
print (colorize("Missing parameter", ERROR_COLOR))
return
filename = pars[1]
defname = pars[2]
if defname not in relations:
print (colorize("No such relation %s" % defname, ERROR_COLOR))
return
try:
relations[defname].save(filename)
except Exception as e:
print (colorize(e, ERROR_COLOR))
else:
exec_query(command)
def replacements(query):
'''This funcion replaces ascii easy operators with the correct ones'''
query = query.replace(u'_PRODUCT', parser.PRODUCT)
query = query.replace(u'_UNION', parser.UNION)
query = query.replace(u'_INTERSECTION', parser.INTERSECTION)
query = query.replace(u'_DIFFERENCE', parser.DIFFERENCE)
query = query.replace(u'_JOIN', parser.JOIN)
query = query.replace(u'_LJOIN', parser.JOIN_LEFT)
query = query.replace(u'_RJOIN', parser.JOIN_RIGHT)
query = query.replace(u'_FJOIN', parser.JOIN_FULL)
query = query.replace(u'_PROJECTION', parser.PROJECTION)
query = query.replace(u'_RENAME_TO', parser.ARROW)
query = query.replace(u'_SELECTION', parser.SELECTION)
query = query.replace(u'_RENAME', parser.RENAME)
query = query.replace(u'_DIVISION', parser.DIVISION)
return query
def exec_query(command):
'''This function executes a query and prints the result on the screen
if the command terminates with ";" the result will not be printed
'''
# If it terminates with ; doesn't print the result
if command.endswith(';'):
command = command[:-1]
printrel = False
else:
printrel = True
# Performs replacements for weird operators
command = replacements(command)
# Finds the name in where to save the query
parts = command.split('=', 1)
relname,query = maintenance.UserInterface.split_query(command)
# Execute query
try:
pyquery = parser.parse(query)
result = pyquery(relations)
printtty(colorize("-> query: %s" % pyquery, 0x00ff00))
if printrel:
print ()
print (result)
relations[relname] = result
completer.add_completion(relname)
except Exception as e:
print (colorize(str(e), ERROR_COLOR))
def main(files=[]):
printtty(colorize('> ', PROMPT_COLOR) + "; Type HELP to get the HELP")
printtty(colorize('> ', PROMPT_COLOR) +
"; Completion is activated using the tab (if supported by the terminal)")
for i in files:
load_relation(i)
readline.set_completer(completer.complete)
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode emacs')
readline.set_completer_delims(" ")
while True:
try:
line = input(colorize('> ' if TTY else '', PROMPT_COLOR))
if isinstance(line, str) and len(line) > 0:
exec_line(line)
except KeyboardInterrupt:
if TTY:
print ('^C\n')
continue
else:
break
except EOFError:
printtty()
sys.exit(0)
if __name__ == "__main__":
main()
relational/relational_readline/__pycache__/ 0000755 0001750 0001750 00000000000 12757112451 020454 5 ustar salvo salvo relational/Makefile 0000644 0001750 0001750 00000004313 12757112451 013710 0 ustar salvo salvo gui: pyqt
pyqt:
pyuic5 relational_gui/survey.ui > relational_gui/survey.py
pyuic5 relational_gui/maingui.ui > relational_gui/maingui.py
pyuic5 relational_gui/rel_edit.ui > relational_gui/rel_edit.py
pyrcc5 relational_gui/resources.qrc > relational_gui/resources.py
sed -i 's/QtWidgets.QPlainTextEdit/editor.Editor/g' relational_gui/maingui.py
echo 'from . import editor' >> relational_gui/maingui.py
dist: clean
rm -rf /tmp/relational/
rm -rf /tmp/relational-*
mkdir /tmp/relational/
cp -R * /tmp/relational/
rm -rf /tmp/relational/windows
rm -rf /tmp/relational/debian/
#mv /tmp/relational /tmp/relational-`./relational_gui.py -v | grep Relational | cut -d" " -f2`
#(cd /tmp; tar -zcf relational.tar.gz relational-*/)
(cd /tmp; tar -zcf relational.tar.gz relational/)
mv /tmp/relational.tar.gz ./relational_`./relational_gui.py -v | grep Relational | cut -d" " -f2`.orig.tar.gz
release: dist
gpg --sign --armor --detach-sign ./relational_`./relational_gui.py -v | grep Relational | cut -d" " -f2`.orig.tar.gz
clean:
rm -rf `find -name "*~"`
rm -rf `find -name "*pyc"`
rm -rf `find -name "*pyo"`
rm -rf relational*.tar.gz
rm -rf relational*.tar.gz.asc
rm -rf data
rm -rf *tar.bz
rm -rf *.deb
rm -f relational_gui/survey.py
rm -f relational_gui/maingui.py
rm -f relational_gui/rel_edit.py
rm -f relational_gui/resources.py
install-relational-cli:
python3 setup/relational-cli.setup.py install --root=$${DESTDIR:-/};
rm -rf build;
install -D relational_gui.py $${DESTDIR:-/}/usr/bin/relational-cli
install -D relational-cli.1 $${DESTDIR:-/}/usr/share/man/man1/relational-cli.1
install-python3-relational:
python3 setup/python3-relational.setup.py install --root=$${DESTDIR:-/};
rm -rf build;
install-relational:
python3 setup/relational.setup.py install --root=$${DESTDIR:-/};
rm -rf build;
install -D relational_gui.py $${DESTDIR:-/}/usr/bin/relational
install -m0644 -D relational.desktop $${DESTDIR:-/}/usr/share/applications/relational.desktop
install -m0644 -D relational_gui/resources/relational.png $${DESTDIR:-/}/usr/share/pixmaps/relational.png
install -D relational.1 $${DESTDIR:-/}/usr/share/man/man1/relational.1
install: install-relational-cli install-python3-relational install-relational
relational/relational.1 0000644 0001750 0001750 00000001565 12757112451 014472 0 ustar salvo salvo .TH "Relational" "1"
.SH "NAME"
relational \(em Implementation of Relational algebra.
.SH "SYNOPSIS"
.PP
\fBrelational\fR [OPTIONS\fR\fP] [ FILE .\|.\|.]
.SH "DESCRIPTION"
.PP
This program provides a UI to execute relational algebra queries. It is meant to experiment with relational algebra queries.
.SH "OPTIONS"
.PP
A summary of options is included below.
.IP "\fB-v\fP
Show version information and exit.
.IP "\fB-h\fP
Shows help and exit.
.IP "\fB-q\fP
Uses the Qt5 GUI (default).
.IP "\fB-r\fP
Uses the readline UI.
.SH "AUTHOR"
.PP
This manual page was written by Salvo 'LtWorf' Tomaselli for
the \fBDebian GNU/Linux\fP system (but may be used by others). Permission is
granted to copy, distribute and/or modify this document under
the terms of the GNU General Public License
version 3 or any later version published by the Free Software Foundation.
relational/relational/ 0000755 0001750 0001750 00000000000 12757112451 014401 5 ustar salvo salvo relational/relational/optimizer.py 0000644 0001750 0001750 00000010735 12757112451 017003 0 ustar salvo salvo # Relational
# Copyright (C) 2008-2016 Salvo "LtWorf" Tomaselli
#
# Relational is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
#
# This module optimizes relational expressions into ones that require less time to be executed.
#
# expression: In all the functions expression can be either an UTF-8 encoded string, containing a valid
# relational query, or it can be a parse tree for a relational expression (ie: class parser.node).
# The functions will always return a string with the optimized query, but if a parse tree was provided,
# the parse tree itself will be modified accordingly.
from relational import optimizations
from relational import parser
from relational import querysplit
from relational.maintenance import UserInterface
# Stuff that was here before, keeping it for compatibility
RELATION = parser.RELATION
UNARY = parser.UNARY
BINARY = parser.BINARY
op_functions = parser.op_functions
node = parser.node
tokenize = parser.tokenize
tree = parser.tree
# End of the stuff
def optimize_program(code, rels):
'''
Optimize an entire program, composed by multiple expressions
and assignments.
'''
lines = code.split('\n')
context = {}
for line in lines:
line = line.strip()
if line.startswith(';') or not line:
continue
res, query = UserInterface.split_query(line)
last_res = res
parsed = parser.tree(query)
optimizations.replace_leaves(parsed, context)
context[res] = parsed
node = optimize_all(context[last_res], rels, tostr=False)
return querysplit.split(node, rels)
def optimize_all(expression, rels, specific=True, general=True, debug=None,tostr=True):
'''This function performs all the available optimizations.
expression : see documentation of this module
rels: dic with relation name as key, and relation istance as value
specific: True if it has to perform specific optimizations
general: True if it has to perform general optimizations
debug: if a list is provided here, after the end of the function, it
will contain the query repeated many times to show the performed
steps.
Return value: this will return an optimized version of the expression'''
if isinstance(expression, str):
n = tree(expression) # Gets the tree
elif isinstance(expression, node):
n = expression
else:
raise (TypeError("expression must be a string or a node"))
if isinstance(debug, list):
dbg = True
else:
dbg = False
total = 1
while total != 0:
total = 0
if specific:
for i in optimizations.specific_optimizations:
res = i(n, rels) # Performs the optimization
if res != 0 and dbg:
debug.append(str(n))
total += res
if general:
for i in optimizations.general_optimizations:
res = i(n) # Performs the optimization
if res != 0 and dbg:
debug.append(str(n))
total += res
if tostr:
return str(n)
else:
return n
def specific_optimize(expression, rels):
'''This function performs specific optimizations. Means that it will need to
know the fields used by the relations.
expression : see documentation of this module
rels: dic with relation name as key, and relation istance as value
Return value: this will return an optimized version of the expression'''
return optimize_all(expression, rels, specific=True, general=False)
def general_optimize(expression):
'''This function performs general optimizations. Means that it will not need to
know the fields used by the relations
expression : see documentation of this module
Return value: this will return an optimized version of the expression'''
return optimize_all(expression, None, specific=False, general=True)
relational/relational/maintenance.py 0000644 0001750 0001750 00000014177 12757112451 017247 0 ustar salvo salvo # Relational
# Copyright (C) 2008-2016 Salvo "LtWorf" Tomaselli
#
# Relation is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
#
# Stuff non-related to relational algebra, but used for maintenance.
import http.client
import urllib.parse
import os.path
import pickle
import base64
from relational.relation import relation
from relational import parser
from relational.rtypes import is_valid_relation_name
def send_survey(data):
'''Sends the survey. Data must be a dictionary.
returns the http response'''
post = ''
for i in data.keys():
post += '%s: %s\n' % (i, data[i])
# sends the string
params = urllib.parse.urlencode({'survey': post})
headers = {"Content-type":
"application/x-www-form-urlencoded", "Accept": "text/plain"}
connection = http.client.HTTPConnection('feedback-ltworf.appspot.com')
try:
connection.request("POST", "/feedback/relational", params, headers)
return connection.getresponse().status
except:
return 0
def check_latest_version():
'''Returns the latest version available.
Heavely dependent on server and server configurations
not granted to work forever.'''
connection = http.client.HTTPConnection('feedback-ltworf.appspot.com')
try:
connection.request("GET", "/version/relational")
r = connection.getresponse()
except:
return None
# html
s = r.read()
if len(s) == 0:
return None
return s.decode().strip()
class UserInterface (object):
'''It is used to provide services to the user interfaces, in order to
reduce the amount of duplicated code present in different user interfaces.
'''
def __init__(self):
self.session_reset()
def load(self, filename, name):
'''Loads a relation from file, and gives it a name to
be used in subsequent queries.'''
rel = relation(filename)
self.set_relation(name, rel)
def unload(self, name):
'''Unloads an existing relation.'''
del self.relations[name]
def store(self, filename, name):
'''Stores a relation to file.'''
pass
def session_dump(self, filename=None):
'''
Dumps the session.
If a filename is specified, the session is dumped
inside the file, and None is returned.
If no filename is specified, the session is returned
as bytes.
'''
if filename:
with open(filename, 'w') as f:
pickle.dump(self.relations, f)
return None
return base64.b64encode(pickle.dumps(self.relations)).decode()
def session_restore(self, session=None, filename=None):
'''
Restores a session.
Either from bytes or from a file
'''
if session:
try:
self.relations = pickle.loads(base64.b64decode(session))
except:
pass
elif filename:
with open(filename) as f:
self.relations = pickle.load(f)
def session_reset(self):
'''
Resets the session to a clean one
'''
self.relations = {}
def get_relation(self, name):
'''Returns the relation corresponding to name.'''
return self.relations[name]
def set_relation(self, name, rel):
'''Sets the relation corresponding to name.'''
if not is_valid_relation_name(name):
raise Exception('Invalid name for destination relation')
self.relations[name] = rel
def suggest_name(self, filename):
'''
Returns a possible name for a relation, given
a filename.
If it is impossible to extract a possible name,
returns None
'''
name = os.path.basename(filename).lower()
if len(name) == 0:
return None
if (name.endswith(".csv")): # removes the extension
name = name[:-4]
if not is_valid_relation_name(name):
return None
return name
def execute(self, query, relname='last_'):
'''Executes a query, returns the result and if
relname is not None, adds the result to the
dictionary, with the name given in relname.'''
if not is_valid_relation_name(relname):
raise Exception('Invalid name for destination relation')
expr = parser.parse(query)
result = expr(self.relations)
self.relations[relname] = result
return result
@staticmethod
def split_query(query, default_name='last_'):
'''
Accepts a query which might have an initial value
assignment
a = query
Returns a tuple with
result_name, query
'''
sq = query.split('=', 1)
if len(sq) == 2 and is_valid_relation_name(sq[0].strip()):
default_name = sq[0].strip()
query = sq[1].strip()
return default_name, query
def multi_execute(self, query):
'''Executes multiple queries, separated by \n
They can have a syntax of
[varname =] query
to assign the result to a new relation
'''
r = relation()
queries = query.split('\n')
for query in queries:
if query.strip() == '':
continue
relname, query = self.split_query(query)
try:
r = self.execute(query, relname)
except Exception as e:
raise Exception('Error in query: %s\n%s' % (
query,
str(e)
))
return r
relational/relational/rtypes.py 0000644 0001750 0001750 00000011530 12757112451 016301 0 ustar salvo salvo # Relational
# Copyright (C) 2008-2016 Salvo "LtWorf" Tomaselli
#
# Relation is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
#
# Custom types for relational algebra.
# Purpose of this module is having the isFloat function and
# implementing dates to use in selection.
import datetime
import re
RELATION_NAME_REGEXP = re.compile(r'^[_a-z][_a-z0-9]*$', re.IGNORECASE)
class Rstring (str):
'''String subclass with some custom methods'''
int_regexp = re.compile(r'^[\+\-]{0,1}[0-9]+$')
float_regexp = re.compile(r'^[\+\-]{0,1}[0-9]+(\.([0-9])+)?$')
date_regexp = re.compile(
r'^([0-9]{1,4})(\\|-|/)([0-9]{1,2})(\\|-|/)([0-9]{1,2})$'
)
def autocast(self):
'''
Returns the automatic cast for this
value.
'''
try:
return self._autocast
except:
pass
self._autocast = self
if len(self) > 0:
if self.isInt():
self._autocast = int(self)
elif self.isFloat():
self._autocast = float(self)
elif self.isDate():
self._autocast = rdate(self)
return self._autocast
def isInt(self):
'''Returns true if the string represents an int number
it only considers as int numbers the strings matching
the following regexp:
r'^[\+\-]{0,1}[0-9]+$'
'''
return Rstring.int_regexp.match(self) is not None
def isFloat(self):
'''Returns true if the string represents a float number
it only considers as float numbers, the strings matching
the following regexp:
r'^[\+\-]{0,1}[0-9]+(\.([0-9])+)?$'
'''
return Rstring.float_regexp.match(self) is not None
def isDate(self):
'''Returns true if the string represents a date,
in the format YYYY-MM-DD. as separators '-' , '\', '/' are allowed.
As side-effect, the date object will be stored for future usage, so
no more parsings are needed
'''
try:
return self._isdate
except:
pass
r = Rstring.date_regexp.match(self)
if r is None:
self._isdate = False
self._date = None
return False
try: # Any of the following operations can generate an exception, if it happens, we aren't dealing with a date
year = int(r.group(1))
month = int(r.group(3))
day = int(r.group(5))
d = datetime.date(year, month, day)
self._isdate = True
self._date = d
return True
except:
self._isdate = False
self._date = None
return False
def getDate(self):
'''Returns the datetime.date object or None'''
try:
return self._date
except:
self.isDate()
return self._date
class Rdate (object):
'''Represents a date'''
def __init__(self, date):
'''date: A string representing a date'''
if not isinstance(date, rstring):
date = rstring(date)
self.intdate = date.getDate()
self.day = self.intdate.day
self.month = self.intdate.month
self.weekday = self.intdate.weekday()
self.year = self.intdate.year
def __hash__(self):
return self.intdate.__hash__()
def __str__(self):
return self.intdate.__str__()
def __add__(self, days):
res = self.intdate + datetime.timedelta(days)
return rdate(res.__str__())
def __eq__(self, other):
return self.intdate == other.intdate
def __ge__(self, other):
return self.intdate >= other.intdate
def __gt__(self, other):
return self.intdate > other.intdate
def __le__(self, other):
return self.intdate <= other.intdate
def __lt__(self, other):
return self.intdate < other.intdate
def __ne__(self, other):
return self.intdate != other.intdate
def __sub__(self, other):
return (self.intdate - other.intdate).days
def is_valid_relation_name(name):
'''Checks if a name is valid for a relation.
Returns boolean'''
return re.match(RELATION_NAME_REGEXP, name) != None
# Backwards compatibility
rdate = Rdate
rstring = Rstring
relational/relational/optimizations.py 0000644 0001750 0001750 00000055315 12757112451 017675 0 ustar salvo salvo # Relational
# Copyright (C) 2009-2016 Salvo "LtWorf" Tomaselli
#
# Relational is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
#
# This module contains functions to perform various optimizations on the expression trees.
# The list general_optimizations contains pointers to general functions, so they can be called
# within a cycle.
#
# It is possible to add new general optimizations by adding the function in the list
# general_optimizations present in this module. And the optimization will be executed with the
# other ones when optimizing.
#
# A function will have one parameter, which is the root node of the tree describing the expression.
# The class used is defined in optimizer module.
# A function will have to return the number of changes performed on the tree.
from io import StringIO
from tokenize import generate_tokens
from relational import parser
sel_op = (
'//=', '**=', 'and', 'not', 'in', '//', '**', '<<', '>>', '==', '!=', '>=', '<=', '+=', '-=',
'*=', '/=', '%=', 'or', '+', '-', '*', '/', '&', '|', '^', '~', '<', '>', '%', '=', '(', ')', ',', '[', ']')
PRODUCT = parser.PRODUCT
DIFFERENCE = parser.DIFFERENCE
UNION = parser.UNION
INTERSECTION = parser.INTERSECTION
DIVISION = parser.DIVISION
JOIN = parser.JOIN
JOIN_LEFT = parser.JOIN_LEFT
JOIN_RIGHT = parser.JOIN_RIGHT
JOIN_FULL = parser.JOIN_FULL
PROJECTION = parser.PROJECTION
SELECTION = parser.SELECTION
RENAME = parser.RENAME
ARROW = parser.ARROW
def find_duplicates(node, dups=None):
'''
Finds repeated subtrees in a parse
tree.
'''
if dups is None:
dups = {}
dups[str(node)] = node
def replace_leaves(node, context):
'''
Node is a parsed tree
context is a dictionary containing
parsed trees as values.
If a name appearing in node appears
also in context, the parse tree is
modified to replace the node with the
subtree found in context.
'''
if node.kind == parser.UNARY:
replace_leaves(node.child, context)
elif node.kind == parser.BINARY:
replace_leaves(node.left, context)
replace_leaves(node.right, context)
elif node.name in context:
replace_node(node, context[node.name])
def replace_node(replace, replacement):
'''This function replaces "replace" node with the node "with",
the father of the node will now point to the with node'''
replace.name = replacement.name
replace.kind = replacement.kind
if replace.kind == parser.UNARY:
replace.child = replacement.child
replace.prop = replacement.prop
elif replace.kind == parser.BINARY:
replace.right = replacement.right
replace.left = replacement.left
def recoursive_scan(function, node, rels=None):
'''Does a recoursive optimization on the tree.
This function will recoursively execute the function given
as "function" parameter starting from node to all the tree.
if rels is provided it will be passed as argument to the function.
Otherwise the function will be called just on the node.
Result value: function is supposed to return the amount of changes
it has performed on the tree.
The various result will be added up and this final value will be the
returned value.'''
changes = 0
# recoursive scan
if node.kind == parser.UNARY:
if rels != None:
changes += function(node.child, rels)
else:
changes += function(node.child)
elif node.kind == parser.BINARY:
if rels != None:
changes += function(node.right, rels)
changes += function(node.left, rels)
else:
changes += function(node.right)
changes += function(node.left)
return changes
def duplicated_select(n):
'''This function locates and deletes things like
σ a ( σ a(C)) and the ones like σ a ( σ b(C))
replacing the 1st one with a single select and
the 2nd one with a single select with both conditions
in and
'''
changes = 0
if n.name == SELECTION and n.child.name == SELECTION:
if n.prop != n.child.prop: # Nested but different, joining them
n.prop = n.prop + " and " + n.child.prop
# This adds parenthesis if they are needed
if n.child.prop.startswith('(') or n.prop.startswith('('):
n.prop = '(%s)' % n.prop
n.child = n.child.child
changes = 1
changes += duplicated_select(n)
return changes + recoursive_scan(duplicated_select, n)
def futile_union_intersection_subtraction(n):
'''This function locates things like r ᑌ r, and replaces them with r.
R ᑌ R --> R
R ᑎ R --> R
R - R --> σ False (R)
σ k (R) - R --> σ False (R)
R - σ k (R) --> σ not k (R)
σ k (R) ᑌ R --> R
σ k (R) ᑎ R --> σ k (R)
'''
changes = 0
# Union and intersection of the same thing
if n.name in (UNION, INTERSECTION, JOIN, JOIN_LEFT, JOIN_RIGHT, JOIN_FULL) and n.left == n.right:
changes = 1
replace_node(n, n.left)
# selection and union of the same thing
elif (n.name == UNION):
if n.left.name == SELECTION and n.left.child == n.right:
changes = 1
replace_node(n, n.right)
elif n.right.name == SELECTION and n.right.child == n.left:
changes = 1
replace_node(n, n.left)
# selection and intersection of the same thing
elif n.name == INTERSECTION:
if n.left.name == SELECTION and n.left.child == n.right:
changes = 1
replace_node(n, n.left)
elif n.right.name == SELECTION and n.right.child == n.left:
changes = 1
replace_node(n, n.right)
# Subtraction and selection of the same thing
elif n.name == DIFFERENCE and \
n.right.name == SELECTION and \
n.right.child == n.left:
n.name = n.right.name
n.kind = n.right.kind
n.child = n.right.child
n.prop = '(not (%s))' % n.right.prop
n.left = n.right = None
# Subtraction of the same thing or with selection on the left child
elif n.name == DIFFERENCE and (n.left == n.right or (n.left.name == SELECTION and n.left.child == n.right)):
changes = 1
n.kind = parser.UNARY
n.name = SELECTION
n.prop = 'False'
n.child = n.left.get_left_leaf()
# n.left=n.right=None
return changes + recoursive_scan(futile_union_intersection_subtraction, n)
def down_to_unions_subtractions_intersections(n):
'''This funcion locates things like σ i==2 (c ᑌ d), where the union
can be a subtraction and an intersection and replaces them with
σ i==2 (c) ᑌ σ i==2(d).
'''
changes = 0
_o = (UNION, DIFFERENCE, INTERSECTION)
if n.name == SELECTION and n.child.name in _o:
left = parser.node()
left.prop = n.prop
left.name = n.name
left.child = n.child.left
left.kind = parser.UNARY
right = parser.node()
right.prop = n.prop
right.name = n.name
right.child = n.child.right
right.kind = parser.UNARY
n.name = n.child.name
n.left = left
n.right = right
n.child = None
n.prop = None
n.kind = parser.BINARY
changes += 1
return changes + recoursive_scan(down_to_unions_subtractions_intersections, n)
def duplicated_projection(n):
'''This function locates thing like π i ( π j (R)) and replaces
them with π i (R)'''
changes = 0
if n.name == PROJECTION and n.child.name == PROJECTION:
n.child = n.child.child
changes += 1
return changes + recoursive_scan(duplicated_projection, n)
def selection_inside_projection(n):
'''This function locates things like σ j (π k(R)) and
converts them into π k(σ j (R))'''
changes = 0
if n.name == SELECTION and n.child.name == PROJECTION:
changes = 1
temp = n.prop
n.prop = n.child.prop
n.child.prop = temp
n.name = PROJECTION
n.child.name = SELECTION
return changes + recoursive_scan(selection_inside_projection, n)
def swap_union_renames(n):
'''This function locates things like
ρ a➡b(R) ᑌ ρ a➡b(Q)
and replaces them with
ρ a➡b(R ᑌ Q).
Does the same with subtraction and intersection'''
changes = 0
if n.name in (DIFFERENCE, UNION, INTERSECTION) and n.left.name == n.right.name and n.left.name == RENAME:
l_vars = {}
for i in n.left.prop.split(','):
q = i.split(ARROW)
l_vars[q[0].strip()] = q[1].strip()
r_vars = {}
for i in n.right.prop.split(','):
q = i.split(ARROW)
r_vars[q[0].strip()] = q[1].strip()
if r_vars == l_vars:
changes = 1
# Copying self, but child will be child of renames
q = parser.node()
q.name = n.name
q.kind = parser.BINARY
q.left = n.left.child
q.right = n.right.child
n.name = RENAME
n.kind = parser.UNARY
n.child = q
n.prop = n.left.prop
n.left = n.right = None
return changes + recoursive_scan(swap_union_renames, n)
def futile_renames(n):
'''This function purges renames like id->id'''
changes = 0
if n.name == RENAME:
# Located two nested renames.
changes = 1
# Creating a dictionary with the attributes
_vars = {}
for i in n.prop.split(','):
q = i.split(ARROW)
_vars[q[0].strip()] = q[1].strip()
# Scans dictionary to locate things like "a->b,b->c" and replace them
# with "a->c"
for key in list(_vars.keys()):
value = _vars.get(key)
if key == value:
_vars.pop(value) # Removes the unused one
if len(_vars) == 0: # Nothing to rename, removing the rename op
replace_node(n, n.child)
else:
n.prop = ','.join('%s%s%s' % (i[0], ARROW, i[1]) for i in _vars.items())
return changes + recoursive_scan(futile_renames, n)
def subsequent_renames(n):
'''This function removes redoundant subsequent renames joining them into one'''
'''Purges renames like id->id Since it's needed to be performed BEFORE this one
so it is not in the list with the other optimizations'''
futile_renames(n)
changes = 0
if n.name == RENAME and n.child.name == RENAME:
# Located two nested renames.
changes = 1
# Joining the attribute into one
n.prop += ',' + n.child.prop
n.child = n.child.child
# Creating a dictionary with the attributes
_vars = {}
for i in n.prop.split(','):
q = i.split(ARROW)
_vars[q[0].strip()] = q[1].strip()
# Scans dictionary to locate things like "a->b,b->c" and replace them
# with "a->c"
for key in list(_vars.keys()):
value = _vars.get(key)
if value in _vars.keys():
if _vars[value] != key:
# Double rename on attribute
_vars[key] = _vars[_vars[key]] # Sets value
_vars.pop(value) # Removes the unused one
else: # Cycle rename a->b,b->a
_vars.pop(value) # Removes the unused one
_vars.pop(key) # Removes the unused one
if len(_vars) == 0: # Nothing to rename, removing the rename op
replace_node(n, n.child)
else:
n.prop = ','.join('%s%s%s' % (i[0], ARROW, i[1]) for i in _vars.items())
return changes + recoursive_scan(subsequent_renames, n)
class level_string(str):
level = 0
def tokenize_select(expression):
'''This function returns the list of tokens present in a
selection. The expression can contain parenthesis.
It will use a subclass of str with the attribute level, which
will specify the nesting level of the token into parenthesis.'''
g = generate_tokens(StringIO(str(expression)).readline)
l = list(token[1] for token in g)
l.remove('')
# Changes the 'a','.','method' token group into a single 'a.method' token
try:
while True:
dot = l.index('.')
l[dot] = '%s.%s' % (l[dot - 1], l[dot + 1])
l.pop(dot + 1)
l.pop(dot - 1)
except:
pass
level = 0
for i in range(len(l)):
l[i] = level_string(l[i])
l[i].level = level
if l[i] == '(':
level += 1
elif l[i] == ')':
level -= 1
return l
def swap_rename_projection(n):
'''This function locates things like π k(ρ j(R))
and replaces them with ρ j(π k(R)).
This will let rename work on a hopefully smaller set
and more important, will hopefully allow further optimizations.
Will also eliminate fields in the rename that are cutted in the projection.
'''
changes = 0
if n.name == PROJECTION and n.child.name == RENAME:
changes = 1
# π index,name(ρ id➡index(R))
_vars = {}
for i in n.child.prop.split(','):
q = i.split(ARROW)
_vars[q[1].strip()] = q[0].strip()
_pr = n.prop.split(',')
for i in range(len(_pr)):
try:
_pr[i] = _vars[_pr[i].strip()]
except:
pass
_pr_reborn = n.prop.split(',')
for i in list(_vars.keys()):
if i not in _pr_reborn:
_vars.pop(i)
n.name = n.child.name
n.prop = ','.join('%s%s%s' % (i[1], ARROW, i[0]) for i in _vars.items())
n.child.name = PROJECTION
n.child.prop = ''
for i in _pr:
n.child.prop += i + ','
n.child.prop = n.child.prop[:-1]
return changes + recoursive_scan(swap_rename_projection, n)
def swap_rename_select(n):
'''This function locates things like σ k(ρ j(R)) and replaces
them with ρ j(σ k(R)). Renaming the attributes used in the
selection, so the operation is still valid.'''
changes = 0
if n.name == SELECTION and n.child.name == RENAME:
changes = 1
# Dictionary containing attributes of rename
_vars = {}
for i in n.child.prop.split(','):
q = i.split(ARROW)
_vars[q[1].strip()] = q[0].strip()
# tokenizes expression in select
_tokens = tokenize_select(n.prop)
# Renaming stuff
for i in range(len(_tokens)):
splitted = _tokens[i].split('.', 1)
if splitted[0] in _vars:
if len(splitted) == 1:
_tokens[i] = _vars[_tokens[i].split('.')[0]]
else:
_tokens[i] = _vars[
_tokens[i].split('.')[0]] + '.' + splitted[1]
# Swapping operators
n.name = RENAME
n.child.name = SELECTION
n.prop = n.child.prop
n.child.prop = ' '.join(_tokens)
return changes + recoursive_scan(swap_rename_select, n)
def select_union_intersect_subtract(n):
'''This function locates things like σ i(a) ᑌ σ q(a)
and replaces them with σ (i OR q) (a)
Removing a O(n²) operation like the union'''
changes = 0
if n.name in {UNION, INTERSECTION, DIFFERENCE} and \
n.left.name == SELECTION and \
n.right.name == SELECTION and \
n.left.child == n.right.child:
changes = 1
d = {UNION: 'or', INTERSECTION: 'and', DIFFERENCE: 'and not'}
op = d[n.name]
newnode = parser.node()
if n.left.prop.startswith('(') or n.right.prop.startswith('('):
t_str = '('
if n.left.prop.startswith('('):
t_str += '(%s)'
else:
t_str += '%s'
t_str += ' %s '
if n.right.prop.startswith('('):
t_str += '(%s)'
else:
t_str += '%s'
t_str += ')'
newnode.prop = t_str % (n.left.prop, op, n.right.prop)
else:
newnode.prop = '%s %s %s' % (n.left.prop, op, n.right.prop)
newnode.name = SELECTION
newnode.child = n.left.child
newnode.kind = parser.UNARY
replace_node(n, newnode)
return changes + recoursive_scan(select_union_intersect_subtract, n)
def union_and_product(n):
'''
A * B ∪ A * C = A * (B ∪ C)
Same thing with inner join
'''
changes = 0
if n.name == UNION and n.left.name in {PRODUCT, JOIN} and n.left.name == n.right.name:
newnode = parser.node()
newnode.kind = parser.BINARY
newnode.name = n.left.name
newchild = parser.node()
newchild.kind = parser.BINARY
newchild.name = UNION
if n.left.left == n.right.left or n.left.left == n.right.right:
newnode.left = n.left.left
newnode.right = newchild
newchild.left = n.left.right
newchild.right = n.right.left if n.left.left == n.right.right else n.right.right
replace_node(n, newnode)
changes = 1
elif n.left.right == n.right.left or n.left.left == n.right.right:
newnode.left = n.left.right
newnode.right = newchild
newchild.left = n.left.left
newchild.right = n.right.left if n.right.left == n.right.right else n.right.right
replace_node(n, newnode)
changes = 1
return changes + recoursive_scan(union_and_product, n)
def projection_and_union(n, rels):
'''
Turns
π a,b,c(A) ∪ π a,b,c(B)
into
π a,b,c(A ∪ B)
if A and B are union compatible
'''
changes = 0
if n.name == UNION and \
n.left.name == PROJECTION and \
n.right.name == PROJECTION and \
set(n.left.child.result_format(rels)) == set(n.right.child.result_format(rels)):
newchild = parser.Node()
newchild.kind = parser.BINARY
newchild.name = UNION
newchild.left = n.left.child
newchild.right = n.right.child
newnode = parser.Node()
newnode.child = newchild
newnode.kind = parser.UNARY
newnode.name = PROJECTION
newnode.prop = n.right.prop
replace_node(n, newnode)
changes = 1
return changes + recoursive_scan(projection_and_union, n, rels)
def selection_and_product(n, rels):
'''This function locates things like σ k (R*Q) and converts them into
σ l (σ j (R) * σ i (Q)). Where j contains only attributes belonging to R,
i contains attributes belonging to Q and l contains attributes belonging to both'''
changes = 0
if n.name == SELECTION and n.child.name in (PRODUCT, JOIN):
l_attr = n.child.left.result_format(rels)
r_attr = n.child.right.result_format(rels)
tokens = tokenize_select(n.prop)
groups = []
temp = []
for i in tokens:
if i == 'and' and i.level == 0:
groups.append(temp)
temp = []
else:
temp.append(i)
if len(temp) != 0:
groups.append(temp)
temp = []
left = []
right = []
both = []
for i in groups:
l_fields = False # has fields in left?
r_fields = False # has fields in left?
for j in set(i).difference(sel_op):
j = j.split('.')[0]
if j in l_attr: # Field in left
l_fields = True
if j in r_attr: # Field in right
r_fields = True
if l_fields and r_fields: # Fields in both
both.append(i)
elif l_fields:
left.append(i)
elif r_fields:
right.append(i)
else: # Unknown.. adding in both
both.append(i)
# Preparing left selection
if len(left) > 0:
changes = 1
l_node = parser.node()
l_node.name = SELECTION
l_node.kind = parser.UNARY
l_node.child = n.child.left
l_node.prop = ''
n.child.left = l_node
while len(left) > 0:
c = left.pop(0)
for i in c:
l_node.prop += i + ' '
if len(left) > 0:
l_node.prop += ' and '
if '(' in l_node.prop:
l_node.prop = '(%s)' % l_node.prop
# Preparing right selection
if len(right) > 0:
changes = 1
r_node = parser.node()
r_node.name = SELECTION
r_node.prop = ''
r_node.kind = parser.UNARY
r_node.child = n.child.right
n.child.right = r_node
while len(right) > 0:
c = right.pop(0)
r_node.prop += ' '.join(c)
if len(right) > 0:
r_node.prop += ' and '
if '(' in r_node.prop:
r_node.prop = '(%s)' % r_node.prop
# Changing main selection
n.prop = ''
if len(both) != 0:
while len(both) > 0:
c = both.pop(0)
n.prop += ' '.join(c)
if len(both) > 0:
n.prop += ' and '
if '(' in n.prop:
n.prop = '(%s)' % n.prop
else: # No need for general select
replace_node(n, n.child)
return changes + recoursive_scan(selection_and_product, n, rels)
def useless_projection(n, rels):
'''
Removes projections that are over all the fields
'''
changes = 0
if n.name == PROJECTION and \
set(n.child.result_format(rels)) == set(i.strip() for i in n.prop.split(',')):
changes = 1
replace_node(n, n.child)
return changes + recoursive_scan(useless_projection, n, rels)
general_optimizations = [
duplicated_select,
down_to_unions_subtractions_intersections,
duplicated_projection,
selection_inside_projection,
subsequent_renames,
swap_rename_select,
futile_union_intersection_subtraction,
swap_union_renames,
swap_rename_projection,
select_union_intersect_subtract,
union_and_product,
]
specific_optimizations = [
selection_and_product,
projection_and_union,
useless_projection,
]
if __name__ == "__main__":
print (tokenize_select("skill == 'C' and id % 2 == 0"))
relational/relational/__init__.py 0000644 0001750 0001750 00000000140 12757112451 016505 0 ustar salvo salvo __all__ = (
"relation",
"parser",
"optimizer",
"optimizations",
"rtypes",
)
relational/relational/parser.py 0000644 0001750 0001750 00000034506 12757112451 016257 0 ustar salvo salvo # Relational
# Copyright (C) 2008-2016 Salvo "LtWorf" Tomaselli
#
# Relational is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
#
#
#
# This module implements a parser for relational algebra, and can be used
# to convert expressions into python expressions and to get the parse-tree
# of the expression.
#
# Language definition here:
# http://ltworf.github.io/relational/grammar.html
from relational import rtypes
RELATION = 0
UNARY = 1
BINARY = 2
PRODUCT = '*'
DIFFERENCE = '-'
UNION = '∪'
INTERSECTION = '∩'
DIVISION = '÷'
JOIN = '⋈'
JOIN_LEFT = '⧑'
JOIN_RIGHT = '⧒'
JOIN_FULL = '⧓'
PROJECTION = 'π'
SELECTION = 'σ'
RENAME = 'ρ'
ARROW = '➡'
b_operators = (PRODUCT, DIFFERENCE, UNION, INTERSECTION, DIVISION,
JOIN, JOIN_LEFT, JOIN_RIGHT, JOIN_FULL) # List of binary operators
u_operators = (PROJECTION, SELECTION, RENAME) # List of unary operators
# Associates operator with python method
op_functions = {
PRODUCT: 'product', DIFFERENCE: 'difference', UNION: 'union', INTERSECTION: 'intersection', DIVISION: 'division', JOIN: 'join',
JOIN_LEFT: 'outer_left', JOIN_RIGHT: 'outer_right', JOIN_FULL: 'outer', PROJECTION: 'projection', SELECTION: 'selection', RENAME: 'rename'}
class TokenizerException (Exception):
pass
class ParserException (Exception):
pass
class CallableString(str):
'''
This is a string. However it is also callable.
For example:
CallableString('1+1')()
returns 2
It is used to contain Python expressions and print
or execute them.
'''
def __call__(self, context=None):
'''
context is a dictionary where to
each name is associated the relative relation
'''
return eval(self, context)
class Node (object):
'''This class is a node of a relational expression. Leaves are relations
and internal nodes are operations.
The 'kind' property indicates whether the node is a binary operator, unary
operator or relation.
Since relations are leaves, a relation node will have no attribute for
children.
If the node is a binary operator, it will have left and right properties.
If the node is a unary operator, it will have a child, pointing to the
child node and a property containing the string with the props of the
operation.
This class is used to convert an expression into python code.'''
kind = None
__hash__ = None
def __init__(self, expression=None):
'''Generates the tree from the tokenized expression
If no expression is specified then it will create an empty node'''
if expression == None or len(expression) == 0:
return
# If the list contains only a list, it will consider the lower level list.
# This will allow things like ((((((a))))) to work
while len(expression) == 1 and isinstance(expression[0], list):
expression = expression[0]
# The list contains only 1 string. Means it is the name of a relation
if len(expression) == 1:
self.kind = RELATION
self.name = expression[0]
if not rtypes.is_valid_relation_name(self.name):
raise ParserException(
u"'%s' is not a valid relation name" % self.name)
return
# Expression from right to left, searching for binary operators
# this means that binary operators have lesser priority than
# unary operators.
# It finds the operator with lesser priority, uses it as root of this
# (sub)tree using everything on its left as left parameter (so building
# a left subtree with the part of the list located on left) and doing
# the same on right.
# Since it searches for strings, and expressions into parenthesis are
# within sub-lists, they won't be found here, ensuring that they will
# have highest priority.
for i in range(len(expression) - 1, -1, -1):
if expression[i] in b_operators: # Binary operator
self.kind = BINARY
self.name = expression[i]
if len(expression[:i]) == 0:
raise ParserException(
u"Expected left operand for '%s'" % self.name)
if len(expression[i + 1:]) == 0:
raise ParserException(
u"Expected right operand for '%s'" % self.name)
self.left = node(expression[:i])
self.right = node(expression[i + 1:])
return
'''Searches for unary operators, parsing from right to left'''
for i in range(len(expression) - 1, -1, -1):
if expression[i] in u_operators: # Unary operator
self.kind = UNARY
self.name = expression[i]
if len(expression) <= i + 2:
raise ParserException(
u"Expected more tokens in '%s'" % self.name)
self.prop = expression[1 + i].strip()
self.child = node(expression[2 + i])
return
raise ParserException("Expected operator in '%s'" % expression)
def toCode(self):
'''This method converts the AST into a python code object'''
code = self._toPython()
return compile(code, '', 'eval')
def toPython(self):
'''This method converts the AST into a python code string, which
will require the relation module to be executed.
The return value is a CallableString, which means that it can be
directly called.'''
return CallableString(self._toPython())
def _toPython(self):
'''
Same as toPython but returns a regular string
'''
if self.name in b_operators:
return '%s.%s(%s)' % (self.left.toPython(), op_functions[self.name], self.right.toPython())
elif self.name in u_operators:
prop = self.prop
# Converting parameters
if self.name == PROJECTION:
prop = '\"%s\"' % prop.replace(' ', '').replace(',', '\",\"')
elif self.name == RENAME:
prop = '{\"%s\"}' % prop.replace(
',', '\",\"').replace(ARROW, '\":\"').replace(' ', '')
else: # Selection
prop = repr(prop)
return '%s.%s(%s)' % (self.child.toPython(), op_functions[self.name], prop)
return self.name
def printtree(self, level=0):
'''returns a representation of the tree using indentation'''
r = ''
for i in range(level):
r += ' '
r += self.name
if self.name in b_operators:
r += self.left.printtree(level + 1)
r += self.right.printtree(level + 1)
elif self.name in u_operators:
r += '\t%s\n' % self.prop
r += self.child.printtree(level + 1)
return '\n' + r
def get_left_leaf(self):
'''This function returns the leftmost leaf in the tree.'''
if self.kind == RELATION:
return self
elif self.kind == UNARY:
return self.child.get_left_leaf()
elif self.kind == BINARY:
return self.left.get_left_leaf()
def result_format(self, rels):
'''This function returns a list containing the fields that the resulting relation will have.
It requires a dictionary where keys are the names of the relations and the values are
the relation objects.'''
if rels == None:
return
if self.kind == RELATION:
return list(rels[self.name].header)
elif self.kind == BINARY and self.name in (DIFFERENCE, UNION, INTERSECTION):
return self.left.result_format(rels)
elif self.kind == BINARY and self.name == DIVISION:
return list(set(self.left.result_format(rels)) - set(self.right.result_format(rels)))
elif self.name == PROJECTION:
l = []
for i in self.prop.split(','):
l.append(i.strip())
return l
elif self.name == PRODUCT:
return self.left.result_format(rels) + self.right.result_format(rels)
elif self.name == SELECTION:
return self.child.result_format(rels)
elif self.name == RENAME:
_vars = {}
for i in self.prop.split(','):
q = i.split(ARROW)
_vars[q[0].strip()] = q[1].strip()
_fields = self.child.result_format(rels)
for i in range(len(_fields)):
if _fields[i] in _vars:
_fields[i] = _vars[_fields[i]]
return _fields
elif self.name in (JOIN, JOIN_LEFT, JOIN_RIGHT, JOIN_FULL):
return list(set(self.left.result_format(rels)).union(set(self.right.result_format(rels))))
def __eq__(self, other):
if not (isinstance(other, node) and self.name == other.name and self.kind == other.kind):
return False
if self.kind == UNARY:
if other.prop != self.prop:
return False
return self.child == other.child
if self.kind == BINARY:
return self.left == other.left and self.right == other.right
return True
def __str__(self):
if (self.kind == RELATION):
return self.name
elif (self.kind == UNARY):
return self.name + " " + self.prop + " (" + self.child.__str__() + ")"
elif (self.kind == BINARY):
le = self.left.__str__()
if self.right.kind != BINARY:
re = self.right.__str__()
else:
re = "(" + self.right.__str__() + ")"
return (le + self.name + re)
def _find_matching_parenthesis(expression, start=0, openpar=u'(', closepar=u')'):
'''This function returns the position of the matching
close parenthesis to the 1st open parenthesis found
starting from start (0 by default)'''
par_count = 0 # Count of parenthesis
string = False
escape = False
for i in range(start, len(expression)):
if expression[i] == '\'' and not escape:
string = not string
if expression[i] == '\\' and not escape:
escape = True
else:
escape = False
if string:
continue
if expression[i] == openpar:
par_count += 1
elif expression[i] == closepar:
par_count -= 1
if par_count == 0:
return i # Closing parenthesis of the parameter
def _find_token(haystack, needle):
'''
Like the string function find, but
ignores tokens that are within a string
literal.
'''
r = -1
string = False
escape = False
for i in range(len(haystack)):
if haystack[i] == '\'' and not escape:
string = not string
if haystack[i] == '\\' and not escape:
escape = True
else:
escape = False
if string:
continue
if haystack[i:].startswith(needle):
return i
return r
def tokenize(expression):
'''This function converts a relational expression into a list where
every token of the expression is an item of a list. Expressions into
parenthesis will be converted into sublists.'''
items = [] # List for the tokens
expression = expression.strip() # Removes initial and ending spaces
while len(expression) > 0:
if expression.startswith('('): # Parenthesis state
end = _find_matching_parenthesis(expression)
if end == None:
raise TokenizerException(
"Missing matching ')' in '%s'" % expression)
# Appends the tokenization of the content of the parenthesis
items.append(tokenize(expression[1:end]))
# Removes the entire parentesis and content from the expression
expression = expression[end + 1:].strip()
elif expression.startswith((SELECTION, RENAME, PROJECTION)): # Unary operators
items.append(expression[0:1])
# Adding operator in the top of the list
expression = expression[
1:].strip() # Removing operator from the expression
if expression.startswith('('): # Expression with parenthesis, so adding what's between open and close without tokenization
par = expression.find(
'(', _find_matching_parenthesis(expression))
else: # Expression without parenthesis, so adding what's between start and parenthesis as whole
par = _find_token(expression, '(')
items.append(expression[:par].strip())
# Inserting parameter of the operator
expression = expression[
par:].strip() # Removing parameter from the expression
else: # Relation (hopefully)
expression += ' ' # To avoid the special case of the ending
# Initial part is a relation, stop when the name of the relation is
# over
for r in range(1, len(expression)):
if rtypes.RELATION_NAME_REGEXP.match(expression[:r + 1]) is None:
break
items.append(expression[:r])
expression = expression[r:].strip()
return items
def tree(expression):
'''This function parses a relational algebra expression into a AST and returns
the root node using the Node class.'''
return node(tokenize(expression))
def parse(expr):
'''This function parses a relational algebra expression, and returns a
CallableString (a string that can be called) whith the corresponding
Python expression.
'''
return tree(expr).toPython()
if __name__ == "__main__":
while True:
e = input("Expression: ")
print (parse(e))
# Backwards compatibility
node = Node
relational/relational/querysplit.py 0000644 0001750 0001750 00000005315 12757112451 017200 0 ustar salvo salvo # Relational
# Copyright (C) 2016 Salvo "LtWorf" Tomaselli
#
# Relational is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
#
# This module splits a query into a program.
from relational import parser
class Program:
def __init__(self, rels):
self.queries = []
self.dictionary = {} # Key is the query, value is the relation
self.vgen = vargen(rels, 'optm_')
def __str__(self):
r = ''
for q in self.queries:
r += '%s = %s' % (q[0], q[1]) + '\n'
return r.rstrip()
def append_query(self, node):
strnode = str(node)
rel = self.dictionary.get(strnode)
if rel:
return rel
qname = next(self.vgen)
self.queries.append((qname, node))
n = parser.Node()
n.kind = parser.RELATION
n.name = qname
self.dictionary[strnode] = n
return n
def _separate(node, program):
if node.kind == parser.UNARY and node.child.kind != parser.RELATION:
_separate(node.child, program)
rel = program.append_query(node.child)
node.child = rel
elif node.kind == parser.BINARY:
if node.left.kind != parser.RELATION:
_separate(node.left, program)
rel = program.append_query(node.left)
node.left = rel
if node.right.kind != parser.RELATION:
_separate(node.right, program)
rel = program.append_query(node.right)
node.right = rel
program.append_query(node)
def vargen(avoid, prefix=''):
'''
Generates temp variables.
Avoid contains variable names to skip.
'''
count = 0
while True:
r = ''
c = count
while True:
r = chr((c % 26) + 97) + r
if c < 26:
break
c //= 26
r = prefix + r
if r not in avoid:
yield r
count += 1
def split(node, rels):
'''
Split a query into a program.
The idea is that if there are duplicated subdtrees they
get executed only once.
'''
p = Program(rels)
_separate(node, p)
return str(p)
relational/relational/__pycache__/ 0000755 0001750 0001750 00000000000 12757112451 016611 5 ustar salvo salvo relational/relational/relation.py 0000644 0001750 0001750 00000043376 12757112451 016605 0 ustar salvo salvo # Relational
# Copyright (C) 2008-2016 Salvo "LtWorf" Tomaselli
#
# Relational is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
#
# This module provides a classes to represent relations and to perform
# relational operations on them.
import csv
from itertools import chain, repeat
from collections import deque
from relational.rtypes import *
class Relation (object):
'''
This object defines a relation (as a group of consistent tuples) and operations.
A relation is a particular kind of set, which has a number of named attributes and
a number of tuples, which must express a value for every attribute.
Set operations like union, intersection and difference are restricted and can only be
performed on relations which share the same set of named attributes.
The constructor optionally accepts a filename and then it will load the relation from
that file.
If no parameter is supplied an empty relation is created.
Files need to be comma separated as described in RFC4180.
The first line need to contain the attributes of the relation while the
following lines contain the tuples of the relation.
An empty relation needs a header, and can be filled using the insert()
method.
'''
__hash__ = None
def __init__(self, filename=""):
self._readonly = False
self.content = set()
if len(filename) == 0: # Empty relation
self.header = Header([])
return
with open(filename) as fp:
reader = csv.reader(fp) # Creating a csv reader
self.header = Header(next(reader)) # read 1st line
iterator = ((self.insert(i) for i in reader))
deque(iterator, maxlen=0)
def _make_duplicate(self, copy):
'''Flag that the relation "copy" is pointing
to the same set as this relation.'''
self._readonly = True
copy._readonly = True
def _make_writable(self, copy_content=True):
'''If this relation is marked as readonly, this
method will copy the content to make it writable too
if copy_content is set to false, the caller must
separately copy the content.'''
if self._readonly:
self._readonly = False
if copy_content:
self.content = set(self.content)
def __iter__(self):
return iter(self.content)
def __contains__(self, key):
return key in self.content
def save(self, filename):
'''
Saves the relation in a file. Will save using the csv
format as defined in RFC4180.
'''
with open(filename, 'w') as fp:
writer = csv.writer(fp) # Creating csv writer
# It wants an iterable containing iterables
head = (self.header,)
writer.writerows(head)
# Writing content, already in the correct format
writer.writerows(self.content)
def _rearrange(self, other):
'''If two relations share the same attributes in a different order, this method
will use projection to make them have the same attributes' order.
It is not exactely related to relational algebra. Just a method used
internally.
Will raise an exception if they don't share the same attributes'''
if not isinstance(other, relation):
raise TypeError('Expected an instance of the same class')
elif self.header == other.header:
return other
elif len(self.header) == len(other.header) and self.header.sharedAttributes(other.header) == len(self.header):
return other.projection(self.header)
raise TypeError('Relations differ: [%s] [%s]' % (
','.join(self.header), ','.join(other.header)
))
def selection(self, expr):
'''
Selection, expr must be a valid Python expression; can contain field names.
'''
newt = relation()
newt.header = Header(self.header)
try:
c_expr = compile(expr, 'selection', 'eval')
except:
raise Exception('Failed to compile expression: %s' % expr)
for i in self.content:
# Fills the attributes dictionary with the values of the tuple
attributes = {attr: i[j].autocast()
for j, attr in enumerate(self.header)
}
try:
if eval(c_expr, attributes):
newt.content.add(i)
except Exception as e:
raise Exception(
"Failed to evaluate %s\n%s" % (expr, e.__str__()))
return newt
def product(self, other):
'''
Cartesian product. Attributes of the relations must differ.
'''
if (not isinstance(other, relation)):
raise Exception('Operand must be a relation')
if self.header.sharedAttributes(other.header) != 0:
raise Exception(
'Unable to perform product on relations with colliding attributes'
)
newt = relation()
newt.header = Header(self.header + other.header)
for i in self.content:
for j in other.content:
newt.content.add(i + j)
return newt
def projection(self, * attributes):
'''
Can be called in two different ways:
a.projection('field1','field2')
or
a.projection(['field1','field2'])
The cardinality of the result, might be less than the cardinality
of the original object.
'''
# Parameters are supplied in a list, instead with multiple parameters
if not isinstance(attributes[0], str):
attributes = attributes[0]
ids = self.header.getAttributesId(attributes)
if len(ids) == 0:
raise Exception('Invalid attributes for projection')
newt = relation()
# Create the header
h = (self.header[i] for i in ids)
newt.header = Header(h)
# Create the body
for i in self.content:
row = (i[j] for j in ids)
newt.content.add(tuple(row))
return newt
def rename(self, params):
'''
Takes a dictionary.
Will replace the field name as the key with its value.
For example if you want to rename a to b, call
rel.rename({'a':'b'})
'''
newt = relation()
newt.header = self.header.rename(params)
newt.content = self.content
self._make_duplicate(newt)
return newt
def intersection(self, other):
'''
Intersection operation. The result will contain items present in both
operands.
Will return an empty one if there are no common items.
'''
other = self._rearrange(other) # Rearranges attributes' order
newt = relation()
newt.header = Header(self.header)
newt.content = self.content.intersection(other.content)
return newt
def difference(self, other):
'''Difference operation. The result will contain items present in first
operand but not in second one.
'''
other = self._rearrange(other) # Rearranges attributes' order
newt = relation()
newt.header = Header(self.header)
newt.content = self.content.difference(other.content)
return newt
def division(self, other):
'''Division operator
The division is a binary operation that is written as R ÷ S. The
result consists of the restrictions of tuples in R to the
attribute names unique to R, i.e., in the header of R but not in the
header of S, for which it holds that all their combinations with tuples
in S are present in R.
'''
# d_headers are the headers from self that aren't also headers in other
d_headers = tuple(set(self.header) - set(other.header))
# Wikipedia defines the division as follows:
# a1,....,an are the d_headers
# T := πa1,...,an(R) × S
# U := T - R
# V := πa1,...,an(U)
# W := πa1,...,an(R) - V
# W is the result that we want
t = self.projection(d_headers).product(other)
return self.projection(d_headers).difference(t.difference(self).projection(d_headers))
def union(self, other):
'''Union operation. The result will contain items present in first
and second operands.
'''
other = self._rearrange(other) # Rearranges attributes' order
newt = relation()
newt.header = Header(self.header)
newt.content = self.content.union(other.content)
return newt
def thetajoin(self, other, expr):
'''Defined as product and then selection with the given expression.'''
return self.product(other).selection(expr)
def outer(self, other):
'''Does a left and a right outer join and returns their union.'''
a = self.outer_right(other)
b = self.outer_left(other)
return a.union(b)
def outer_right(self, other):
'''
Outer right join. Considers self as left and param as right. If the
tuple has no corrispondence, empy attributes are filled with a "---"
string. This is due to the fact that the None token would cause
problems when saving and reloading the relation.
Just like natural join, it works considering shared attributes.
'''
return other.outer_left(self)
def outer_left(self, other, swap=False):
'''
See documentation for outer_right
'''
shared = self.header.intersection(other.header)
newt = relation() # Creates the new relation
# Creating the header with all the fields, done like that because order is
# needed
h = (i for i in other.header if i not in shared)
newt.header = Header(chain(self.header, h))
# Shared ids of self
sid = self.header.getAttributesId(shared)
# Shared ids of the other relation
oid = other.header.getAttributesId(shared)
# Non shared ids of the other relation
noid = [i for i in range(len(other.header)) if i not in oid]
for i in self.content:
# Tuple partecipated to the join?
added = False
for j in other.content:
match = True
for k in range(len(sid)):
match = match and (i[sid[k]] == j[oid[k]])
if match:
item = chain(i, (j[l] for l in noid))
newt.content.add(tuple(item))
added = True
# If it didn't partecipate, adds it
if not added:
item = chain(i, repeat(rstring('---'), len(noid)))
newt.content.add(tuple(item))
return newt
def join(self, other):
'''
Natural join, joins on shared attributes (one or more). If there are no
shared attributes, it will behave as the cartesian product.
'''
# List of attributes in common between the relations
shared = self.header.intersection(other.header)
newt = relation() # Creates the new relation
# Creating the header with all the fields, done like that because order is
# needed
h = (i for i in other.header if i not in shared)
newt.header = Header(chain(self.header, h))
# Shared ids of self
sid = self.header.getAttributesId(shared)
# Shared ids of the other relation
oid = other.header.getAttributesId(shared)
# Non shared ids of the other relation
noid = [i for i in range(len(other.header)) if i not in oid]
for i in self.content:
for j in other.content:
match = True
for k in range(len(sid)):
match = match and (i[sid[k]] == j[oid[k]])
if match:
item = chain(i, (j[l] for l in noid))
newt.content.add(tuple(item))
return newt
def __eq__(self, other):
if not isinstance(other, relation):
return False
if len(self.content) != len(other.content):
return False
if set(self.header) != set(other.header):
return False
# Rearranges attributes' order so can compare tuples directly
other = self._rearrange(other)
# comparing content
return self.content == other.content
def __len__(self):
return len(self.content)
def __str__(self):
m_len = [len(i) for i in self.header] # Maximum lenght string
for f in self.content:
for col, i in enumerate(f):
if len(i) > m_len[col]:
m_len[col] = len(i)
res = ""
for f, attr in enumerate(self.header):
res += "%s" % (attr.ljust(2 + m_len[f]))
for r in self.content:
res += "\n"
for col, i in enumerate(r):
res += "%s" % (i.ljust(2 + m_len[col]))
return res
def update(self, expr, dic):
'''
Updates certain values of a relation.
expr must be a valid Python expression that can contain field names.
This operation will change the relation itself instead of generating a new one,
updating all the tuples where expr evaluates as True.
Dic must be a dictionary that has the form "field name":"new value". Every kind of value
will be converted into a string.
Returns the number of affected rows.
'''
self._make_writable(copy_content=False)
affected = self.selection(expr)
not_affected = self.difference(affected)
new_values = tuple(
zip(self.header.getAttributesId(dic.keys()), dic.values())
)
for i in set(affected.content):
i = list(i)
for column, value in new_values:
i[column] = value
not_affected.insert(i)
self.content = not_affected.content
return len(affected)
def insert(self, values):
'''
Inserts a tuple in the relation.
This function will not insert duplicate tuples.
All the values will be converted in string.
Will return the number of inserted rows.
Will fail if the tuple has the wrong amount of items.
'''
if len(self.header) != len(values):
raise Exception(
'Tuple has the wrong size. Expected %d, got %d' % (
len(self.header),
len(values)
)
)
self._make_writable()
prevlen = len(self.content)
self.content.add(tuple(map(rstring, values)))
return len(self.content) - prevlen
def delete(self, expr):
'''
Delete, expr must be a valid Python expression; can contain field names.
This operation will change the relation itself instead of generating a new one,
deleting all the tuples where expr evaluates as True.
Returns the number of affected rows.'''
l = len(self.content)
self._make_writable(copy_content=False)
self.content = self.difference(self.selection(expr)).content
return len(self.content) - l
class Header(tuple):
'''This class defines the header of a relation.
It is used within relations to know if requested operations are accepted'''
def __new__(cls, fields):
return super(Header, cls).__new__(cls, tuple(fields))
def __init__(self, *args, **kwargs):
'''Accepts a list with attributes' names. Names MUST be unique'''
for i in self:
if not is_valid_relation_name(i):
raise Exception('"%s" is not a valid attribute name' % i)
if len(self) != len(set(self)):
raise Exception('Attribute names must be unique')
def __repr__(self):
return "Header(%s)" % super(Header, self).__repr__()
def rename(self, params):
'''Returns a new header, with renamed fields.
params is a dictionary of {old:new} names
'''
attrs = list(self)
for old, new in params.items():
if not is_valid_relation_name(new):
raise Exception('%s is not a valid attribute name' % new)
try:
id_ = attrs.index(old)
attrs[id_] = new
except:
raise Exception('Field not found: %s' % old)
return Header(attrs)
def sharedAttributes(self, other):
'''Returns how many attributes this header has in common with a given one'''
return len(set(self).intersection(set(other)))
def union(self, other):
'''Returns the union of the sets of attributes with another header.'''
return set(self).union(set(other))
def intersection(self, other):
'''Returns the set of common attributes with another header.'''
return set(self).intersection(set(other))
def getAttributesId(self, param):
'''Returns a list with numeric index corresponding to field's name'''
try:
return [self.index(i) for i in param]
except ValueError as e:
raise Exception('One of the fields is not in the relation: %s' % ','.join(param))
# Backwards compatibility
relation = Relation
header = Header
relational/samples/ 0000755 0001750 0001750 00000000000 12757112451 013713 5 ustar salvo salvo relational/samples/dates.csv 0000644 0001750 0001750 00000000105 12757112451 015524 0 ustar salvo salvo "date"
"2008-12-12"
"2007-08-12"
"1985-05-09"
"1988-4-21"
"1992-7-27" relational/samples/rooms.csv 0000644 0001750 0001750 00000000146 12757112451 015570 0 ustar salvo salvo "room","phone"
"0","1515"
"1","1516"
"2","1617"
"3","1601"
"4","1041"
"5","9212"
"6","1424"
"7","1294" relational/samples/paghe.csv 0000644 0001750 0001750 00000000203 12757112451 015507 0 ustar salvo salvo grado,paga
Tenente,10000
Comandante,1000000
Tenente Comandante,100000
Capitano,10000000
Sottotenente,1000
Guardiamarina,100
relational/samples/people.csv 0000644 0001750 0001750 00000000163 12757112451 015714 0 ustar salvo salvo id,name,chief,age
0,jack,0,22
1,carl,0,20
2,john,1,30
3,dean,1,33
4,eve,0,25
5,duncan,4,30
6,paul,4,30
7,alia,1,28
relational/samples/skills.csv 0000644 0001750 0001750 00000000302 12757112451 015724 0 ustar salvo salvo "id","skill"
"0","C"
"0","Python"
"1","Python"
"1","C++"
"1","System Admin"
"2","C"
"2","PHP"
"3","C++"
"4","C++"
"4","C"
"4","Perl"
"5","Perl"
"5","C"
"7","Python"
"7","C"
"7","PHP"
"9","Java"
relational/samples/person_room.csv 0000644 0001750 0001750 00000000113 12757112451 016765 0 ustar salvo salvo "id","room"
"0","1"
"1","4"
"2","2"
"3","2"
"4","5"
"5","1"
"6","5"
"7","1" relational/samples/equipaggio.csv 0000644 0001750 0001750 00000000415 12757112451 016562 0 ustar salvo salvo nome,grado
Jean Luc Picard,Capitano
Deanna Troy,Comandante
William T. Riker,Comandante
Data,Tenente Comandante
Worf,Tenente
Beverly Crusher,Comandante
O'Brian,Capo di Prima Classe
Rho Laren,Tenente
Geordi La Forge,Tenente Comandante
Reginald Barklay,Tenente
relational/samples/ratings.csv 0000644 0001750 0001750 00000000070 12757112451 016074 0 ustar salvo salvo id,rating
0,5.3
1,6
2,5.7
3,3.3
4,9.1
5,4.4
6,5.1
7,4.9
relational/relational_gui.py 0000755 0001750 0001750 00000010021 12757112451 015614 0 ustar salvo salvo #!/usr/bin/env python3
# Relational
# Copyright (C) 2008-2016 Salvo "LtWorf" Tomaselli
#
# Relational is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
import sys
import os
import os.path
import getopt
version = "2.5"
def printver(exit=True):
print ("Relational %s" % version)
print ("Copyright (C) 2008-2016 Salvo 'LtWorf' Tomaselli.")
print ()
print ("This program comes with ABSOLUTELY NO WARRANTY.")
print ("This is free software, and you are welcome to redistribute it")
print ("under certain conditions.")
print ("For details see the GPLv3 Licese.")
print ()
print ("Written by Salvo 'LtWorf' Tomaselli ")
print ()
print ("http://ltworf.github.io/relational/")
if exit:
sys.exit(0)
def printhelp(code=0):
print ("Relational")
print ()
print ("Usage: %s [options] [files]" % sys.argv[0])
print ()
print (" -v Print version and exits")
print (" -h Print this help and exits")
if sys.argv[0].endswith('relational-cli'):
print (" -q Uses QT user interface")
print (" -r Uses readline user interface (default)")
else:
print (" -q Uses QT user interface (default)")
print (" -r Uses readline user interface")
sys.exit(code)
if __name__ == "__main__":
if sys.argv[0].endswith('relational-cli'):
x11 = False
else:
x11 = True # Will try to use the x11 interface
# Getting command line
try:
switches, files = getopt.getopt(sys.argv[1:], "vhqr")
except:
printhelp(1)
for i in switches:
if i[0] == '-v':
printver()
elif i[0] == '-h':
printhelp()
elif i[0] == '-q':
x11 = True
elif i[0] == '-r':
x11 = False
if x11:
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
import sip # needed on windows
from PyQt5 import QtWidgets
try:
from relational_gui import guihandler, about, surveyForm
except:
print (
"Module relational_gui is missing.\n"
"Please install relational package or run make.",
file=sys.stderr
)
sys.exit(3)
m = zip(files, map(os.path.isfile, files))
invalid = ' '.join(
(i[0] for i in (filter(lambda x: not x[1], m)))
)
if invalid:
print ("%s: not a file" % invalid, file=sys.stderr)
printhelp(12)
about.version = version
surveyForm.version = version
guihandler.version = version
app = QtWidgets.QApplication(sys.argv)
app.setOrganizationName('None')
app.setApplicationName('relational')
app.setOrganizationDomain("None")
form = guihandler.relForm()
if len(files):
form.loadRelation(files)
form.show()
sys.exit(app.exec_())
else:
try:
import relational_readline.linegui
if relational_readline.linegui.TTY:
printver(False)
except:
print (
"Module relational_readline is missing.\nPlease install relational-cli package.",
file=sys.stderr
)
sys.exit(3)
relational_readline.linegui.version = version
relational_readline.linegui.main(files)
relational/COPYING 0000644 0001750 0001750 00000104513 12757112451 013306 0 ustar salvo salvo GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
relational/driver.py 0000755 0001750 0001750 00000020375 12757112451 014126 0 ustar salvo salvo #!/usr/bin/env python3
# Relational
# Copyright (C) 2010-2016 Salvo "LtWorf" Tomaselli
#
# Relational is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
import os
from sys import exit
import sys
import traceback
from relational import relation, parser, optimizer
from xtermcolor import colorize
COLOR_RED = 0xff0000
COLOR_GREEN = 0x00ff00
COLOR_MAGENTA = 0xff00ff
COLOR_CYAN = 0x00ffff
print(relation)
rels = {}
examples_path = 'samples/'
tests_path = 'test/'
def readfile(fname):
'''Reads a file as string and returns its content'''
fd = open(fname, encoding='utf-8')
expr = fd.read()
fd.close()
return expr
def load_relations():
'''Loads all the relations present in the directory indicated in the
examples_path variable and stores them in the rels dictionary'''
print("Loading relations")
for i in os.listdir(examples_path):
if i.endswith('.csv'): # It's a relation, loading it
# Naming the relation
relname = i[:-4]
print ("Loading relation %s with name %s..." % (i, relname))
rels[relname] = relation.relation('%s%s' % (examples_path, i))
print('done')
def execute_tests():
py_bad = 0
py_good = 0
py_tot = 0
q_bad = 0
q_good = 0
q_tot = 0
ex_bad = 0
ex_good = 0
ex_tot = 0
f_tot = 0
f_good = 0
f_bad = 0
for i in os.listdir(tests_path):
if i.endswith('.query'):
q_tot += 1
if run_test(i[:-6]):
q_good += 1
else:
q_bad += 1
elif i.endswith('.python'):
py_tot += 1
if run_py_test(i[:-7]):
py_good += 1
else:
py_bad += 1
elif i.endswith('.py'):
ex_tot += 1
if run_exec_test(i[:-3]):
ex_good += 1
else:
ex_bad += 1
elif i.endswith('.fail'):
f_tot += 1
if run_fail_test(i[:-5]):
f_good += 1
else:
f_bad += 1
print (colorize("Resume of the results", COLOR_CYAN))
print (colorize("Query tests", COLOR_MAGENTA))
print ("Total test count: %d" % q_tot)
print ("Passed tests: %d" % q_good)
if q_bad > 0:
print (colorize("Failed tests count: %d" % q_bad, COLOR_RED))
print (colorize("Python tests", COLOR_MAGENTA))
print ("Total test count: %d" % py_tot)
print ("Passed tests: %d" % py_good)
if py_bad > 0:
print (colorize("Failed tests count: %d" % py_bad, COLOR_RED))
print (colorize("Execute Python tests", COLOR_MAGENTA))
print ("Total test count: %d" % ex_tot)
print ("Passed tests: %d" % ex_good)
if ex_bad > 0:
print (colorize("Failed tests count: %d" % ex_bad, COLOR_RED))
print (colorize("Execute fail tests", COLOR_MAGENTA))
print ("Total test count: %d" % f_tot)
print ("Passed tests: %d" % f_good)
if f_bad > 0:
print (colorize("Failed tests count: %d" % f_bad, COLOR_RED))
print (colorize("Total results", COLOR_CYAN))
if f_bad + q_bad + py_bad + ex_bad == 0:
print (colorize("No failed tests", COLOR_GREEN))
return 0
else:
print (colorize("There are %d failed tests" %
(f_bad + py_bad + q_bad + ex_bad), COLOR_RED))
return 1
def run_exec_test(testname):
'''Runs a python test, which executes code directly rather than queries'''
print ("Running python test: " + colorize(testname, COLOR_MAGENTA))
glob = rels.copy()
exp_result = {}
expr = readfile('%s%s.py' % (tests_path, testname))
try:
exec(expr, glob) # Evaluating the expression
print (colorize('Test passed', COLOR_GREEN))
return True
except Exception as e:
print (colorize('ERROR', COLOR_RED))
print (colorize('=====================================', COLOR_RED))
traceback.print_exc(file=sys.stdout)
print (colorize('=====================================', COLOR_RED))
return False
def run_py_test(testname):
'''Runs a python test, which evaluates expressions directly rather than queries'''
print ("Running expression python test: " +
colorize(testname, COLOR_MAGENTA))
try:
expr = readfile('%s%s.python' % (tests_path, testname))
result = eval(expr, rels)
expr = readfile('%s%s.result' % (tests_path, testname))
exp_result = eval(expr, rels)
if result == exp_result:
print (colorize('Test passed', COLOR_GREEN))
return True
except:
pass
print (colorize('ERROR', COLOR_RED))
print (colorize('=====================================', COLOR_RED))
print ("Expected %s" % exp_result)
print ("Got %s" % result)
print (colorize('=====================================', COLOR_RED))
return False
def run_fail_test(testname):
'''Runs a test, which executes a query that is supposed to fail'''
print ("Running fail test: " + colorize(testname, COLOR_MAGENTA))
query = readfile('%s%s.fail' % (tests_path, testname)).strip()
test_succeed = True
try:
expr = parser.parse(query)
expr(rels)
test_succeed = False
except:
pass
try:
o_query = optimizer.optimize_all(query, rels)
o_expr = parser.parse(o_query)
o_expr(rels)
test_succeed = False
except:
pass
try:
c_expr = parser.tree(query).toCode()
eval(c_expr, rels)
test_succeed = False
except:
pass
if test_succeed:
print (colorize('Test passed', COLOR_GREEN))
else:
print (colorize('Test failed (by not raising any exception)', COLOR_RED))
return test_succeed
def run_test(testname):
'''Runs a specific test executing the file
testname.query
and comparing the result with
testname.result
The query will be executed both unoptimized and
optimized'''
print ("Running test: " + colorize(testname, COLOR_MAGENTA))
query = None
expr = None
o_query = None
o_expr = None
result_rel = None
result = None
o_result = None
try:
result_rel = relation.relation('%s%s.result' % (tests_path, testname))
query = readfile('%s%s.query' % (tests_path, testname)).strip()
o_query = optimizer.optimize_all(query, rels)
expr = parser.parse(query)
result = expr(rels)
o_expr = parser.parse(o_query)
o_result = o_expr(rels)
c_expr = parser.tree(query).toCode()
c_result = eval(c_expr, rels)
if (o_result == result_rel) and (result == result_rel) and (c_result == result_rel):
print (colorize('Test passed', COLOR_GREEN))
return True
except Exception as inst:
traceback.print_exc(file=sys.stdout)
print (inst)
pass
print (colorize('ERROR', COLOR_RED))
print ("Query: %s -> %s" % (query, expr))
print ("Optimized query: %s -> %s" % (o_query, o_expr))
print (colorize('=====================================', COLOR_RED))
print (colorize("Expected result", COLOR_GREEN))
print (result_rel)
print (colorize("Result", COLOR_RED))
print (result)
print (colorize("Optimized result", COLOR_RED))
print (o_result)
print (colorize("optimized result match %s" %
str(result_rel == o_result), COLOR_MAGENTA))
print (colorize("result match %s" %
str(result == result_rel), COLOR_MAGENTA))
print (colorize('=====================================', COLOR_RED))
return False
if __name__ == '__main__':
print ("-> Starting testsuite for relational")
load_relations()
print ("-> Starting tests")
exit(execute_tests())
relational/README.md 0000644 0001750 0001750 00000002402 12757112451 013524 0 ustar salvo salvo Relational an educational tool to provide a workspace for experimenting with *relational* *algebra*, an offshoot of first-order logic.
It works on GNU/Linux, Windows and OS X.
It provides:
* A GUI that can be used for executing relational queries
* A standalone Python module that can be used for executing relational queries, parsing relational expressions and optimizing them
* A command line interface
Official website
================
More documentation can be found here http://ltworf.github.io/relational/
Install
=======
Binary download for Windows can be obtained from the website.
For Linux, check your distribution's packages, relational is available on Debian and Ubuntu.
Syntax
======
These are some valid queries
```
σage > 25 and rank == weight(A)
σ (name.upper().startswith('J') and age>21 )(people)
Q ⋈ π a,b(A) ⋈ B
ρid➡i,name➡n(A) - π a,b(π a,b(A)) ∩ σage > 25 or rank = weight(A)
π a,b(π a,b(A))
ρ id➡i,name➡n(π a,b(A))
A ⋈ B
```
Run from sources
================
If it needs some dependencies:
* Qt5
* Python 3.4 or greater
* PyQt5
* pyuic5 and pyrcc5
You will need to run
```
make
```
to generate some .py files.
To launch the application, run
```
./relational_gui.py
```
or
```
python3 relational_gui.py
```
relational/CHANGELOG 0000644 0001750 0001750 00000021661 12757112451 013467 0 ustar salvo salvo 2.5
- Add new class of tests for queries that are supposed to fail
- Changes to make failures in commutative operators commutative too
- Added new optimization to remove useless joins
- Correct optimization over selection and product
- Fix Python code generator to correctly escape strings
- Improved multi-line text editor
- Multi-line mode has support for optimizations
- Workaround a QSettings bug so that sessions work again
- "Save" button works on the relation selected in the list, instead of the
one shown in the central table
2.4
- Improve error reporting
- Release is now signed with PGP
- Doesn't crash on network errors
- Fixed optimization introduced in 2.2 that did not hold in all cases
- Better handling of parenthesis inside string literals
- Emit less parenthesis in optimized queries
2.3
- Very small release. The windows setup now installs the C++ library
automatically.
- The setup was re-made on windows 10, so now it works properly on windows 10
and all the symbols are shown.
- If you don't use windows, this release is identical to the previous.
2.2
- Added again make install target
- Ctrl+C in the terminal will terminate the GUI
- UI indicates ongoing processing with a label
- Added new optimizations
- Added shortcuts within the UI
- History can be navigated with up/down arrows
- Single line edit mode allows for the resulting relation to be written
within the query textbox itself.
2.1
- Introduced sessions; GUI loads the same relations of the previous time
- redesigned GUI, to fit in smaller screens
- Fix bug in tokenizer
- Fixed bug where select on relations with '---' values would always fail
- Improve error reporting
- Fix bug in code to check for new version
- Performance improvements
- More Pythonic name for classes (API is compatible with version 2.0)
2.0
- Fix bug in relational-cli that made it crash when an exception was raised
- Point to new website
- Switch to Python3 and drop support for Python2
- Switch to Qt5
- Radical change of language. The UNICODE symbols used previously were meant for a
Canadian Aborigenal script. Now switched them to use UNICODE math symbols.
- Since the language is changing, take the chance to use better symbols for JOIN
- GUI has a new mode to insert multiple queries at once, assigning them to variables
- Automatic casting is now faster
- GUI can load multiple relations at once
- GUI will only assign default names to loaded relations, without prompting the user
1.2
- Better tokenizer, gives more indicative errors
- Parser gives more indicative errors
- Improved select_union_intersect_subtract optimization to avoid parenthesis whenever possible
- Moved feedback service, and added the code for it
- Different way of checking the latest version
- Removed support for pyside
1.1
- Incorrect relational operations now raise an exception instead of returning None
- Forces relations to have correct names for attributes
- Colored output in readline mode
- Can send email in survey
- Can check for new version online
- Can use both PySide and PyQt
- Removed buttons for adding and deleting tuples
- Can edit relations within the GUI
- API migrated to unicode (instead of utf-8 encoded strings)
1.0
- Adds history in the GUI
- Adds menus to the GUI
- Checks if given name to relations are valid
- Discards the old and not so functional tlb format
- Float type recognition is more robust, now handled using a regexp
- Date type recognition is more robust, now using a combination of regexp plus date object
- Integer type recognition now allows negative numbers in relations
- Rename operations are now much faster, content won't be copied unless subsequent updates, insert, updates or deletes will occur
- Added testsuite
- Module parallel does something, can execute queries in parallel
- Implemented select_union_intersect_subtract general optimization
- Removed encoding from .desktop file (was deprecated)
- Added manpage for relational-cli
- Internally uses set instead of lists to describe relation's content
- Tuples are internally mapped on tuples and no longer on lists
- Set hash method for the classes
- Parsing of strings representing dates is now cached, eliminating the need for double parse
- Fixed python expression tokenization, now uses native tokenizer
- Fixed optimization involving selection and parenthesis in the expression (Rev 260)
- Fixed futile_union_intersection_subtraction optimization that didn't work when selection operator was in the left subtree (Rev 261)
- Restyle of the GUI, splitters added
0.11
- Font is set only on windows (Rev 206)
- Improved futile_union_intersection_subtraction in case of A-A, when A is a sub-query (Rev 208)
- Improved futile_union_intersection_subtraction, handles when a branch of subtracion has a selection (Rev 209)
- Can load relations specified in command line (Rev 210)
- Using fakeroot instead of su in make debian (Rev 214)
- Fixed problem with float numbers with selection of certain relations (Rev 215)
- Added .desktop file on svn (Rev 216)
- Automatically fills some fields in the survey (Rev 217)
- When a query fails, shows the message of the exception (Rev220)
- Improved tokenizer for select in optimizations, now can accept operators in identifiers (Rev 220)
- Uses getopt to handle the command line in a more standard way
- Organized code so the ui can be either qt or command line
- Does not depend on QT anymore
- Added readline user interface
- Added division operator
0.10
- In optimizer, added a function that tokenizes an expression
- Document about complexity of operations
- Bug: error in update operation, it changed the original tuple, so also other relations using the same tuple would change. Now it copies it.
- Added make install and uninstall
- Optimizer generate a tree from the expression
- Uses python-psyco when it is available
- Ability to perform optimizations from GUI
- Able to (temporarily) store queries with a name
- Mechanism to add new kind of optimizations, without having to edit all the code
- Implemented duplicated_select general optimization
- Implemented down_to_unions_subtractions_intersections general optimization
- Implemented duplicated_projection general optimization
- Implemented selection_inside_projection general optimization
- Implemented subsequent_renames general optimization
- Implemented swap_rename_select general optimization
- Implemented selection_and_product specific optimization
- Added stub for converting SQL to relational algebra
- Implemented futile_union_intersection_subtraction general optimization
- Implemented swap_rename_projection general optimization
- Replaced old relational algebra to python compiler with new one based on the new tokenizer/parser (Rev 188)
- Code refactory to move the new parser into parser.py out of optimizer.py, that will still be compatible (Rev 190)
- Selection can now accept expressions with parenthesis
0.9
- Splitted into independent packages (gui and library)
- Simplified makefile, bringing outside files for debian package
- Default source package now doesn't contain informations to generate debian/mac packages
- "make source_all" generates the old style tarball containing all the files
- Bug: relational script installed with debian package now passes arguments to the python executable
- Insert and delete from GUI are now done on the displayed relation, not on the selected one
0.8
- Added __eq__ to relation object, will compare ignoring order.
- New default relation's format is csv, as defined in RFC4180
- Converted sample's relations to csv
- Deb postinstall generates optimized files, this will increase loading speed
- Relation module has SQL-like delete
- Relation module has SQL-like update
- Relation module has SQL-like insert
- GUI can be used to insert and delete tuples
- Showing fields of selected relation will work with themes different than oxygen
0.7
- Added README
- Expressions between quotes aren't parsed anymore
- When adding a relation, the file must be chosen 1st, and then the default relation's name is the same as the filename
- Changed internal rename method. Now uses a dictionary
- Optimized saving of relations
- Can save relations from gui
- Outer join methods simplified
- Form to send a survey
- Makefile to create .deb package
0.6
- Fixes to run on Mac OsX
- Added Makefile
- Able to create .app MacOsX files using "make app"
- Able to create tar.gz file containing Mac OsX application and samples using "make mac"
0.5
- Added support for float numbers
- Added support for dates
0.4
- Created GUI
0.3
- Added support for parenthesis in relational queries
0.2
- Created parser module
- Created function to parse expression with operators without parameters
- Created recoursive function to parse expressions
0.1
- Created header class to handle attributes
- Created relation class
- Added union
- Added intersection
- Added difference
- Added product
- Added projection
- Added rename
- Projection can use a list or several parameters
- Added selection
- Added left join
- Added right join
- Added capability of operation even if attributes aren't in the same order
- Added full outer join
relational/feedback-ltworf/ 0000755 0001750 0001750 00000000000 12757112451 015306 5 ustar salvo salvo relational/feedback-ltworf/app.yaml 0000644 0001750 0001750 00000000217 12757112451 016752 0 ustar salvo salvo application: feedback-ltworf
version: 4
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: feedback.application
relational/feedback-ltworf/feedback.py 0000644 0001750 0001750 00000001722 12757112451 017406 0 ustar salvo salvo from google.appengine.api import users
import webapp2
import micro_webapp2
application = micro_webapp2.WSGIApplication()
@application.route('/')
def m(request, *args, **kwargs):
return ""
@application.route("/version/")
def show_version(request, *args, **kwargs):
if kwargs["id"] == "relational":
return "2.5"
return "No version"
@application.route('/feedback/')
def mail_sender(request, *args, **kwargs):
if request.method != "POST":
return ""
message = ""
for k,v in request.POST.iteritems():
message += "%s: %s\n" % (k,v)
message += "ip address: %s\n" % str(request.remote_addr)
if kwargs["id"] == "relational":
from google.appengine.api import mail
mail.send_mail(sender="Feedback service ",
to="tiposchi@tiscali.it",
subject="Feedback from %s" % kwargs["id"],
body=message)
return "Message queued"
relational/feedback-ltworf/micro_webapp2.py 0000644 0001750 0001750 00000001327 12757112451 020414 0 ustar salvo salvo import webapp2
class WSGIApplication(webapp2.WSGIApplication):
def __init__(self, *args, **kwargs):
super(WSGIApplication, self).__init__(*args, **kwargs)
self.router.set_dispatcher(self.__class__.custom_dispatcher)
@staticmethod
def custom_dispatcher(router, request, response):
rv = router.default_dispatcher(request, response)
if isinstance(rv, basestring):
rv = webapp2.Response(rv)
elif isinstance(rv, tuple):
rv = webapp2.Response(*rv)
return rv
def route(self, *args, **kwargs):
def wrapper(func):
self.router.add(webapp2.Route(handler=func, *args, **kwargs))
return func
return wrapper
relational/complexity 0000644 0001750 0001750 00000011201 12757112451 014362 0 ustar salvo salvo
Complexity
Abstract
Purpose of this document is to describe in a detailed way the
complexity of relational algebra operations. The evaluation will be
done on the specific implementation of this program, not on theorical
lower limits.
Latest implementation can be found at:
https://github.com/ltworf/relational
Notation
Big O notation will be used. Constant values will be ignored.
Single letters will be used to indicate relations and letters between
| will indicate the cardinality (number of tuples) of the relation.
Number of tuples can't be enough. For example a relation with one
touple and thousands of fields, will not take O(1) in general to be
evaluated. So we assume that relations will have a reasonable and
comparable number of fields.
Then after evaluating the big O notation, an attempt to find more
precise results will be done, since it will be important to know
with a certain precision the weight of the operation.
1. UNARY OPERATORS
Relational defines three unary operations, and they will be studied
in this section. It doesn't mean that they should have similar
complexity.
1.1 Selection
Selection works on a relation and on a python expression. For each
tuple of the relation, it will create a dictionary with name:value
where name are names of the fields in the relation and value is the
value for the specific row.
We can consider the inner cycle as constant as its value doesn't
depend on the relation itself but only on the kind of the relation
(how many field it has).
Then comes the evaluation. A python expression in truth could do
much more things than just checking if a>b. Anyway, ssuming that
nobody would ever write cycles into a selection condition, we have
another constant complexity for this operation.
Then, the tuple is inserted in a new relation if it satisfies the
condition. Since no check on duplicated tuples is performed, this
operation is constant too.
In the end we have O(|n|) as complexity for a selection on the
relation n.
1.2 Rename
The rename operation itself is very simple, just modify the list
containing the name of the fields.
The big issue is to copy the content of the relation into a new
relation object, so the new one can be modified.
So the operation depends on the size of the relation: O(|n|).
1.3 Projection
The projection operation creates a copy of the original relation
using only a subset of its fields. Time for the copy is something
like O(|n|) where f is the number of fields to copy.
But that's not all. Since relations are set, duplicated items are not
allowed. So after extracting the wanted elements, it has to check if
the new tuple was already added to the new relation. And this brings
the complexity to O(|n|²).
But the projection can also be used to "rearrange" fields, which
makes no sense in pure relational algebra, but can be usefull to make
two relations match (in fact it is used internally to make relations
match if they have the same fields in different order). In this case
there is no need to check if the tuple already exists, because it is
assumed that the relation was correct. This gives a complexity of
O(|n|) in the best case.
2. BINARY OPERATORS
Relational defines nine binary operations, and they will be studied
in this section. Since we will deal with two relations per operation
here, we will call them m and n, and f and g will be the number of
their fields.
2.1 Product
Product is a very complex operations. It is O(|n|*|m|).
Obvious.
2.2 Intersection
Same as product even if it does a different thing. But it has to
compare every tuple from n with every tuple from m, to see if they
match, and in this case, put them in the resulting relation.
So this operation is O(|n|*|m|) as well.
2.3 Difference
Same as above:
2.4 Union
This operation first creates a new relation copying all the tuples
from one of the originating relations, then compares them all with
tuples from the other relation, and if they aren't in, they will be
added.
In fact it is same as above: O(|n|*|m|)
2.5 Thetajoin
This operation is the combination of a product and a selection. So it
is O(|n|*|m|) too.
2.6 Outer
This operation is the union of the outer left and the outer right
join. Makes it O(|n|*|m|) too.
2.7 Outer_left
O(|n|*|m|), very depending on the number of the fields, because they
are compared.
2.8 Outer_right
Mirror operation of outer_lef
2.9 Join
Same as above.
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
relational/relational-cli.1 0000644 0001750 0001750 00000002454 12757112451 015235 0 ustar salvo salvo .TH "Relational" "1"
.SH "NAME"
relational-cli \(em Implementation of Relational algebra.
.SH "SYNOPSIS"
.PP
\fBrelational-cli\fR [OPTIONS\fR\fP] [ FILE .\|.\|.]
.SH "DESCRIPTION"
.PP
This program provides a command line interface to execute relational algebra queries. It is meant to experiment with relational algebra queries.
.SH "SCRIPTING"
.PP
The tool always runs in interactive mode, but it is possible to write a sequence of queries in a script and run it.
relational-cli < script.txt
The result of all the lines that do not terminate with a `;' are printed.
Comments are lines beginning with `;'.
Whenever stdin or stdout are not a terminal, silent mode will be used, which prints less debug information, to avoid cluttering.
.SH "OPTIONS"
.PP
A summary of options is included below.
.IP "\fB-v\fP
Show version information and exit.
.IP "\fB-h\fP
Shows help and exit.
.IP "\fB-q\fP
Uses the Qt5 GUI.
.IP "\fB-r\fP
Uses the readline UI (default).
.SH "AUTHOR"
.PP
This manual page was written by Salvo 'LtWorf' Tomaselli for
the \fBDebian GNU/Linux\fP system (but may be used by others). Permission is
granted to copy, distribute and/or modify this document under
the terms of the GNU General Public License
version 3 or any later version published by the Free Software Foundation.
relational/relational_gui/ 0000755 0001750 0001750 00000000000 12757112451 015245 5 ustar salvo salvo relational/relational_gui/editor_pireal.py 0000644 0001750 0001750 00000013614 12757112451 020446 0 ustar salvo salvo # -*- coding: utf-8 -*-
#
# Copyright 2015 - Gabriel Acosta
#
# This file is part of Pireal.
#
# Pireal is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# any later version.
#
# Pireal is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pireal; If not, see .
from PyQt5.QtWidgets import (
QPlainTextEdit,
QTextEdit
)
from PyQt5.QtGui import (
QTextCharFormat,
QTextCursor,
QColor,
QPalette
)
from PyQt5.QtCore import Qt
from . import highlighter
class Editor(QPlainTextEdit):
def __init__(self, *args, **kwargs):
super(Editor, self).__init__(*args, **kwargs)
self._highlighter = highlighter.Highlighter(self.document())
self.__cursor_position_changed()
# Menu
self.setContextMenuPolicy(Qt.CustomContextMenu)
# Connection
self.cursorPositionChanged.connect(self.__cursor_position_changed)
def __cursor_position_changed(self):
extra_selections = []
_selection = QTextEdit.ExtraSelection()
extra_selections.append(_selection)
# Highlight current line
if True:
color = QPalette().color(QPalette.Normal, QPalette.Window).lighter()
_selection.format.setBackground(color)
_selection.format.setProperty(
QTextCharFormat.FullWidthSelection, True)
_selection.cursor = self.textCursor()
_selection.cursor.clearSelection()
extra_selections.append(_selection)
# Paren matching
extras = None
if True:
extras = self.__check_brackets()
if extras is not None:
extra_selections.extend(extras)
self.setExtraSelections(extra_selections)
def set_font(self, font):
self.document().setDefaultFont(font)
def __check_brackets(self):
left, right = QTextEdit.ExtraSelection(), QTextEdit.ExtraSelection()
cursor = self.textCursor()
block = cursor.block()
data = block.userData()
previous, _next = None, None
if data is not None:
position = cursor.position()
block_pos = cursor.block().position()
paren = data.paren
print(data,data.paren)
n = len(paren)
for k in range(0, n):
if paren[k].position == position - block_pos or \
paren[k].position == position - block_pos - 1:
previous = paren[k].position + block_pos
if paren[k].character == '(':
_next = self.__match_left(block,
paren[k].character,
k + 1, 0)
elif paren[k].character == ')':
_next = self.__match_right(block,
paren[k].character,
k, 0)
if _next is not None and _next > 0:
if previous is not None and previous > 0:
_format = QTextCharFormat()
cursor.setPosition(previous)
cursor.movePosition(QTextCursor.NextCharacter,
QTextCursor.KeepAnchor)
_format.setForeground(Qt.blue)
_format.setBackground(Qt.white)
left.format = _format
left.cursor = cursor
cursor.setPosition(_next)
cursor.movePosition(QTextCursor.NextCharacter,
QTextCursor.KeepAnchor)
_format.setForeground(Qt.white)
_format.setBackground(Qt.blue)
right.format = _format
right.cursor = cursor
return left, right
elif previous is not None:
_format = QTextCharFormat()
cursor.setPosition(previous)
cursor.movePosition(QTextCursor.NextCharacter,
QTextCursor.KeepAnchor)
_format.setForeground(Qt.white)
_format.setBackground(Qt.red)
left.format = _format
left.cursor = cursor
return (left,)
def __match_left(self, block, char, start, found):
while block.isValid():
data = block.userData()
if data is not None:
paren = data.paren
n = len(paren)
for i in range(start, n):
if paren[i].character == char:
found += 1
if paren[i].character == ')':
if not found:
return paren[i].position + block.position()
else:
found -= 1
block = block.next()
start = 0
def __match_right(self, block, char, start, found):
while block.isValid():
data = block.userData()
if data is not None:
paren = data.paren
if start is None:
start = len(paren)
for i in range(start - 1, -1, -1):
if paren[i].character == char:
found += 1
if paren[i].character == '(':
if found == 0:
return paren[i].position + block.position()
else:
found -= 1
block = block.previous()
start = None
relational/relational_gui/maingui.ui 0000644 0001750 0001750 00000146205 12757112451 017245 0 ustar salvo salvo
Salvo 'LtWorf' Tomaselli
MainWindow
0
0
637
496
0
0
Relational
:/icon:/icon
0
0
0
0
0
-
Qt::Vertical
0
10
150
150
0
0
true
QAbstractItemView::NoSelection
false
Empty relation
0
1
0
0
0
0
0
-
0
0
120
60
DejaVu Sans
11
50
false
false
false
false
true
false
result=query
-
3
-
⌫
Ctrl+Shift+Backspace
-
Execute
Ctrl+Return
false
true
-
Optimize
-
Undo optimize
-
Qt::Vertical
20
40
2
0
0
0
0
-
0
2
120
60
16777215
16777215
0
0
-
Qt::Vertical
QSizePolicy::MinimumExpanding
20
0
-
1
-
Optimize
Ctrl+Shift+O
-
Undo optimize
Ctrl+Shift+U
-
Clear history
Ctrl+Shift+C
-
0
-
-
0
0
50
16777215
⌫
Ctrl+Shift+Backspace
true
-
Execute
Ctrl+Return
true
true
-
Processing…
QDockWidget::DockWidgetMovable
Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea
Operators
1
0
QLayout::SetMinimumSize
0
0
0
0
-
0
0
QFrame::NoFrame
QFrame::Plain
0
0
0
0
0
0
3
-
0
0
40
16777215
Left outer join
⧑
Alt+J, Alt+L
true
-
0
0
40
16777215
➡
Alt+A
true
-
0
0
40
16777215
Union
∪
Alt+U
true
-
0
0
40
16777215
Difference
-
true
-
0
0
40
16777215
Rename
ρ
Alt+R
true
-
0
0
40
16777215
Division
÷
Alt+D
true
-
0
0
40
16777215
Full outer join
⧓
Alt+J, Alt+O
true
-
0
0
40
16777215
Intersection
∩
Alt+I
true
-
0
0
40
16777215
Product
*
true
-
0
0
40
16777215
Right outer join
⧒
Alt+J, Alt+R
true
-
0
0
40
16777215
Projection
π
Alt+P
true
-
0
0
40
16777215
Selection
σ
Alt+S
true
-
0
0
40
16777215
Natural join
⋈
Alt+J, Alt+J
true
-
Qt::Vertical
20
25
QDockWidget::DockWidgetMovable
Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea
Attrib&utes
2
0
0
0
0
0
-
0
0
16777215
16777215
QFrame::NoFrame
QFrame::Plain
195
254
QDockWidget::DockWidgetMovable
Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea
Re&lations
2
0
0
0
0
-
0
0
16777215
16777215
QFrame::NoFrame
true
-
2
0
2
3
-
New
-
Edit
-
Load
-
Save
-
Unload all
-
Unload
99
101
QDockWidget::DockWidgetMovable
Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea
Menu
1
3
0
0
0
0
-
About
-
Survey
&About
QAction::AboutRole
&Load relation
Ctrl+O
&Save relation
Ctrl+S
&Quit
Ctrl+Q
QAction::QuitRole
&Check for new versions
&New relation
Ctrl+N
&Edit relation
Ctrl+E
&Unload relation
true
&Multi-line mode
Ctrl+L
true
Show history
table
cmdProduct
cmdDifference
cmdUnion
cmdIntersection
cmdJoin
cmdOuter
cmdOuterLeft
cmdOuterRight
cmdDivision
cmdSelection
cmdProjection
cmdRename
cmdArrow
cmdAbout
cmdSurvey
lstAttributes
lstRelations
cmdLoad
cmdSave
cmdNew
cmdEdit
cmdUnload
cmdNewSession
txtMultiQuery
cmdClearMultilineQuery
cmdExecuteMultiline
cmdOptimizeProgram
cmdUndoOptimizeProgram
cmdUndoOptimize
cmdClearHistory
txtQuery
cmdClearQuery
cmdExecute
lstHistory
cmdOptimize
cmdAbout
clicked()
MainWindow
showAbout()
95
444
79
495
cmdSurvey
clicked()
MainWindow
showSurvey()
78
484
99
495
cmdUnload
clicked()
MainWindow
unloadRelation()
516
491
636
495
cmdSave
clicked()
MainWindow
saveRelation()
631
423
636
495
cmdLoad
clicked()
MainWindow
loadRelation()
516
423
636
495
lstRelations
itemDoubleClicked(QListWidgetItem*)
MainWindow
printRelation(QListWidgetItem*)
633
328
636
495
lstRelations
itemClicked(QListWidgetItem*)
MainWindow
showAttributes(QListWidgetItem*)
633
384
510
495
actionAbout
triggered()
MainWindow
showAbout()
-1
-1
399
305
action_Load_relation
triggered()
MainWindow
loadRelation()
-1
-1
399
305
action_Save_relation
triggered()
MainWindow
saveRelation()
-1
-1
399
305
action_Quit
triggered()
MainWindow
close()
-1
-1
399
305
actionCheck_for_new_versions
triggered()
MainWindow
checkVersion()
-1
-1
399
305
cmdEdit
clicked()
MainWindow
editRelation()
631
457
399
305
actionEdit_relation
triggered()
MainWindow
editRelation()
-1
-1
399
305
cmdNew
clicked()
MainWindow
newRelation()
516
457
399
305
actionNew_relation
triggered()
MainWindow
newRelation()
-1
-1
399
305
actionUnload_relation
triggered()
MainWindow
unloadRelation()
-1
-1
399
305
actionMulti_line_mode
toggled(bool)
MainWindow
setMultiline(bool)
-1
-1
399
305
cmdClearMultilineQuery
clicked()
txtMultiQuery
clear()
394
262
221
286
cmdExecuteMultiline
clicked()
MainWindow
execute()
394
296
636
495
cmdClearQuery
clicked()
txtQuery
clear()
310
494
260
493
cmdClearHistory
clicked()
lstHistory
clear()
394
459
395
418
cmdOptimize
clicked()
MainWindow
optimize()
186
459
130
495
cmdUndoOptimize
clicked()
MainWindow
undoOptimize()
296
459
544
495
cmdExecute
clicked()
MainWindow
execute()
394
494
636
495
txtQuery
returnPressed()
MainWindow
execute()
260
493
636
495
lstHistory
itemDoubleClicked(QListWidgetItem*)
MainWindow
resumeHistory(QListWidgetItem*)
384
418
297
495
cmdProduct
clicked()
MainWindow
addProduct()
46
87
399
335
cmdDifference
clicked()
MainWindow
addDifference()
90
87
399
335
cmdUnion
clicked()
MainWindow
addUnion()
46
121
399
335
cmdIntersection
clicked()
MainWindow
addIntersection()
90
121
399
335
cmdDivision
clicked()
MainWindow
addDivision()
46
223
399
335
cmdOuter
clicked()
MainWindow
addOuter()
90
155
399
335
cmdOuterLeft
clicked()
MainWindow
addOLeft()
46
189
399
335
cmdOuterRight
clicked()
MainWindow
addORight()
90
189
399
335
cmdJoin
clicked()
MainWindow
addJoin()
46
155
399
335
cmdProjection
clicked()
MainWindow
addProjection()
90
257
399
335
cmdSelection
clicked()
MainWindow
addSelection()
46
257
399
335
cmdRename
clicked()
MainWindow
addRename()
46
291
399
335
cmdArrow
clicked()
MainWindow
addArrow()
90
291
399
335
cmdNewSession
clicked()
MainWindow
newSession()
631
491
636
396
actionShow_history
toggled(bool)
MainWindow
setHistoryShown(bool)
-1
-1
318
247
cmdOptimizeProgram
clicked()
MainWindow
optimizeProgram()
357
313
398
360
cmdUndoOptimizeProgram
clicked()
MainWindow
undoOptimizeProgram()
371
353
397
44
execute()
checkVersion()
showAbout()
showSurvey()
addProduct()
addDifference()
addUnion()
addIntersection()
addDivision()
addOLeft()
addORight()
addOuter()
addJoin()
addProjection()
addSelection()
addRename()
addArrow()
optimize()
undoOptimize()
loadRelation()
unloadRelation()
saveRelation()
insertTuple()
deleteTuple()
printRelation(QListWidgetItem*)
showAttributes(QListWidgetItem*)
loadQuery()
resumeHistory(QListWidgetItem*)
editRelation()
newRelation()
newSession()
saveSessionAs()
manageSessions()
setMultiline(bool)
setHistoryShown(bool)
optimizeProgram()
undoOptimizeProgram()
relational/relational_gui/guihandler.py 0000644 0001750 0001750 00000040716 12757112451 017751 0 ustar salvo salvo # Relational
# Copyright (C) 2008-2016 Salvo "LtWorf" Tomaselli
#
# Relational is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
import sys
from PyQt5 import QtCore, QtWidgets, QtGui
from relational import parser, optimizer, rtypes
from relational.maintenance import UserInterface
from relational_gui import about
from relational_gui import survey
from relational_gui import surveyForm
from relational_gui import maingui
class relForm(QtWidgets.QMainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.About = None
self.Survey = None
self.undo = None # UndoQueue for queries
self.undo_program = None
self.selectedRelation = None
self.ui = maingui.Ui_MainWindow()
self.user_interface = UserInterface()
self.history_current_line = None
# Creates the UI
self.ui.setupUi(self)
# Setting fonts for symbols
f = QtGui.QFont()
size = f.pointSize()
if sys.platform.startswith('win'):
winFont = 'Cambria'
symbolFont = 'Segoe UI Symbol'
increment = 4
else:
winFont = f.family()
symbolFont = f.family()
increment = 2
font = QtGui.QFont(winFont, size + increment)
sfont = QtGui.QFont(symbolFont)
self.ui.lstHistory.setFont(font)
self.ui.txtMultiQuery.setFont(font)
self.ui.txtQuery.setFont(font)
self.ui.groupOperators.setFont(font)
self.ui.cmdClearMultilineQuery.setFont(sfont)
self.ui.cmdClearQuery.setFont(sfont)
self.settings = QtCore.QSettings()
self._restore_settings()
# Shortcuts
shortcuts = (
(self.ui.lstRelations, QtGui.QKeySequence.Delete, self.unloadRelation),
(self.ui.lstRelations, 'Space', lambda: self.printRelation(self.ui.lstRelations.currentItem())),
(self.ui.txtQuery, QtGui.QKeySequence.MoveToNextLine, self.next_history),
(self.ui.txtQuery, QtGui.QKeySequence.MoveToPreviousLine, self.prev_history),
)
self.add_shortcuts(shortcuts)
def next_history(self):
if self.ui.lstHistory.currentRow() + 1 == self.ui.lstHistory.count() and self.history_current_line:
self.ui.txtQuery.setText(self.history_current_line)
self.history_current_line = None
elif self.history_current_line:
self.ui.lstHistory.setCurrentRow(self.ui.lstHistory.currentRow()+1)
self.resumeHistory(self.ui.lstHistory.currentItem())
def prev_history(self):
if self.history_current_line is None:
self.history_current_line = self.ui.txtQuery.text()
if self.ui.lstHistory.currentItem() is None:
return
if not self.ui.lstHistory.currentItem().text() != self.ui.txtQuery.text():
self.ui.lstHistory.setCurrentRow(self.ui.lstHistory.currentRow()-1)
elif self.ui.lstHistory.currentRow() > 0:
self.ui.lstHistory.setCurrentRow(self.ui.lstHistory.currentRow()-1)
self.resumeHistory(self.ui.lstHistory.currentItem())
def add_shortcuts(self, shortcuts):
for widget,shortcut,slot in shortcuts:
action = QtWidgets.QAction(self)
action.triggered.connect(slot)
action.setShortcut(QtGui.QKeySequence(shortcut))
# I couldn't find the constant
action.setShortcutContext(0)
widget.addAction(action)
def checkVersion(self):
from relational import maintenance
online = maintenance.check_latest_version()
if online is None:
r = QtWidgets.QApplication.translate("Form", "Network error")
elif online > version:
r = QtWidgets.QApplication.translate(
"Form", "New version available online: %s." % online)
elif online == version:
r = QtWidgets.QApplication.translate(
"Form", "Latest version installed.")
else:
r = QtWidgets.QApplication.translate(
"Form", "You are using an unstable version.")
QtWidgets.QMessageBox.information(
self, QtWidgets.QApplication.translate("Form", "Version"), r)
def setHistoryShown(self, history_shown):
self.history_shown = history_shown
self.settings.setValue('history_shown', history_shown)
self.ui.lstHistory.setVisible(history_shown)
self.ui.actionShow_history.setChecked(history_shown)
def setMultiline(self, multiline):
self.multiline = multiline
self.settings.setValue('multiline', multiline)
if multiline:
index = 0
else:
index = 1
self.ui.stackedWidget.setCurrentIndex(index)
self.ui.actionMulti_line_mode.setChecked(multiline)
def load_query(self, *index):
self.ui.txtQuery.setText(self.savedQ.itemData(index[0]).toString())
def undoOptimize(self):
'''Undoes the optimization on the query, popping one item from the undo list'''
if self.undo != None:
self.ui.txtQuery.setText(self.undo)
def undoOptimizeProgram(self):
if self.undo_program:
self.ui.txtMultiQuery.setPlainText(self.undo_program)
def optimizeProgram(self):
self.undo_program = self.ui.txtMultiQuery.toPlainText()
result = optimizer.optimize_program(
self.ui.txtMultiQuery.toPlainText(),
self.user_interface.relations
)
self.ui.txtMultiQuery.setPlainText(result)
def optimize(self):
'''Performs all the possible optimizations on the query'''
self.undo = self.ui.txtQuery.text() # Storing the query in undo list
res_rel,query = self.user_interface.split_query(self.ui.txtQuery.text(),None)
try:
trace = []
result = optimizer.optimize_all(
query,
self.user_interface.relations,
debug=trace
)
print('==== Optimization steps ====')
print(query)
print('\n'.join(trace))
print('========')
if res_rel:
result = '%s = %s' % (res_rel, result)
self.ui.txtQuery.setText(result)
except Exception as e:
self.error(e)
def resumeHistory(self, item):
if item is None:
return
itm = item.text()
self.ui.txtQuery.setText(itm)
def execute(self):
# Show the 'Processing' frame
self.ui.stackedWidget.setCurrentIndex(2)
QtCore.QCoreApplication.processEvents()
try:
'''Executes the query'''
if self.multiline:
query = self.ui.txtMultiQuery.toPlainText()
self.settings.setValue('multiline/query', query)
else:
query = self.ui.txtQuery.text()
if not query.strip():
return
try:
self.selectedRelation = self.user_interface.multi_execute(query)
except Exception as e:
return self.error(e)
finally:
self.updateRelations() # update the list
self.showRelation(self.selectedRelation)
if not self.multiline:
# Last in history
item = self.ui.lstHistory.item(self.ui.lstHistory.count() - 1)
if item is None or item.text() != query:
# Adds to history if it is not already the last
hitem = QtWidgets.QListWidgetItem(None, 0)
hitem.setText(query)
self.ui.lstHistory.addItem(hitem)
self.ui.lstHistory.setCurrentItem(hitem)
finally:
# Restore the normal frame
self.setMultiline(self.multiline)
def showRelation(self, rel):
'''Shows the selected relation into the table'''
self.ui.table.clear()
if rel == None: # No relation to show
self.ui.table.setColumnCount(1)
self.ui.table.headerItem().setText(0, "Empty relation")
return
self.ui.table.setColumnCount(len(rel.header))
# Set content
for i in rel.content:
item = QtWidgets.QTreeWidgetItem()
for j,k in enumerate(i):
item.setText(j, k)
self.ui.table.addTopLevelItem(item)
# Sets columns
for i, attr in enumerate(rel.header):
self.ui.table.headerItem().setText(i, attr)
self.ui.table.resizeColumnToContents(i)
def printRelation(self, item):
self.selectedRelation = self.user_interface.relations[item.text()]
self.showRelation(self.selectedRelation)
def showAttributes(self, item):
'''Shows the attributes of the selected relation'''
rel = item.text()
self.ui.lstAttributes.clear()
for j in self.user_interface.relations[rel].header:
self.ui.lstAttributes.addItem(j)
def updateRelations(self):
self.ui.lstRelations.clear()
for i in self.user_interface.relations:
if i != "__builtins__":
self.ui.lstRelations.addItem(i)
def saveRelation(self):
if not self.ui.lstRelations.selectedItems():
r = QtWidgets.QApplication.translate(
"Form", "Select a relation first."
)
QtWidgets.QMessageBox.information(
self, QtWidgets.QApplication.translate("Form", "Error"), r
)
return
filename = QtWidgets.QFileDialog.getSaveFileName(
self, QtWidgets.QApplication.translate("Form", "Save Relation"),
"",
QtWidgets.QApplication.translate("Form", "Relations (*.csv)")
)[0]
if (len(filename) == 0): # Returns if no file was selected
return
relname = self.ui.lstRelations.selectedItems()[0].text()
self.user_interface.relations[relname].save(filename)
def unloadRelation(self):
for i in self.ui.lstRelations.selectedItems():
del self.user_interface.relations[i.text()]
self.updateRelations()
def newSession(self):
self.user_interface.session_reset()
self.updateRelations()
def editRelation(self):
from relational_gui import creator
for i in self.ui.lstRelations.selectedItems():
result = creator.edit_relation(
self.user_interface.get_relation(i.text())
)
if result != None:
self.user_interface.set_relation(i.text(), result)
self.updateRelations()
def error(self, exception):
print (exception)
QtWidgets.QMessageBox.information(
None, QtWidgets.QApplication.translate("Form", "Error"),
str(exception)
)
def promptRelationName(self):
while True:
res = QtWidgets.QInputDialog.getText(
self,
QtWidgets.QApplication.translate("Form", "New relation"),
QtWidgets.QApplication.translate(
"Form", "Insert the name for the new relation"),
QtWidgets.QLineEdit.Normal, ''
)
if res[1] == False: # or len(res[0]) == 0:
return None
name = res[0]
if not rtypes.is_valid_relation_name(name):
r = QtWidgets.QApplication.translate(
"Form", str(
"Wrong name for destination relation: %s." % name)
)
QtWidgets.QMessageBox.information(
self, QtWidgets.QApplication.translate("Form", "Error"), r
)
continue
return name
def newRelation(self):
from relational_gui import creator
result = creator.edit_relation()
if result == None:
return
name = self.promptRelationName()
try:
self.user_interface.relations[name] = result
self.updateRelations()
except Exception as e:
self.error(e)
def closeEvent(self, event):
self.save_settings()
event.accept()
def save_settings(self):
self.settings.setValue('maingui/geometry', self.saveGeometry())
self.settings.setValue('maingui/windowState', self.saveState())
self.settings.setValue('maingui/splitter', self.ui.splitter.saveState())
self.settings.setValue('maingui/relations', self.user_interface.session_dump())
def _restore_settings(self):
self.user_interface.session_restore(self.settings.value('maingui/relations'))
self.updateRelations()
self.setMultiline(self.settings.value('multiline', 'false') == 'true')
self.setHistoryShown(self.settings.value('history_shown', 'true') == 'true')
self.ui.txtMultiQuery.setPlainText(
self.settings.value('multiline/query', ''))
try:
self.restoreGeometry(self.settings.value('maingui/geometry'))
self.restoreState(self.settings.value('maingui/windowState'))
self.ui.splitter.restoreState(self.settings.value('maingui/splitter'))
except:
pass
def showSurvey(self):
if self.Survey == None:
self.Survey = surveyForm.surveyForm()
ui = survey.Ui_Form()
self.Survey.setUi(ui)
ui.setupUi(self.Survey)
self.Survey.setDefaultValues()
self.Survey.show()
def showAbout(self):
if self.About == None:
self.About = QtWidgets.QDialog()
ui = about.Ui_Dialog()
ui.setupUi(self.About)
self.About.show()
def loadRelation(self, filenames=None):
'''Loads a relation. Without parameters it will ask the user which relation to load,
otherwise it will load filename, giving it name.
It shouldn't be called giving filename but not giving name.'''
# Asking for file to load
if not filenames:
f = QtWidgets.QFileDialog.getOpenFileNames(
self,
QtWidgets.QApplication.translate("Form", "Load Relation"),
"",
QtWidgets.QApplication.translate(
"Form",
"Relations (*.csv);;Text Files (*.txt);;All Files (*)"
)
)
filenames = f[0]
for f in filenames:
# Default relation's name
name = self.user_interface.suggest_name(f)
if name is None:
name = self.promptRelationName()
if name is None:
continue
try:
self.user_interface.load(f, name)
except Exception as e:
self.error(e)
continue
self.updateRelations()
def addProduct(self):
self.addSymbolInQuery(parser.PRODUCT)
def addDifference(self):
self.addSymbolInQuery(parser.DIFFERENCE)
def addUnion(self):
self.addSymbolInQuery(parser.UNION)
def addIntersection(self):
self.addSymbolInQuery(parser.INTERSECTION)
def addDivision(self):
self.addSymbolInQuery(parser.DIVISION)
def addOLeft(self):
self.addSymbolInQuery(parser.JOIN_LEFT)
def addJoin(self):
self.addSymbolInQuery(parser.JOIN)
def addORight(self):
self.addSymbolInQuery(parser.JOIN_RIGHT)
def addOuter(self):
self.addSymbolInQuery(parser.JOIN_FULL)
def addProjection(self):
self.addSymbolInQuery(parser.PROJECTION)
def addSelection(self):
self.addSymbolInQuery(parser.SELECTION)
def addRename(self):
self.addSymbolInQuery(parser.RENAME)
def addArrow(self):
self.addSymbolInQuery(parser.ARROW)
def addSymbolInQuery(self, symbol):
if self.multiline:
self.ui.txtMultiQuery.insertPlainText(symbol)
self.ui.txtMultiQuery.setFocus()
else:
self.ui.txtQuery.insert(symbol)
self.ui.txtQuery.setFocus()
relational/relational_gui/survey.ui 0000644 0001750 0001750 00000023701 12757112451 017144 0 ustar salvo salvo
Form
0
0
422
313
Survey
-
-
-
Country
txtCountry
-
-
School
txtSchool
-
-
Age
txtAge
-
-
How did you find relational
txtFind
-
-
System
txtSystem
-
Comments
txtComments
-
true
-
Email (only if you want a reply)
txtEmail
-
-
-
Qt::Horizontal
40
20
-
Cancel
-
Clear
-
Send
true
txtSystem
txtCountry
txtSchool
txtAge
txtFind
txtEmail
txtComments
cmdSend
cmdClear
cmdCancel
cmdCancel
clicked()
Form
close()
202
384
180
319
cmdClear
clicked()
txtComments
clear()
265
384
291
248
cmdClear
clicked()
txtFind
clear()
265
384
400
151
cmdClear
clicked()
txtAge
clear()
265
384
257
123
cmdClear
clicked()
txtSchool
clear()
265
384
317
87
cmdClear
clicked()
txtCountry
clear()
265
384
400
70
cmdClear
clicked()
txtSystem
clear()
265
384
400
39
txtSystem
returnPressed()
txtCountry
setFocus()
213
22
224
52
txtCountry
returnPressed()
txtSchool
setFocus()
268
54
276
89
txtSchool
returnPressed()
txtAge
setFocus()
355
85
358
118
txtAge
returnPressed()
txtFind
setFocus()
375
123
400
151
cmdSend
clicked()
Form
send()
327
384
396
320
cmdClear
clicked()
txtEmail
clear()
233
367
242
168
txtFind
returnPressed()
txtEmail
setFocus()
302
140
302
167
txtEmail
returnPressed()
txtComments
setFocus()
302
167
302
255
send()
relational/relational_gui/creator.py 0000644 0001750 0001750 00000011252 12757112451 017257 0 ustar salvo salvo # Relational
# Copyright (C) 2008-2015 Salvo "LtWorf" Tomaselli
#
# Relational is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
from PyQt5 import QtGui, QtWidgets
from relational_gui import rel_edit
from relational import relation
class creatorForm(QtWidgets.QDialog):
def __init__(self, rel=None):
QtWidgets.QDialog.__init__(self)
self.setSizeGripEnabled(True)
self.result_relation = None
self.rel = rel
def setUi(self, ui):
self.ui = ui
self.table = self.ui.table
if self.rel == None:
self.setup_empty()
else:
self.setup_relation(self.rel)
def setup_relation(self, rel):
self.table.insertRow(0)
for i in rel.header:
item = QtWidgets.QTableWidgetItem()
item.setText(i)
self.table.insertColumn(self.table.columnCount())
self.table.setItem(0, self.table.columnCount() - 1, item)
for i in rel.content:
self.table.insertRow(self.table.rowCount())
for j in range(len(i)):
item = QtWidgets.QTableWidgetItem()
item.setText(i[j])
self.table.setItem(self.table.rowCount() - 1, j, item)
pass
def setup_empty(self):
self.table.insertColumn(0)
self.table.insertColumn(0)
self.table.insertRow(0)
self.table.insertRow(0)
i00 = QtWidgets.QTableWidgetItem()
i01 = QtWidgets.QTableWidgetItem()
i10 = QtWidgets.QTableWidgetItem()
i11 = QtWidgets.QTableWidgetItem()
i00.setText('Field name 1')
i01.setText('Field name 2')
i10.setText('Value 1')
i11.setText('Value 2')
self.table.setItem(0, 0, i00)
self.table.setItem(0, 1, i01)
self.table.setItem(1, 0, i10)
self.table.setItem(1, 1, i11)
def create_relation(self):
h = (self.table.item(0, i).text()
for i in range(self.table.columnCount()))
try:
header = relation.header(h)
except Exception as e:
QtWidgets.QMessageBox.information(None, QtWidgets.QApplication.translate("Form", "Error"), "%s\n%s" % (
QtWidgets.QApplication.translate("Form", "Header error!"), e.__str__()))
return None
r = relation.relation()
r.header = header
for i in range(1, self.table.rowCount()):
hlist = []
for j in range(self.table.columnCount()):
try:
hlist.append(self.table.item(i, j).text())
except:
QtWidgets.QMessageBox.information(None, QtWidgets.QApplication.translate(
"Form", "Error"), QtWidgets.QApplication.translate("Form", "Unset value in %d,%d!" % (i + 1, j + 1)))
return None
r.insert(hlist)
return r
def accept(self):
self.result_relation = self.create_relation()
# Doesn't close the window in case of errors
if self.result_relation != None:
QtWidgets.QDialog.accept(self)
def reject(self):
self.result_relation = None
QtWidgets.QDialog.reject(self)
def addColumn(self):
self.table.insertColumn(self.table.columnCount())
def addRow(self):
self.table.insertRow(1)
def deleteColumn(self):
if self.table.columnCount() > 1:
self.table.removeColumn(self.table.currentColumn())
def deleteRow(self):
if self.table.rowCount() > 2:
self.table.removeRow(self.table.currentRow())
def edit_relation(rel=None):
'''Opens the editor for the given relation and returns a _new_ relation
containing the new relation.
If the user cancels, it returns None'''
ui = rel_edit.Ui_Dialog()
Form = creatorForm(rel)
ui.setupUi(Form)
Form.setUi(ui)
Form.exec_()
return Form.result_relation
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
r = relation.relation(
"/home/salvo/dev/relational/trunk/samples/people.csv")
print (edit_relation(r))
relational/relational_gui/rel_edit.ui 0000644 0001750 0001750 00000010325 12757112451 017374 0 ustar salvo salvo
Dialog
0
0
594
444
Relation editor
-
-
Edit
-
Add tuple
-
Remove tuple
-
Add column
-
Remove column
-
-
Remember that new relations and modified relations are not automatically saved
-
Qt::Horizontal
QDialogButtonBox::Cancel|QDialogButtonBox::Ok
buttonBox
accepted()
Dialog
accept()
328
354
157
274
buttonBox
rejected()
Dialog
reject()
396
360
286
274
cmdAddColumn
clicked()
Dialog
addColumn()
71
95
188
100
cmdRemoveColumn
clicked()
Dialog
deleteColumn()
126
121
202
129
cmdAddTuple
clicked()
Dialog
addRow()
124
155
197
158
cmdRemoveTuple
clicked()
Dialog
deleteRow()
122
181
182
193
addColumn()
addRow()
deleteColumn()
deleteRow()
relational/relational_gui/resources/ 0000755 0001750 0001750 00000000000 12757112451 017257 5 ustar salvo salvo relational/relational_gui/resources/relational.png 0000644 0001750 0001750 00000100114 12757112451 022114 0 ustar salvo salvo PNG
IHDR \rf sRGB bKGD pHYs n nޱ tIME
7V IDATxye>|kwWut:C"L3?.A,**8#,㰈0.?>ܹ@DQ$,B0Đ;I{~|O=U՝ {^s>&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h&h<Y._K'v ޙя~)N@TrLfp`IdtNg`$I/ISd^,R-˙RiNIC|~TKX8t81>cjjJ4lݺկDFm[6ͶBYnNgX,0ͰX,0L00LdF#F#z=$I^$I$ :}-(ːebrb|>|>B y)"˱[6E*BT*}ry J$i s\?яzK.c= OKWX3
jպji2LNv6
V6
6
ffF}5C~VʲRB|>\.L&t:T*T*d2D"T*x