Merge branch 'master' of github.com:ltworf/relational

master
Salvo 'LtWorf' Tomaselli 2013-06-29 15:40:03 +07:00
commit 68b60b7b07
3 changed files with 82 additions and 215 deletions

@ -19,9 +19,17 @@
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>
from relational import relation, parser, optimizer
from relational_readline.termcolor import colored
import os
from sys import exit
from relational import relation, parser, optimizer
from xtermcolor import colorize
COLOR_RED = 0xff0000
COLOR_GREEN = 0x00ff00
COLOR_MAGENTA = 0xff00ff
COLOR_CYAN = 0x00ffff
print relation
@ -84,37 +92,39 @@ def execute_tests():
ex_good+=1
else:
ex_bad+=1
print "\n\033[36;1mResume of the results\033[0m"
print colorize("Resume of the results",COLOR_CYAN)
print "\n\033[35;1mQuery tests\033[0m"
print colorize("Query tests",COLOR_MAGENTA)
print "Total test count: %d" % q_tot
print "Passed tests: %d" % q_good
if q_bad>0:
print "\033[31;1mFailed tests count: %d\033[0m" % q_bad
print colorize("Failed tests count: %d" % q_bad,COLOR_RED)
print "\n\033[35;1mPython tests\033[0m"
print colorize("Python tests",COLOR_MAGENTA)
print "Total test count: %d" % py_tot
print "Passed tests: %d" % py_good
if py_bad>0:
print "\033[31;1mFailed tests count: %d\033[0m" % py_bad
print colorize("Failed tests count: %d" % py_bad,COLOR_RED)
print "\n\033[35;1mExecute Python tests\033[0m"
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 "\033[31;1mFailed tests count: %d\033[0m" % ex_bad
print colorize("Failed tests count: %d" % ex_bad,COLOR_RED)
print "\n\033[36;1mTotal results\033[0m"
print colorize("Total results",COLOR_CYAN)
if q_bad+py_bad+ex_bad==0:
print "\033[32;1mNo failed tests\033[0m"
print colorize("No failed tests",COLOR_GREEN)
return 0
else:
print "\033[31;1mThere are %d failed tests\033[0m" % (py_bad+q_bad+ex_bad)
print colorize("There are %d failed tests" % (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: \033[35;1m%s\033[0m" % testname
print "Running python test: " + colorize(testname,COLOR_MAGENTA)
glob=rels.copy()
exp_result={}
@ -139,20 +149,20 @@ def run_exec_test(testname):
fields_ok = fields_ok and glob[i]==exp_result[i]
if fields_ok:
print colored('Test passed','green')
print colorize('Test passed',COLOR_GREEN)
return True
except:
pass
print colored('ERROR','red')
print colored('=====================================','red')
print colorize('ERROR',COLOR_RED)
print colorize('=====================================',COLOR_RED)
print "Expected %s" % exp_result
#print "Got %s" % result
print colored('=====================================','red')
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: " + colored (testname,'magenta')
print "Running expression python test: " + colorize (testname,COLOR_MAGENTA)
try:
@ -163,16 +173,16 @@ def run_py_test(testname):
exp_result=eval(expr,rels) #Evaluating the expression
if result==exp_result:
print colored('Test passed','green')
print colorize('Test passed',COLOR_GREEN)
return True
except:
pass
print colored('ERROR','red')
print colored('=====================================','red')
print colorize('ERROR',COLOR_RED)
print colorize('=====================================',COLOR_RED)
print "Expected %s" % exp_result
print "Got %s" % result
print colored('=====================================','red')
print colorize('=====================================',COLOR_RED)
return False
def run_test(testname):
@ -182,7 +192,7 @@ def run_test(testname):
testname.result
The query will be executed both unoptimized and
optimized'''
print "Running test: "+ colored(testname,'magenta')
print "Running test: "+ colorize(testname,COLOR_MAGENTA)
query=None;expr=None;o_query=None;o_expr=None
result_rel=None
@ -206,24 +216,24 @@ def run_test(testname):
c_result=eval(c_expr,rels)
if (o_result==result_rel) and (result==result_rel) and (c_result==result_rel):
print colored('Test passed','green')
print colorize('Test passed',COLOR_GREEN)
return True
except Exception as inst:
print inst
pass
print colored('ERROR','red')
print colorize('ERROR',COLOR_RED)
print "Query: %s -> %s" % (query,expr)
print "Optimized query: %s -> %s" % (o_query,o_expr)
print colored('=====================================','red')
print "\033[33;1mExpected result\033[0m"
print colorize('=====================================',COLOR_RED)
print colorize("Expected result",COLOR_GREEN)
print result_rel
print "\033[33;1mResult\033[0m"
print colorize("Result",COLOR_RED)
print result
print "\033[33;1mOptimized result\033[0m"
print colorize("Optimized result",COLOR_RED)
print o_result
print "\033[33;1moptimized result match\033[0m", result_rel==o_result
print "\033[33;1mresult match \033[0m", result==result_rel
print colored('=====================================','red')
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
@ -231,4 +241,4 @@ if __name__ == '__main__':
print "-> Starting testsuite for relational"
load_relations()
print "-> Starting tests"
execute_tests()
exit(execute_tests())

@ -26,8 +26,10 @@ import os
import sys
from relational import relation, parser, rtypes
from termcolor import colored
from xtermcolor import colorize
PROMPT_COLOR = 0xffff00
ERROR_COLOR = 0xff0000
class SimpleCompleter(object):
'''Handles completion'''
@ -97,7 +99,7 @@ completer=SimpleCompleter(['SURVEY','LIST','LOAD ','UNLOAD ','HELP ','QUIT','SAV
def load_relation(filename,defname=None):
if not os.path.isfile(filename):
print >> sys.stderr, colored("%s is not a file" % filename,'red')
print >> sys.stderr, colorize("%s is not a file" % filename,ERROR_COLOR)
return None
f=filename.split('/')
@ -107,16 +109,16 @@ def load_relation(filename,defname=None):
defname=defname[:-4]
if not rtypes.is_valid_relation_name(defname):
print >> sys.stderr, colored("%s is not a valid relation name" % defname,'red')
print >> sys.stderr, colorize("%s is not a valid relation name" % defname,ERROR_COLOR)
return
try:
relations[defname]=relation.relation(filename)
completer.add_completion(defname)
print colored("Loaded relation %s"% defname,'green',attrs=['bold'])
print colorize("Loaded relation %s"% defname,0x00ff00)
return defname
except Exception, e:
print >>sys.stderr,colored(e,'red')
print >>sys.stderr,colorize(e,ERROR_COLOR)
return None
def survey():
@ -182,7 +184,7 @@ def exec_line(command):
elif command.startswith('LOAD '): #Loads a relation
pars=command.split(' ')
if len(pars)==1:
print colored("Missing parameter",'red')
print colorize("Missing parameter",ERROR_COLOR)
return
filename=pars[1]
@ -195,55 +197,56 @@ def exec_line(command):
elif command.startswith('UNLOAD '):
pars=command.split(' ')
if len(pars)<2:
print colored("Missing parameter",'red')
print colorize("Missing parameter",ERROR_COLOR)
return
if pars[1] in relations:
del relations[pars[1]]
completer.remove_completion(pars[1])
else:
print colored("No such relation %s" % pars[1],'red')
print colorize("No such relation %s" % pars[1],ERROR_COLOR)
pass
elif command.startswith('SAVE '):
pars=command.split(' ')
if len(pars)!=3:
print colored("Missing parameter",'red')
print colorize("Missing parameter",ERROR_COLOR)
return
filename=pars[1]
defname=pars[2]
if defname not in relations:
print colored("No such relation %s" % defname,'red')
print colorize("No such relation %s" % defname,ERROR_COLOR)
return
try:
relations[defname].save(filename)
except Exception,e:
print colored(e,'red')
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( '_PRODUCT' , '*')
query=query.replace( '_UNION' , '')
query=query.replace( '_INTERSECTION' , '')
query=query.replace( '_DIFFERENCE' , '-')
query=query.replace( '_JOIN' , 'ᐅᐊ')
query=query.replace( '_LJOIN' , 'ᐅLEFTᐊ')
query=query.replace( '_RJOIN' , 'ᐅRIGHTᐊ')
query=query.replace( '_FJOIN' , 'ᐅFULLᐊ')
query=query.replace( '_PROJECTION' , 'π')
query=query.replace( '_RENAME_TO' , '')
query=query.replace( '_SELECTION' , 'σ')
query=query.replace( '_RENAME' , 'ρ')
query=query.replace( '_DIVISION' , '÷')
query=query.replace(u'_PRODUCT' , u'*')
query=query.replace(u'_UNION' , u'')
query=query.replace(u'_INTERSECTION' , u'')
query=query.replace(u'_DIFFERENCE' , u'-')
query=query.replace(u'_JOIN' , u'ᐅᐊ')
query=query.replace(u'_LJOIN' , u'ᐅLEFTᐊ')
query=query.replace(u'_RJOIN' , u'ᐅRIGHTᐊ')
query=query.replace(u'_FJOIN' , u'ᐅFULLᐊ')
query=query.replace(u'_PROJECTION' , u'π')
query=query.replace(u'_RENAME_TO' , u'')
query=query.replace(u'_SELECTION' , u'σ')
query=query.replace(u'_RENAME' , u'ρ')
query=query.replace(u'_DIVISION' , u'÷')
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
'''
command=unicode(command,'utf-8')
#If it terminates with ; doesn't print the result
if command.endswith(';'):
@ -252,6 +255,8 @@ def exec_query(command):
else:
printrel=True
#Performs replacements for weird operators
command=replacements(command)
@ -265,12 +270,13 @@ def exec_query(command):
relname='last_'
query=command
query=unicode(query,'utf-8')
#Execute query
try:
pyquery=parser.parse(query)
result=eval(pyquery,relations)
print colored("-> query: %s" % pyquery,'green')
print colorize("-> query: %s" % pyquery.encode('utf-8'),0x00ff00)
if printrel:
print
@ -280,11 +286,11 @@ def exec_query(command):
completer.add_completion(relname)
except Exception, e:
print colored(e,'red')
print colorize(e,ERROR_COLOR)
def main(files=[]):
print colored('> ','blue') + "; Type HELP to get the HELP"
print colored('> ','blue') + "; Completion is activated using the tab (if supported by the terminal)"
print colorize('> ',PROMPT_COLOR) + "; Type HELP to get the HELP"
print colorize('> ',PROMPT_COLOR) + "; Completion is activated using the tab (if supported by the terminal)"
for i in files:
load_relation(i)
@ -298,9 +304,12 @@ def main(files=[]):
while True:
try:
line = raw_input(colored('> ','blue'))
line = raw_input(colorize('> ',PROMPT_COLOR))
if isinstance(line,str) and len(line)>0:
exec_line(line)
except KeyboardInterrupt:
print
continue
except EOFError:
print
sys.exit(0)

@ -1,152 +0,0 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2009 Konstantin Lepa <konstantin.lepa@gmail.com>.
#
# This file is part of termcolor.
#
# termcolor 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, or (at your option) any later
# version.
#
# termcolor 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 termcolor. If not, see <http://www.gnu.org/licenses/>.
"""ANSII Color formatting for output in terminal."""
import os
__ALL__ = [ 'colored' ]
ATTRIBUTES = dict(
zip([
'bold',
'dark',
'',
'underline',
'blink',
'',
'reverse',
'concealed'
],
range(1, 9)
)
)
del ATTRIBUTES['']
HIGHLIGHTS = dict(
zip([
'on_grey',
'on_red',
'on_green',
'on_yellow',
'on_blue',
'on_magenta',
'on_cyan',
'on_white'
],
range(40, 48)
)
)
COLORS = dict(
zip([
'grey',
'red',
'green',
'yellow',
'blue',
'magenta',
'cyan',
'white',
],
range(30, 38)
)
)
RESET = '\033[0m'
def colored(text, color=None, on_color=None, attrs=['bold']):
"""Colorize text.
Available text colors:
red, green, yellow, blue, magenta, cyan, white.
Available text highlights:
on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white.
Available attributes:
bold, dark, underline, blink, reverse, concealed.
Example:
colored('Hello, World!', 'red', 'on_grey', ['blue', 'blink'])
colored('Hello, World!', 'green')
"""
if os.getenv('ANSI_COLORS_DISABLED') is None:
fmt_str = '\033[%dm%s'
if color is not None:
text = fmt_str % (COLORS[color], text)
if on_color is not None:
text = fmt_str % (HIGHLIGHTS[on_color], text)
if attrs is not None:
for attr in attrs:
text = fmt_str % (ATTRIBUTES[attr], text)
text += RESET
return text
if __name__ == '__main__':
print 'Current terminal type: ', os.getenv('TERM')
print 'Test basic colors:'
print colored('Grey color', 'grey')
print colored('Red color', 'red')
print colored('Green color', 'green')
print colored('Yellow color', 'yellow')
print colored('Blue color', 'blue')
print colored('Magenta color', 'magenta')
print colored('Cyan color', 'cyan')
print colored('White color', 'white')
print '-' * 78
print 'Test highlights:'
print colored('On grey color', on_color='on_grey')
print colored('On red color', on_color='on_red')
print colored('On green color', on_color='on_green')
print colored('On yellow color', on_color='on_yellow')
print colored('On blue color', on_color='on_blue')
print colored('On magenta color', on_color='on_magenta')
print colored('On cyan color', on_color='on_cyan')
print colored('On white color', color='grey', on_color='on_white')
print '-' * 78
print 'Test attributes:'
print colored('Bold grey color', 'grey', attrs=['bold'])
print colored('Dark red color', 'red', attrs=['dark'])
print colored('Underline green color', 'green', attrs=['underline'])
print colored('Blink yellow color', 'yellow', attrs=['blink'])
print colored('Reversed blue color', 'blue', attrs=['reverse'])
print colored('Concealed Magenta color', 'magenta', attrs=['concealed'])
print colored('Bold underline reverse cyan color', 'cyan',
attrs=['bold', 'underline', 'reverse'])
print colored('Dark blink concealed white color', 'white',
attrs=['dark', 'blink', 'concealed'])
print '-' * 78
print 'Test mixing:'
print colored('Underline red on grey color', 'red', 'on_grey',
['underline'])
print colored('Reversed green on red color', 'green', 'on_red', ['reverse'])