relational/0000775000175000017500000000000014647215100012244 5ustar salvosalvorelational/complexity0000664000175000017500000001120314647215100014361 0ustar salvosalvo 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://codeberg.ogr/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/CREDITS0000664000175000017500000000027614647215100013271 0ustar salvosalvoOri 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_gui/0000775000175000017500000000000014647215100015242 5ustar salvosalvorelational/relational_gui/__pycache__/0000775000175000017500000000000014647215100017452 5ustar salvosalvorelational/relational_gui/maingui.ui0000664000175000017500000012601014647215100017232 0ustar salvosalvo Salvo 'LtWorf' Tomaselli MainWindow 0 0 637 496 Relational 0 0 0 0 0 Qt::Vertical 0 0 true QAbstractItemView::NoSelection false Empty relation 0 1 0 0 0 0 0 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 0 Qt::Vertical QSizePolicy::MinimumExpanding 20 0 1 Optimize Ctrl+Shift+O Undo optimize Ctrl+Shift+U Clear history Ctrl+Shift+C 0 Ctrl+Shift+Backspace true Execute Ctrl+Return true true Processing… 0 0 637 27 &File Help Relations Setti&ngs QDockWidget::DockWidgetMovable Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea Operators 1 0 QLayout::SetMinimumSize 0 0 0 0 QFrame::NoFrame QFrame::Plain 0 0 0 0 0 0 3 Left outer join Alt+J, Alt+L true Alt+A true Union Alt+U true Difference - true Rename ρ Alt+R true Division ÷ Alt+D true Full outer join Alt+J, Alt+O true Intersection Alt+I true Product * true Right outer join Alt+J, Alt+R true Projection π Alt+P true Selection σ Alt+S true 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 QFrame::NoFrame QFrame::Plain QDockWidget::DockWidgetMovable Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea Re&lations 2 0 0 0 0 QFrame::NoFrame true 2 0 2 3 New Edit Load Save Unload all Unload 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/resources/0000775000175000017500000000000014647215100017254 5ustar salvosalvorelational/relational_gui/resources/relational.png0000664000175000017500000010011414647215100022111 0ustar salvosalvoPNG  IHDR\rfsRGBbKGD pHYsnnޱ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@TrLf p `IdtNg`$I/ISd^,R-˙RiNIC|~TKX8t81>cjjJ4lݺկDFm[6ͶB׷YnNgX,0ͰX,0L00LdF#F#z=  $I^$I$ :}-(ːebrb|>|>B y)"˱[6E*BT*}ry J$i s\?яzK.c=OKWX3 jպji2LNv6 V6 6 ffF}5 C~VʲR B|>\.L&t:T*T*d2D"T*xVysڼBVSdYrcECS.Q*P,Bd2HRbD"r$""h>K<ߞvX,e+~3PiԕGy_~9+htdZmn~\.rIyyRv>T*5Nd2?T*h>C=|s×ej`n8㳟}||R~xOSS)= {liw)*PVQR%)gRPuT*!NcrrCCCE?dQ~vz50+k}nrkmmEss$Rzs-iZ >)kשWg  ԃg>јH$022">|X:x v'l|g>|k_f z!UW]ul7ӹ rkk Ţxh)l@'PRj LTCB DY,d066&H{Kt>#<iUMn&w}L'UnkkZ[[ŢE|j^DP/78dLBpA>G&|A^:??|}6>@6M1!WakC-KǣPcV(N1::7|G=66vC=K 6P(XppBGUɏ6!80gc4$j0x/(HӈbÇz+322}{s TKN涶6tttȝRss3,A;S€zBxzK߫N浪1&X,&KW^||r^z)}Q=ȃ>(رnq˂ h",YMMM0 TVSz<\#[}=.^gږfV1T{cf099Catt+O=ܹu8/ >Յ%K:NPR+n=ʩfޮCSMaf $P{|݄3I0B4fF111Gbjj󷾝fSl9/^,/[LjhhPj]|L|sP9-ΦXhgI`6"d2F@6]w-pÆ ؾ}fNe?n47 WX!577W*)L3XgS771LLsy,Uu###!O|/[o "ԣ 7rn씻 d28Ww2= .`s fdgRPG\DcccL&O~U (7prB[[[Ӓ%Kb vUŬϤw"1njAX@-q\rYJ,0<<ј^?;vm;}NVڊ^̮6>\겫^f[jR͐T.՞J=V4P( LbttTr7 ,]w,rOk,Yn8κ`{=ɿ' T+ i=Qf2]XPWeDgF4ITB&ah`rr`{{f޾^sGG[`9%2?]ՠx!IVsY=aI!U "FFF䡡!}wR^@NT;rñkŊ3 ,-Z7͏K;Kw;pwve˖ɫWXCZ j*j)ՉZ":T5EMA&SڵM)UTK`jf\,/ܴi[ny??K/ix宻½ދaҥXbt:ÕH6r1PjB8YV!%\)jT j)hPV$ID.f8kÆ o'.iR`6'ZZZf) խԳUQ-x= ^!-ylvE"㗬R)ɃR& tO~%?666.BR0dB=>x=L؀Ov>x^c1 籼W iА<>>~kYjO[Ne@SRz {j=/+QZϣVB}5jS/( wf=]* ='x┩ RG,>I |>|>_8a;^R5,tL1s=1XmtW=y*"5t+R3}cTB< zYw\z饚SN|'QzD*\ǃ jfyx.A5ROTINp8,bnzo[$I^vz,vWLӗ?tϓf=y=_o=[{s\o' HRD"(m馛N2*`0|h4d2UuyF橔Ěn;5=ds#W˶.*9k)\K0M7tIջSOfI2 MXM;f_*gWU~(4izgfr_TpJg}g4f4X,Z3Rz3l3gcf|-nd)!J!˵zh4`0T@^2 L&Csy7èDy2 L8%4Yٕ&`Bz6Nr,KP*dt2IM8nc*S9GksP(0}v\r]r; +eY)Q|J%b1\W|^g6d W>F{^yO$I0W^yH.]|gA$ [τxZO4" ][DNDYa0W_-?#o.b,ndRd=^?{kّyog5o)?_$RI\L&_VBVbtPDf6.ŝ Wq.|ƝT#e_MclvNW`  I$"fQ]uNр,ovqbXt$Il6$)X,wр)MKhF@SYFu^^$i:uȅ˲,R)$I2)^"8E?Ȣ&ӕT&rt"ٟ@(R Pr|clJhr"~W~R|ݎD"r,CZ OJJa+Zb`D'`|h2W^W~&dhDOOrS~E|69J Ɖbz v~?",3x#Qh!&tnܓIF#СCH,td2!^͛72L]\.{B$4440@'!v`Uk_Oi7Nϟ-1OlbAOOxLgׅyeVXf.@&ݻQ*RAdҌH4ݴM~'o6aXza2pDъs,M:`ٲe/8z(%mzR|5vڅnALNN"JU`AIJM$,*?D>2fLy~rL?oFIC r9޽-Bgg'"Y"짘7ԓW4#%xW]% X,|> r/Z F{էp8asSS4PRV2T۳g0֮] Ʉh4\.WC\T. }J+40?>'wOhn޽{SR~1hH$_4777Ztؿ?yfAD"ii|}!6f|My ;y} I/c``&IQvN~466`dddÇ9rľi&d2x.hѣ8묳 ŐH$秡>>[F@2.S>'`XvDc9rDU^bÇhѢx3u?pm!N3T˧C@L&Bۍr|>Gbttmmmhnne Ttz@bQl+U3ZRBI}&Jaj'%34sffQ,vac~%`} gy&Jۇ/fNGOO}Qlݺ\N5֓eF,ft2O d2}a`` ,@0C"`-b~G""P\.TSj^T|QψWz0V8;dY0<< ? < IDAT3NL&a6aY_OvcѢEB`E- x<Xf qlذ`PUQD#p8`_+ÈD"zX`vkK2dx80z}~k=7#ZFaA{\+{wb"wm6JFGG100!d $p؟W|(`||/2Gq#F@ôi&w}lO\.LNN"Hjb0HT*arrp\@0ACCJ$rj@$b@D )S1(T[*^G1W2W jF6 FLGA__&&&XYX,"J!J_Q|p=`B$qg_C^S(Bww7"nvd2~e촆"%d z8^ID@9-$ߓqPRr5o[ AE- wZ8*)y5KwJǧ|^|> bppHǟW-OL&Q(*dʇv~;(mjjbH{ߚ @(ֆ>q]wnC2"&ra||xVfy׏СCC[[ZZZp8X V YjV>:K[ּW8J~VRt?^TZJ&o?22!D"d2TV ~r̒. Nsޟns$IYg`!*!… Q*yfߎ;TJW*ÁbzY?onR>89F?9J%rQdB핾*M-}?j dW=.KDo/*=|TǏFH$t=U8{V k6(0~?Yp8t:Q,$84=Ug}jm˵BjO^1f3KΥi ##2O/v|#D!x^ d6%om6nVJ%Fgg'~?$"4Q( ,+v;/>O_jӪ$Iz(JbrҊt:<&''YQCC^PX,"!#MEZd*^mIjb`&| F HJXI7J1Š3xXh4VT^/n7{tK~:]wp碳>,cttCm( K @Fӟя~?*by%OЀqfUX<䔙%@@DH$0<<  P(T :`jW3 s6Z)R y(4bz$I( fFݛz*wߋ}"'/I4<^/Jo2Dp 7`ʕ8쳱`FӃ|>P(Hb1ᘶfXr% z=f3N'z|czq011bQ21ojP(0tِݨ'jנ{.Y TkDh_@)VKg"Ri&EL& =DgQy.?~q`0Q ~f?x[lgx<X,@dM L:tM{ڽ{NC `e˅G})R'dP{ ãT6P` t:]AM, kViؕޗZ鬞]VwYLל}aś8DRcxzjjJ{p\xXz5, Jd2A^8s/X,0Rt{Ux<ӟ+_tR9H\b8,dH K~r4Dq&#fpD%bA)WGg˜j7;yUi_OX+N)?%L&l6ø[h"\r%Xd <\.f3F_h~EQy#'EeoJ D |"\6bX,l#fcJ+:_)ѕBV{U KR)6-f+bs0ͰZlW)5U))W_|,fH$`4Y/5L&X,| /s=k֬a5~=y뭷D* :3v )T*وןCiܹhnnؿ }v\r%qƊ}1D,eF@TdՆ R Ad2SgG\Ł9 ęcS<.o`\R5@ơ[=^&QPbQ'7 L8l߾{/:::pW`ҥ )x^$ ߿Z; y=Dt:7g.Î;xbtww @ ={?%/099x<Β= #45/"ZH_-E7}y߰Vbp%@#OԒJ 4)* ]Z .zbqW|m޼zOUp8n ###xߍUVvv^ơCP.Uy,tN zCCC_ "N_FwJ޴c׮]ki&\ru z<lQӉ8&F"jb l6W$v]aZCMC =T[FP4t&I7V)y~q׃W4/BaJIw [lAgg'CvozzzX H5Papp>Oi.X~=r\xC`2dgr9lذ͈D"0Lp:B®]pqd2]:hX <)Ÿ8hԒ~J<< AlqZrqfBb4Tf DOMeIM>WpA)Ħ%7LHRH&lpl,> ~_cժUՅFVx<(Jxױw^&ɄGs@$JaB`I?" 9S8rO?MMMlF0͌cصk."\tEa6dH$p\!0 qGl@ͳ|7B.6?WJiljzD،~ݸ˱dAͲ,c``rܴ@bQDz dٜ~z.liiiկ~;oj0U{VtT SSSH$hmmECC(h`K,ڵko>|fuX'\.rU,L;mZ# UsQ9]@ χ]vG޽{qC/^@ d2@4e&n: y#@7LNH|#fFtvvb۶m;2NRehhmmEss3$8477cٲeXf <^x!\.&&&H$p8`PhvX6zdb|\4ǣ>\J^^w6&Ot:YyJ|瑡8TmRgyQ.zj\s5@CC#wiGssrJtwwk vylddP'"nWWd2Cww7 ^d2ijll,/YDca``PhZ jl6dY:ǖB!6Mctp^/۱rJuYGoo/ Jaʕزe KVO>vz: bpzW_?_VK.e]voKK+Bqd2t:Vaj1ٳ\r <F ,k@$ŢT*%cÆ xp#VE@%nǤR)[n,|. @tuuaݺuC?wVX7bhjjR!tW  444rU<gjHGSĤbP)WU6Zʮ|EWX}+`޽hjjBgg'.b#09nGX(1<<j]*id2Rڴ#~V+oᬳB b7%χ. >O#NNX,:fbX,]vvc…p\hjjBP@<gAPK.E<188_|> ^/c|| )͎`N >%G[V<hooGWW\.Jdm1IL&ce9dYz5z)ǻnyUhU(>(N'::: rw M v=B,Yx044>?(|>/_N; k֬A `ϥJa˅d2B5fj,J C"WS~2L( L)/|;g[D0D[[6n܈6A|><48G"OTL̥R! Pdmۆ>\pt:M($p܌ `ӦMx'`ttt&L} |b. Xh.\W.pJ%X,:::N0991 gŃ>NK-ҥK*}xnuzE@7Vw[+umJ9aS&rU|<-ő#G~E[lA g$vbK\rhCCCl)o6>SyNCG\vnD"sTz$Ift:6~tuua˖-{/}-Pj]DP@,C,CCCC+?Rx<8rB L&x<``en5 eY{0551*[9 ى.,[ ˖-ca<:P24DbL&t:Hg24 7PWc~}%OC J V:u@cc#p%AzzE' caFGGH$Xi ^Rb* iv4ŗ%wyb,H-)(ŋ3;v^6)f199\.Fx C$C[Hg/፧1yk vF6J3 6nVy<LMM!ɈLAZ(ƚX v>rgq2>F(0Jm`&?\#2!f͆SBWn>.K"=|(A聺y\ 5&''{nF+FcG(RUgC&T'?w-‏䥳٬RBbcAD"Gd8nlܸy~ӄa yohŽ1)0v;~?3τ^7ߌn k֬A>֔£"{S$j;,Dr $r {Ǔ5^y maYz5E<U$IG'2 $(c_EdU4zT*ŦB}>K6*ݻw/nlٲׯG0^0"6 h4VtQeoo/W[.C2dJ1H>ody\׏$IbvF JAVj AvfDg~lH.RuC Zuk⼾*䪦O矏5kְVcł^r FT[ %b=|-ihh_6 k.u]f$bY`0t:*5\x IDAT cx j yƗ6_ -ZJ>VFb6Q+HfXa-rtETa%P'}u: [x;088 /v~?aJkɤq> H$Z(}pi:k֬nǫ w}7с1Ӹ>H/k)-ve(L؛oB5o6Qv ]P8{\qx@5j0|T8:LۀSK\RBi_P^x!+ eO* 0o $IO/UW]b75^6",x:8@=j,"k0i %Q'0<*QcQ 'f*JBᡴuGŗ!l6IjTz-}\.K^x~_'? 6n܈ףbӮNJ,YD>tМu< ,8sʙL_ xED"صkVZ&h^/;3Ոv;E. PZLjD) U2 >>f"A-s%R[SASPzEjKAԶ#rֳJwd|d7trn݊n455jT(᤟s6m$UbQ"VD&HFyzDUmR_mxmdW~1. ?3ĺuh"x<XevB<gʮ0GB ccc/@n맦*EUԩT V^P(p8 Nv_3ALBğ\i h(Dϯfs=8F={{%\nx^a曌AZLs37`|АiL1^4W^Aww7VZ24g}hoo-hP8f; @齔ɪ !~u%R:0T+VWJ GkCE|_FkV"%/ ?(/.#%^q1wl۶ v>#B.VSSSÇN+8(Rt׮]Xhl2b:3E'N+Ioi&ivȩ(e= H͆@ ŋcժUطo>`+q3ODؚ0:P_2Ռ@=䚼Qp:1.1׳D_}Y TR~2bq "P[ K-6T*rF|Mj7R^mRb }xMC᷿-^}UJ%X%<1 K<Wfk)L| ވ=/" r,˲˲KRŊ+OϞʼgv;cI&z(ԄFyƱo4… j*]‘#Gۋz g}6.ttt LVm[i#${6SU DjʯBd,;uGiW n)N'$.]͛7cѢEBRr2100d29mŤJHD4,駟ƅ^#eٲHvϗ B5kHַA_%EZ,P_X`"l6[ BXlpQQn%ů Li =J._Ķm011.] ,@KK ' y7H&8pFY5Ol|jAl6>^fs>Y{^N$IJ&瓖-[#Gw=\xi1H2b`add---hoo$I{ qiajjm9p~iy]gu֮]F6ΗĒC {e׻@iXIJ[.bT43ᑒW*t`rh4;v^Ν;a0h"_hnnfe>?U_===@,cqR9/#JAWS?m۶mC:Ʋev|>_*fѨqS>Skkk!֯_/=Xt)*tD6E"Ź\}ĺx%YzO!+WD48100{ _a۱|r^k׮E(b\uj!z~H BM5&aqM (L+;Ap7zj|brOi?@4::;wbϞ=طoZ[[ގ/Po}NMM1bZ6BN$b#r\ a*%ED011~]tdV05Z'|bEexޤju`Νضmկ2H^(آP@db 2ͬOd2H$l)QRB$,]V’%Kxb[Eje!^"F)XޯFERT'R5`bkMӯilP\f`@ <VONNu`t=]zHhhh`4N믿s֭[&Ȳ{ܟ.袍pm9o8nF|߬ڙƣC1JlG([0 ٜb/|hiiA.cLXq~7lY{{;/^e˖---*+ K3՘P 1ezڅyja)6+<_%!H  " a֭qdlJAg(WR/%eYf%C%獇l_+WbŊzj Y9# 2KRP5kJp-G&Q Hy(GY~SD8FSphkkC[[\.[E(DGH_xc(Î;0>>Y… с@ P+!Jov[ju (Q!x"r 9ryݡ!```,L0d䯴K6qc<7)RBICRSB_TENSLT~͆[nXnt:h4*ycI@vɤ-ɤ^T*aÆ o~tv~'qoᨚY@&A?~?,$fjm%ESp8Pr$a===رc(bJ ڊF|>@e Ns5Vk;-u~*yurrg[qg{̙g_[Hb p ZP-Ph+$J/BMW~-*KP˧4\ M? %)(B5x<_eyN~ϱjW:ljcyd2i2HH$M6e]XR’WeFd2 SSSdPO2D`P+ XS.-^A4~19,LkfUۈt$ڟgT[$Du$bC_zxQyK cvu38 ,]xF~+xw/kעC*f2 hL ypvg&RC|t;`~v0,2 9>ϩTUKn~~"*E<*1<馓N5U ?9;.ӬRsr$ZS ZZ"S& f)ycآZ>{looP(,L&X`vv6a`G#G|>_G=ðm6; ~<Y\!`=JFFc,D|فa;!hi@O!RdD܁&''P^(hԓO> /2\uUpyYㆆ(˅ng;|>IzFÇ׭_>T @z+< -u ;B#T^vN` AС!Pę@`u79#JXW-Fh+@yh{(bzE_` 2nXE |T*p$Ip7† ,IR odu9J%2*M`ppnÆ D"x<$I 97 < Gq[,[bD;Ͽ0v|$ /MNd m݉@h R#\HI}N>SGKVA.D"uuuB2Ѻ:x͛7Å^HfDQV( árD /fff  "455kx'?"ќqu. FOՂD Sb+*1>'@t΁F%5><@ԓ 6~Jc {Du]D"a}dR $\s5p9X)7b$xT* >Çz;NS7|3 |x<0$@Zn n&7 BViđ6PZw"@wb i(R /@?5D{~m%e$b%u\v*nHHtB4MHyxꩧχ. z{{-@ `b1cttz@VLo ?zl"h7_G:zhhȗdj[lE +tttݻ矇pZ7F|QD\C,%/'"{8]{9[lM6Agg'ף1T|M$ F>IÓO<33S/bJAojPV1妦&D2hZZZ<ر>Cؼy"I&5umiwn@)):"-?J}v|DU# !t(AیydYۏK\R xxǡm\p]" F<7|e߾}a|Α@yMMMDS믿+ rT*,@.B!Qa$I }֬YL& $ -(-Ѝ3"G;ce6̮fwJ2,ŽT&DeP(d/EAoo";̌~8H96^BW0ӫ@Ckkk,]i -L4)b455A[[tttر}.s"*IDATzo;"vRCacEvN@;/NrCm. /Z*)]ڏ? tL΅B q066>(< W^y%lٲ֯_oHֈㆦiqÇV*,:4Hyq _߳g^8ܷo­z :?LS,3MX6cZ<Wlc l~iw`` DL5JlXyF)OkHw٥vY-;wT$[V+2z'`&*M# {?B{{"ojj hAuvvFGGsss,0 -SjxzLg 6t5HMѻV.=>~_²zzz믿O<,,,@?B6UU G]GStL NTΩ -!eA2ۥvtᴡIDQc Ţ5۹s'w}022pW^guef6aD"РEmdd;11* T*,i /x<׿u] Sf/~RN&ocL4 t!JT 2$ MSWWFkkB -,,,Z)Jd`jj FGGahh:k׮.buPaœQ ,ҲCh**gY  'Z rV^ |E};g@m>tfj v킿o֭nK 02SѺ:Vi<77g-<+jMdx5\s7q@jf qhii/_V PvZ (w>I"]]]ڪ744` 9ZQ Rce2cǎ%\[nFKTl‰׸.`KJi@;tr\/b(]/-/ ۷<]]]cCCY(j133Î9"OOO[$DZL&HѨ>{<o#f2h03 ~ow^*0:K?id2 HX=Fě+#05rb 077CH$ H<!ȗFB]X|>o ,W/W#@Sh>,VzNa{!ڵk-okkD"aEz{'7fV,<11ɤb@SdB? A">95` @ }'MEzʑT*A*jj)ډSM")U&eV1En.rQ AP!s΁͛7CKKUj8,@T ðCSeQ)7EDAP +xDhzavv}]8p:tEmmmԴH"8Ie(‚q1/y?DE$Eن./:j2}x7kFi3/@`N j_yH$jBGf!JYgH7^(a=,jS(~SnR"3։3330==me :;;:::Q&]yD;ȮG(/Rx#T#>ccc0>>n p4f#x,x@9o :0 F^}zL ΂녦&k喂QD rg`͚5,Y\sT#}ʹ|fVgYd2J*Մab`fcc#477[r8kvW ǎgHӖB!yaS2 Y0ڝ8,`tEQt3aBANR033Tʢ$]O_RkBGP2a_2t]W/xffL/v:h?@3x<~/~߯*IxVYL#$ fsx &x@PJDm]VBT%T*-J1@M*Kv >o?-+jd, 4B{^h|JbQ,jaaU!M$&*1,`Q'gTꗾ{D_;!Yl,J]t}~cNvzuݒF?Xsss !B,뙢(麮kq_.j*G0 ƏpI) vT|31NMRCFCϼ I\(:<`z"LyK(#y@*<aDrWNW^y彪i9}3X{0l+g}rqI%YN7ka*wTUUQa[WW'A R"nQVJ"UUI4*q;uio% 9 _)#4IBٵA2 3Q|((YKyp'S1#mX Qu},O2B~p \->085s7bhM1J% ™H$  .jo4w2P"jUjRZe隦yHme h7b%~h9ՠ E_U+)b~J$ɆaH{gT*e ?5sR~t7;y5ZByhIx`0Ȟ{=?я~eFiۏ53!0L'q_ͯ~nQŨjN,-?ci1BZmx@gf@uf:"C4t v"! fa`"Fa\cƉK j$y$IdY=f28,+Zqn&tv9)!'ZkXlQ?L%s2s3(8zsB&w^n]k\64Mc!geB$x^hlly{z3!?{Ye3›TQl7t]QU麮ju]uf^]׫,k&b9,c0 fcLb)$I,2cL$*˲G$&I*I024*VA/*"St_2Bt^/E~WJ&gDnikgB` ,@i믿'w} vUFg\@@Y'ySoJl,y(JM|;Sŏs$ɤWU(a@7N'Cpc2v2cI:373f1zRtlX20,@ Ph"r vcl_^ A[@<_4 NP=S?if%3Ϥ ,%($-nxꩧn^n]3b(_(`nn|>qK wi n2хp@8xu]*sզl<]I/y~π6#"r)2;e ֶ'@,[$ h[nM㟅+%3?m@> =Mb:_wuny90 Brf4|MՖBx Qw^vּFѨuzWxWQ3>A:;v۴iS3v(@V!@)|TXxD#5 8vr_N4߼CeY psM(C/c v"vJDQpڵ 7}ݷq8@ƙd@gGH&P5ߘwu7ئM׭[׀,uv `1"!!"]4vDQ@t,JKNBJ[>WUK\"2"{&od'Ⱦ*,^1448曂%A b1ꫯN{]]]ui P'`@ю?XuhM;Rs>kqH$&p۩"Q , cWTyVjDTZ|>b0";|p;;v>2  pr}L4OV˧Rg}^{-aÆDOOO,3߿DĎ,WuS *:]/QqP |DuRu Qϳ+$oH G}r1߈D"ɻ'tFv&T$|2Lܹ^zi~J@@5e| O#آ+:)?EI/phĜt?Rp۷oz'|=Fi03u xB*&('Z$IZ} `e2caa#2EğtL(u\.[klv\J>(^dv>|,/GL:2iŘa/>jڸi3$ҧW'Q@R\5n2A^{׾z$D"VUى7n 69Dz'#$+1Pq(`tt4s}?aif"PO&p4#%# X[nteu744H.)VXک`Fi JeQ ?WhW&8 2`px3ݲrў1 qXQ7ޘxg>HR#oڌc}_j3r:Sw#F8u߰aÆ뮻n_ѱNቐhB)@ob 4X6rܮ?HAY05U:ƾ\c*$Pe2ӟ4O?6S|Ϊ3cy䲂8'_jW_NnTjW'o9bT.Q._ 82ʬۥ+ ?{4lx7fv9o>k~LF`}5Ao&CX͇:ff|y$tĺ;ڎK/iƍ~Seﰶ/e_u:#:=9AWbضm[%\ !gDo:9ps Dة6 wr@0>'k؆c~&''~;[o%w5izڌ)Os|Zۥj# 1 H!FC(K/i|3ι>bpbц?p:Sti'rf[ǰ\N!88p ;;[*6|V`|3:O6+΀/hPOA8 񁁁76n\~{Y]! "#S`GJeFE^l-g|30 Ce`飏>1}4DFF{#e|p:z8lfX,V7m<JGGbfl-0њVU(MO*n GsVyiDeD\cǎC8Pܿ.JZm޼cJ ,i]O;3 T,\aq8 ===^oWWd\D7<E 6t\ɏy  8fFßxmdd666V."JMqW;604wu_S1d,OJl.򟇨C0WS[fx<.b1(B!VWWBdnIĨ엪rrFXt:R)m~~^d2:55U;~xmrrZVi F_"0SGx]pZ9)В5cu²]2wIqzрq\M|=u*Rqѻrcbd8D~{KK:8&0~e P.4|]DW6Ʈ wS@%w^A6A# _r 1j`5*Wx{ Sw8\%ARr0tI0l u%aɗ3t] Lo`cC:a%N}^.J5r4y/=q{=q{=q{=q{=q{=q{=q{=q{=q{=q{=q{=q{=q{=q{V&I$zGIENDB`relational/relational_gui/rel_edit.ui0000664000175000017500000001032514647215100017371 0ustar salvosalvo 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/editor.py0000664000175000017500000000444714647215100017113 0ustar salvosalvo# Relational # Copyright (C) 2016-2024 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. from PyQt6.QtWidgets import QPlainTextEdit from PyQt6.QtWidgets import QTextEdit from PyQt6.QtCore import Qt from PyQt6.QtGui import QColor from PyQt6.QtGui import QPalette from PyQt6.QtGui import QTextCharFormat class Editor(QPlainTextEdit): def __init__(self, *args, **kwargs): super(Editor, self).__init__(*args, **kwargs) self._cursor_moved() self.cursorPositionChanged.connect(self._cursor_moved) def _cursor_moved(self): selections = [] # Current line cur_line = QTextEdit.ExtraSelection() bgcolor = QPalette().color( QPalette.ColorGroup.Active, QPalette.ColorRole.Window, ).lighter() cur_line.format.setBackground(bgcolor) cur_line.format.setProperty( QTextCharFormat.Property.FullWidthSelection, True ) cur_line.cursor = self.textCursor() cur_line.cursor.clearSelection() selections.append(cur_line) # Apply the selections self.setExtraSelections(selections) def wheelEvent(self, event): if event.modifiers() & Qt.ControlModifier: event.accept() self.zoom(1 if event.angleDelta().y()>0 else -1) else: super(Editor, self).wheelEvent(event) def zoom(self, incr): font = self.font() point_size = font.pointSize() point_size += incr font.setPointSize(point_size) self.setFont(font) relational/relational_gui/survey.ui0000664000175000017500000002370114647215100017141 0ustar salvosalvo 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/guihandler.py0000664000175000017500000004105614647215100017744 0ustar salvosalvo# Relational # Copyright (C) 2008-2024 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 from gettext import gettext as _ from PyQt6 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 version = '' 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) if os.path.exists('/usr/share/pixmaps/relational.png'): icon = QtGui.QIcon('/usr/share/pixmaps/relational.png') self.setWindowIcon(icon) else: ... #FIXME set icon on non-linux systems # 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.StandardKey.Delete, self.unloadRelation), (self.ui.lstRelations, 'Space', lambda: self.printRelation(self.ui.lstRelations.currentItem())), (self.ui.txtQuery, QtGui.QKeySequence.StandardKey.MoveToNextLine, self.next_history), (self.ui.txtQuery, QtGui.QKeySequence.StandardKey.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 = QtGui.QAction(self) action.triggered.connect(slot) action.setShortcut(QtGui.QKeySequence(shortcut)) action.setShortcutContext(QtCore.Qt.ShortcutContext.WidgetShortcut) widget.addAction(action) def checkVersion(self): from relational import maintenance online = maintenance.check_latest_version() if online is None: r = _('Network error') elif online > version: r = _('New version available online: %s.') % online elif online == version: r = _('Latest version installed.') else: r = _('You are using an unstable version.') QtWidgets.QMessageBox.information(self, _('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 is 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): if k is None: item.setBackground(j, QtGui.QBrush(QtCore.Qt.GlobalColor.darkRed, QtCore.Qt.BrushStyle.Dense4Pattern)) elif isinstance(k, (int, float)): item.setForeground(j, QtGui.QPalette().link()) elif not isinstance(k, str): item.setBackground(j, QtGui.QBrush(QtCore.Qt.GlobalColor.darkGreen, QtCore.Qt.BrushStyle.Dense4Pattern)) item.setText(j, str(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(): QtWidgets.QMessageBox.information( self, _('Error'), _('Select a relation first.') ) return filename = QtWidgets.QFileDialog.getSaveFileName( self, _("Save Relation"), "", _("Json relations (*.json);;CSV relations (*.csv)") )[0] if (len(filename) == 0): # Returns if no file was selected return relname = self.ui.lstRelations.selectedItems()[0].text() self.user_interface.store(filename, relname) 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(): try: result = creator.edit_relation( self.user_interface.get_relation(i.text()) ) except Exception as e: QtWidgets.QMessageBox.warning( self, _("Error"), str(e) ) return if result != None: self.user_interface.set_relation(i.text(), result) self.updateRelations() def error(self, exception): print (exception) QtWidgets.QMessageBox.information( self, _("Error"), str(exception) ) def promptRelationName(self): while True: res = QtWidgets.QInputDialog.getText( self, _("New relation"), _("Insert the name for the new relation"), QtWidgets.QLineEdit.EchoMode.Normal, '' ) if res[1] == False: # or len(res[0]) == 0: return None name = res[0] if not rtypes.is_valid_relation_name(name): QtWidgets.QMessageBox.information( self, _("Error"), _('Wrong name for destination relation: {name}.') ) continue return name def newRelation(self): from relational_gui import creator result = creator.edit_relation() if result is 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 is 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 is 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, _("Load Relation"), "", _("Relations (*.json *.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/surveyForm.py0000664000175000017500000002020314647215100017772 0ustar salvosalvo# Relational # Copyright (C) 2008-2024 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 platform import locale from gettext import gettext as _ from PyQt6 import QtWidgets from relational import maintenance version = '' class surveyForm (QtWidgets.QWidget): '''This class is the form used for the survey, needed to intercept the events. It also sends the data with http POST to a page''' def setUi(self, ui): self.ui = ui def setDefaultValues(self): '''Sets default values into the form GUI. It has to be called after the form has been initialized''' # Dictionary with country codes countries = {'BD': 'BANGLADESH', 'BE': 'BELGIUM', 'BF': 'BURKINA FASO', 'BG': 'BULGARIA', 'BA': 'BOSNIA AND HERZEGOVINA', 'BB': 'BARBADOS', 'WF': 'WALLIS AND FUTUNA', 'BL': 'SAINT BARTH\xc3\x89LEMY', 'BM': 'BERMUDA', 'BN': 'BRUNEI DARUSSALAM', 'BO': 'BOLIVIA, PLURINATIONAL STATE OF', 'BH': 'BAHRAIN', 'BI': 'BURUNDI', 'BJ': 'BENIN', 'BT': 'BHUTAN', 'JM': 'JAMAICA', 'BV': 'BOUVET ISLAND', 'BW': 'BOTSWANA', 'WS': 'SAMOA', 'BR': 'BRAZIL', 'BS': 'BAHAMAS', 'JE': 'JERSEY', 'BY': 'BELARUS', 'BZ': 'BELIZE', 'RU': 'RUSSIAN FEDERATION', 'RW': 'RWANDA', 'RS': 'SERBIA', 'TL': 'TIMOR-LESTE', 'RE': 'R\xc3\x89UNION', 'TM': 'TURKMENISTAN', 'TJ': 'TAJIKISTAN', 'RO': 'ROMANIA', 'TK': 'TOKELAU', 'GW': 'GUINEA-BISSAU', 'GU': 'GUAM', 'GT': 'GUATEMALA', 'GS': 'SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS', 'GR': 'GREECE', 'GQ': 'EQUATORIAL GUINEA', 'GP': 'GUADELOUPE', 'JP': 'JAPAN', 'GY': 'GUYANA', 'GG': 'GUERNSEY', 'GF': 'FRENCH GUIANA', 'GE': 'GEORGIA', 'GD': 'GRENADA', 'GB': 'UNITED KINGDOM', 'GA': 'GABON', 'GN': 'GUINEA', 'GM': 'GAMBIA', 'GL': 'GREENLAND', 'GI': 'GIBRALTAR', 'GH': 'GHANA', 'OM': 'OMAN', 'TN': 'TUNISIA', 'JO': 'JORDAN', 'HR': 'CROATIA', 'HT': 'HAITI', 'HU': 'HUNGARY', 'HK': 'HONG KONG', 'HN': 'HONDURAS', 'HM': 'HEARD ISLAND AND MCDONALD ISLANDS', 'VE': 'VENEZUELA, BOLIVARIAN REPUBLIC OF', 'PR': 'PUERTO RICO', 'PS': 'PALESTINIAN TERRITORY, OCCUPIED', 'PW': 'PALAU', 'PT': 'PORTUGAL', 'KN': 'SAINT KITTS AND NEVIS', 'PY': 'PARAGUAY', 'IQ': 'IRAQ', 'PA': 'PANAMA', 'PF': 'FRENCH POLYNESIA', 'PG': 'PAPUA NEW GUINEA', 'PE': 'PERU', 'PK': 'PAKISTAN', 'PH': 'PHILIPPINES', 'PN': 'PITCAIRN', 'PL': 'POLAND', 'PM': 'SAINT PIERRE AND MIQUELON', 'ZM': 'ZAMBIA', 'EH': 'WESTERN SAHARA', 'EE': 'ESTONIA', 'EG': 'EGYPT', 'ZA': 'SOUTH AFRICA', 'EC': 'ECUADOR', 'IT': 'ITALY', 'VN': 'VIET NAM', 'SB': 'SOLOMON ISLANDS', 'ET': 'ETHIOPIA', 'SO': 'SOMALIA', 'ZW': 'ZIMBABWE', 'SA': 'SAUDI ARABIA', 'ES': 'SPAIN', 'ER': 'ERITREA', 'ME': 'MONTENEGRO', 'MD': 'MOLDOVA, REPUBLIC OF', 'MG': 'MADAGASCAR', 'MF': 'SAINT MARTIN', 'MA': 'MOROCCO', 'MC': 'MONACO', 'UZ': 'UZBEKISTAN', 'MM': 'MYANMAR', 'ML': 'MALI', 'MO': 'MACAO', 'MN': 'MONGOLIA', 'MH': 'MARSHALL ISLANDS', 'MK': 'MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF', 'MU': 'MAURITIUS', 'MT': 'MALTA', 'MW': 'MALAWI', 'MV': 'MALDIVES', 'MQ': 'MARTINIQUE', 'MP': 'NORTHERN MARIANA ISLANDS', 'MS': 'MONTSERRAT', 'MR': 'MAURITANIA', 'IM': 'ISLE OF MAN', 'UG': 'UGANDA', 'TZ': 'TANZANIA, UNITED REPUBLIC OF', 'MY': 'MALAYSIA', 'MX': 'MEXICO', 'IL': 'ISRAEL', 'FR': 'FRANCE', 'AW': 'ARUBA', 'SH': 'SAINT HELENA', 'SJ': 'SVALBARD AND JAN MAYEN', 'FI': 'FINLAND', 'FJ': 'FIJI', 'FK': 'FALKLAND ISLANDS (MALVINAS)', 'FM': 'MICRONESIA, FEDERATED STATES OF', 'FO': 'FAROE ISLANDS', 'NI': 'NICARAGUA', 'NL': 'NETHERLANDS', 'NO': 'NORWAY', 'NA': 'NAMIBIA', 'VU': 'VANUATU', 'NC': 'NEW CALEDONIA', 'NE': 'NIGER', 'NF': 'NORFOLK ISLAND', 'NG': 'NIGERIA', 'NZ': 'NEW ZEALAND', 'NP': 'NEPAL', 'NR': 'NAURU', 'NU': 'NIUE', 'CK': 'COOK ISLANDS', 'CI': "C\xc3\x94TE D'IVOIRE", 'CH': 'SWITZERLAND', 'CO': 'COLOMBIA', 'CN': 'CHINA', 'CM': 'CAMEROON', 'CL': 'CHILE', 'CC': 'COCOS (KEELING) ISLANDS', 'CA': 'CANADA', 'CG': 'CONGO', 'CF': 'CENTRAL AFRICAN REPUBLIC', 'CD': 'CONGO, THE DEMOCRATIC REPUBLIC OF THE', 'CZ': 'CZECH REPUBLIC', 'CY': 'CYPRUS', 'CX': 'CHRISTMAS ISLAND', 'CR': 'COSTA RICA', 'CV': 'CAPE VERDE', 'CU': 'CUBA', 'SZ': 'SWAZILAND', 'SY': 'SYRIAN ARAB REPUBLIC', 'KG': 'KYRGYZSTAN', 'KE': 'KENYA', 'SR': 'SURINAME', 'KI': 'KIRIBATI', 'KH': 'CAMBODIA', 'SV': 'EL SALVADOR', 'KM': 'COMOROS', 'ST': 'SAO TOME AND PRINCIPE', 'SK': 'SLOVAKIA', 'KR': 'KOREA, REPUBLIC OF', 'SI': 'SLOVENIA', 'KP': "KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF", 'KW': 'KUWAIT', 'SN': 'SENEGAL', 'SM': 'SAN MARINO', 'SL': 'SIERRA LEONE', 'SC': 'SEYCHELLES', 'KZ': 'KAZAKHSTAN', 'KY': 'CAYMAN ISLANDS', 'SG': 'SINGAPORE', 'SE': 'SWEDEN', 'SD': 'SUDAN', 'DO': 'DOMINICAN REPUBLIC', 'DM': 'DOMINICA', 'DJ': 'DJIBOUTI', 'DK': 'DENMARK', 'VG': 'VIRGIN ISLANDS, BRITISH', 'DE': 'GERMANY', 'YE': 'YEMEN', 'DZ': 'ALGERIA', 'US': 'UNITED STATES', 'UY': 'URUGUAY', 'YT': 'MAYOTTE', 'UM': 'UNITED STATES MINOR OUTLYING ISLANDS', 'LB': 'LEBANON', 'LC': 'SAINT LUCIA', 'LA': "LAO PEOPLE'S DEMOCRATIC REPUBLIC", 'TV': 'TUVALU', 'TW': 'TAIWAN, PROVINCE OF CHINA', 'TT': 'TRINIDAD AND TOBAGO', 'TR': 'TURKEY', 'LK': 'SRI LANKA', 'LI': 'LIECHTENSTEIN', 'LV': 'LATVIA', 'TO': 'TONGA', 'LT': 'LITHUANIA', 'LU': 'LUXEMBOURG', 'LR': 'LIBERIA', 'LS': 'LESOTHO', 'TH': 'THAILAND', 'TF': 'FRENCH SOUTHERN TERRITORIES', 'TG': 'TOGO', 'TD': 'CHAD', 'TC': 'TURKS AND CAICOS ISLANDS', 'LY': 'LIBYAN ARAB JAMAHIRIYA', 'VA': 'HOLY SEE (VATICAN CITY STATE)', 'VC': 'SAINT VINCENT AND THE GRENADINES', 'AE': 'UNITED ARAB EMIRATES', 'AD': 'ANDORRA', 'AG': 'ANTIGUA AND BARBUDA', 'AF': 'AFGHANISTAN', 'AI': 'ANGUILLA', 'VI': 'VIRGIN ISLANDS, U.S.', 'IS': 'ICELAND', 'IR': 'IRAN, ISLAMIC REPUBLIC OF', 'AM': 'ARMENIA', 'AL': 'ALBANIA', 'AO': 'ANGOLA', 'AN': 'NETHERLANDS ANTILLES', 'AQ': 'ANTARCTICA', 'AS': 'AMERICAN SAMOA', 'AR': 'ARGENTINA', 'AU': 'AUSTRALIA', 'AT': 'AUSTRIA', 'IO': 'BRITISH INDIAN OCEAN TERRITORY', 'IN': 'INDIA', 'AX': '\xc3\x85LAND ISLANDS', 'AZ': 'AZERBAIJAN', 'IE': 'IRELAND', 'ID': 'INDONESIA', 'UA': 'UKRAINE', 'QA': 'QATAR', 'MZ': 'MOZAMBIQUE'} # Setting system string try: self.ui.txtSystem.setText(platform.platform()) self.ui.txtSystem.setCursorPosition(0) except: pass # Getting country from locale code try: locale.setlocale(locale.LC_ALL, '') country_code = locale.getlocale()[0].split('_')[1] self.ui.txtCountry.setText(countries[country_code]) self.ui.txtCountry.setCursorPosition(0) except: pass def send(self): '''Sends the data inserted in the form''' post = {} post['software'] = "Relational algebra" post["version"] = version post["system"] = self.ui.txtSystem.text() post["country"] = self.ui.txtCountry.text() post["school"] = self.ui.txtSchool.text() post["age"] = self.ui.txtAge.text() post["find"] = self.ui.txtFind.text() post["email"] = self.ui.txtEmail.text() post["comments"] = self.ui.txtComments.toPlainText() # Clears the form self.ui.txtSystem.clear() self.ui.txtCountry.clear() self.ui.txtSchool.clear() self.ui.txtAge.clear() self.ui.txtFind.clear() self.ui.txtEmail.clear() self.ui.txtComments.clear() response = maintenance.send_survey(post) if response == 200: QtWidgets.QMessageBox.information(None, _('Thanks'), _('Thanks for sending!')) elif response == -1: QtWidgets.QMessageBox.information(None, _('Seriously?'), _('Yeah, not sending that.')) else: QtWidgets.QMessageBox.information(None, _('Error'), _('Unable to send the data!')) self.hide() relational/relational_gui/__init__.py0000664000175000017500000000000014647215100017341 0ustar salvosalvorelational/relational_gui/creator.py0000664000175000017500000001076014647215100017257 0ustar salvosalvo# Relational # Copyright (C) 2008-2024 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 gettext import gettext as _ from PyQt6 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 is 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, value in enumerate(i): if value is None: raise Exception(_('Relation contains a None value and cannot be edited from the GUI')) item = QtWidgets.QTableWidgetItem() item.setText(str(value)) self.table.setItem(self.table.rowCount() - 1, j, item) 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, _("Error"), "%s\n%s" % ( _("Header error!"), e.__str__())) return None content = [] 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, _("Error"), _('Unset value in %d,%d!') % (i + 1, j + 1)) return None content.append(hlist) return relation.Relation.create_from(header, content) 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 relational/relational_gui/about.py0000664000175000017500000021633114647215100016734 0ustar salvosalvo# Relational # Copyright (C) 2008-2024 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 PyQt6 import QtCore, QtGui, QtWidgets version = '' class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(510, 453) self.verticalLayout_2 = QtWidgets.QVBoxLayout(Dialog) self.verticalLayout_2.setObjectName("verticalLayout_2") self.tabWidget = QtWidgets.QTabWidget(Dialog) self.tabWidget.setObjectName("tabWidget") self.tab = QtWidgets.QWidget() self.tab.setGeometry(QtCore.QRect(0, 0, 494, 377)) self.tab.setObjectName("tab") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.tab) self.verticalLayout_3.setObjectName("verticalLayout_3") self.groupBox = QtWidgets.QGroupBox(self.tab) self.groupBox.setObjectName("groupBox") self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.groupBox) self.verticalLayout_5.setObjectName("verticalLayout_5") self.label = QtWidgets.QLabel(self.groupBox) font = QtGui.QFont() font.setPointSize(15) self.label.setFont(font) self.label.setObjectName("label") self.verticalLayout_5.addWidget(self.label) self.label_3 = QtWidgets.QLabel(self.groupBox) self.label_3.setObjectName("label_3") self.verticalLayout_5.addWidget(self.label_3) self.verticalLayout_3.addWidget(self.groupBox) self.groupBox_3 = QtWidgets.QGroupBox(self.tab) self.groupBox_3.setObjectName("groupBox_3") self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.groupBox_3) self.verticalLayout_4.setObjectName("verticalLayout_4") self.label_2 = QtWidgets.QLabel(self.groupBox_3) self.label_2.setObjectName("label_2") self.verticalLayout_4.addWidget(self.label_2) self.verticalLayout_3.addWidget(self.groupBox_3) self.groupBox_2 = QtWidgets.QGroupBox(self.tab) self.groupBox_2.setObjectName("groupBox_2") self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.groupBox_2) self.verticalLayout_6.setObjectName("verticalLayout_6") self.label_4 = QtWidgets.QLabel(self.groupBox_2) self.label_4.setObjectName("label_4") self.verticalLayout_6.addWidget(self.label_4) self.label_donate = QtWidgets.QLabel(self.groupBox_2) self.verticalLayout_6.addWidget(self.label_donate) self.verticalLayout_3.addWidget(self.groupBox_2) self.tabWidget.addTab(self.tab, "") self.License = QtWidgets.QWidget() self.License.setGeometry(QtCore.QRect(0, 0, 494, 377)) self.License.setObjectName("License") self.verticalLayout = QtWidgets.QVBoxLayout(self.License) self.verticalLayout.setObjectName("verticalLayout") self.textEdit = QtWidgets.QTextEdit(self.License) self.textEdit.setObjectName("textEdit") self.verticalLayout.addWidget(self.textEdit) self.tabWidget.addTab(self.License, "") self.tab_2 = QtWidgets.QWidget() self.tab_2.setObjectName("tab_2") self.verticalLayout_7 = QtWidgets.QVBoxLayout(self.tab_2) self.verticalLayout_7.setObjectName("verticalLayout_7") self.verticalLayout_2.addWidget(self.tabWidget) self.buttonBox = QtWidgets.QDialogButtonBox(Dialog) self.buttonBox.setObjectName("buttonBox") self.verticalLayout_2.addWidget(self.buttonBox) self.retranslateUi(Dialog) self.tabWidget.setCurrentIndex(0) self.buttonBox.accepted.connect(Dialog.accept) self.buttonBox.rejected.connect(Dialog.reject) def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtWidgets.QApplication.translate( "Dialog", "Documentation", None)) self.groupBox.setTitle(QtWidgets.QApplication.translate( "Dialog", "Relational", None)) self.label.setText(QtWidgets.QApplication.translate( "Dialog", "Relational", None)) self.label_3.setText(QtWidgets.QApplication.translate( "Dialog", "Version " + version, None)) self.label_3.setTextInteractionFlags( QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse | QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) self.groupBox_3.setTitle(QtWidgets.QApplication.translate( "Dialog", "Author", None)) self.label_2.setText(QtWidgets.QApplication.translate( "Dialog", "Salvo \"LtWorf\" Tomaselli <tiposchi@tiscali.it>
Emilio Di Prima <emiliodiprima[at]msn[dot]com> (For the windows setup)", None)) self.label_2.setOpenExternalLinks(True) self.label_2.setTextInteractionFlags( QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse | QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) self.groupBox_2.setTitle(QtWidgets.QApplication.translate( "Dialog", "Links", None)) self.label_4.setText(QtWidgets.QApplication.translate( "Dialog", "https://ltworf.codeberg.page/relational/", None)) self.label_4.setOpenExternalLinks(True) self.label_4.setTextInteractionFlags( QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse | QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) self.label_donate.setText(QtWidgets.QApplication.translate( "Dialog", "Donate", None)) self.label_donate.setOpenExternalLinks(True) self.label_donate.setTextInteractionFlags( QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse | QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QtWidgets.QApplication.translate( "Dialog", "About", None)) self.textEdit.setHtml(QtWidgets.QApplication.translate("Dialog", "\n" "GNU General Public License - GNU Project - Free Software Foundation (FSF)\n" "

GNU GENERAL PUBLIC LICENSE

\n" "

Version 3, 29 June 2007

\n" "

Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>

\n" "

Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

\n" "

Preamble

\n" "

The GNU General Public License is a free, copyleft license for software and other kinds of works.

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

The precise terms and conditions for copying, distribution and modification follow.

\n" "

TERMS AND CONDITIONS

\n" "

0. Definitions.

\n" "

“This License” refers to version 3 of the GNU General Public License.

\n" "

“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.

\n" "

“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.

\n" "

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.

\n" "

A “covered work” means either the unmodified Program or a work based on the Program.

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

1. Source Code.

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.

\n" "

The Corresponding Source for a work in source code form is that same work.

\n" "

2. Basic Permissions.

\n" "

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.

\n" "

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.

\n" "

Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.

\n" "

3. Protecting Users\' Legal Rights From Anti-Circumvention Law.

\n" "

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.

\n" "

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.

\n" "

4. Conveying Verbatim Copies.

\n" "

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.

\n" "

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.

\n" "

5. Conveying Modified Source Versions.

\n" "

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:

\n" "
  • a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
  • \n" "
  • 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”.
  • \n" "
  • 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.
  • \n" "
  • 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.
\n" "

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.

\n" "

6. Conveying Non-Source Forms.

\n" "

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:

\n" "
  • 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.
  • \n" "
  • 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.
  • \n" "
  • 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.
  • \n" "
  • 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.
  • \n" "
  • 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.
\n" "

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.

\n" "

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.

\n" "

“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.

\n" "

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).

\n" "

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.

\n" "

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.

\n" "

7. Additional Terms.

\n" "

“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.

\n" "

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.

\n" "

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:

\n" "
  • a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
  • \n" "
  • 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
  • \n" "
  • 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
  • \n" "
  • d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
  • \n" "
  • e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
  • \n" "
  • 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.
\n" "

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.

\n" "

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.

\n" "

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.

\n" "

8. Termination.

\n" "

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).

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

9. Acceptance Not Required for Having Copies.

\n" "

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.

\n" "

10. Automatic Licensing of Downstream Recipients.

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

11. Patents.

\n" "

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”.

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

12. No Surrender of Others\' Freedom.

\n" "

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.

\n" "

13. Use with the GNU Affero General Public License.

\n" "

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.

\n" "

14. Revised Versions of this License.

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

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.

\n" "

15. Disclaimer of Warranty.

\n" "

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.

\n" "

16. Limitation of Liability.

\n" "

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.

\n" "

17. Interpretation of Sections 15 and 16.

\n" "

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.

\n" "

END OF TERMS AND CONDITIONS

\n" "

How to Apply These Terms to Your New Programs

\n" "

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.

\n" "

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.

\n" "
    <one line to give the program\'s name and a brief idea of what it does.>
\n" "
    Copyright (C) <year>  <name of author>
\n" "
\n"
                                                               "
    This program is free software: you can redistribute it and/or modify
\n" "
    it under the terms of the GNU General Public License as published by
\n" "
    the Free Software Foundation, either version 3 of the License, or
\n" "
    (at your option) any later version.
\n" "
\n"
                                                               "
    This program is distributed in the hope that it will be useful,
\n" "
    but WITHOUT ANY WARRANTY; without even the implied warranty of
\n" "
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
\n" "
    GNU General Public License for more details.
\n" "
\n"
                                                               "
    You should have received a copy of the GNU General Public License
\n" "
    along with this program.  If not, see <http://www.gnu.org/licenses/>. 
\n" "

Also add information on how to contact you by electronic and paper mail.

\n" "

If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:

\n" "
    <program>  Copyright (C) <year>  <name of author>
\n" "
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w\'.
\n" "
    This is free software, and you are welcome to redistribute it
\n" "
    under certain conditions; type `show c\' for details. 
\n" "

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”.

\n" "

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 <http://www.gnu.org/licenses/>.

\n" "

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 <http://www.gnu.org/philosophy/why-not-lgpl.html>.

", None)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.License), QtWidgets.QApplication.translate( "Dialog", "License", None)) relational/README.md0000664000175000017500000000344114647215100013525 0ustar salvosalvoRelational ========== Relational an educational tool to provide a workspace for experimenting with *relational* *algebra*, an offshoot of first-order logic. ![screenshot](https://ltworf.codeberg.pages/relational/screenshots/3.png) I test it on GNU/Linux and Windows. It probably works on other systems too. 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 [![Donate to LtWorf](docs/donate.svg)](https://liberapay.com/ltworf/donate) Official website ================ More documentation can be found here https://ltworf.codeberg.pages/relational/ Install ======= * Windows:https://ltworf.codeberg.pages/relational/download.html?exe * Debian based: `apt-get install relational` * Everyone else: Download the sourceshttps://ltworf.codeberg.pages/relational/download.html?tar.gz Run from sources ================ For the dependencies, check `debian/control` for the build dependencies. You will need to run ``` make ``` to generate some .py files. To launch the application, run ``` ./relational.py ``` Syntax ====== These are some valid queries (using the provided example dataset) ``` # Join people and skills people ⋈ skills # Select people within a certain age range σ age > 25 and age < 50 (people) # Selection with complicated expression requires an extra set of () around the expression σ (name.upper().startswith('J') and age > 21) (people) # Cartesian product of people with itself, including only name and id ρ id➡i, name➡n (people) * π name, id (people) ``` For the selection, python expressions are used. The syntax is explained here:https://ltworf.codeberg.pages/relational/allowed_expressions.html relational/relational.kdev40000600000175000017500000000011514647215100015320 0ustar salvosalvo[Project] CreatedFrom=Makefile Manager=KDevCustomMakeManager Name=relational relational/CHANGELOG0000664000175000017500000002360014647215100013457 0ustar salvosalvo3.3 - Move to qt6 - Fix survey - Improve localization 3.2 - Move to codeberg 3.1 - Fix version check - Add support for localization - Add Italian localization - Use setuptools because python dropped distutil -_-' - Fix survey - Drop windows 3.0 - UI shows different colours for different types - Better documentation on the website - By default relations are saved as json. This allows to keep the type - Dates can no longer be added or subtracted - Types are now inferred by column, no longer by cell - Relations now use frozenset internally and are immutable - Refactored parser to use better typing - Refactored and fixed some optimizations - Added more test cases - Improved survey sending - Prevent relation/field names from being reserved keywords - Fixed issue in cli where loading an invalid file would lead to a crash - Added typing hints throughout the code - New major release, API changed - Windows: installer installs python and uses pip to get dependencies 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/relational/0000775000175000017500000000000014647215100014376 5ustar salvosalvorelational/relational/__pycache__/0000775000175000017500000000000014647215100016606 5ustar salvosalvorelational/relational/relation.py0000664000175000017500000004427514647215100016601 0ustar salvosalvo# Relational # Copyright (C) 2008-2024 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. from itertools import chain, repeat, product as iproduct from collections import deque from typing import FrozenSet, Iterable, List, Dict, Tuple, Optional from dataclasses import dataclass from pathlib import Path from gettext import gettext as _ from relational.rtypes import * __all__ = [ 'Relation', 'Header', ] @dataclass(repr=True, unsafe_hash=False, frozen=True) class Relation: ''' 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. ''' header: 'Header' content: FrozenSet[Tuple[CastValue, ...]] @staticmethod def load_csv(filename: Union[str, Path]) -> 'Relation': ''' Load a relation object from a csv file. The 1st row is the header and the other rows are the content. Types will be inferred automatically ''' import csv with open(filename) as fp: reader = csv.reader(fp) # Creating a csv reader header = Header(next(reader)) # read 1st line return Relation.create_from(header, reader) @staticmethod def load(filename: Union[str, Path]) -> 'Relation': ''' Load a relation object from a json file. ''' with open(filename) as fp: from json import load as jload from typedload import load loaded = jload(fp) header = Header(loaded['header']) content = [] for row in loaded['content']: if len(row) != len(header): raise ValueError(_('Line %d contains an incorrect amount of values') % row) t_row: Tuple[Optional[Union[int, float, str, Rdate]], ...] = load( row, Tuple[Optional[Union[int, float, str, Rdate]], ...], # type: ignore basiccast=False ) content.append(t_row) return Relation(header, frozenset(content)) def save(self, filename: Union[Path, str]) -> None: ''' Saves the relation in a file. Will save using the json format ''' with open(filename, 'w') as fp: from json import dump as jdump from typedload import dump jdump(dump(self), fp) def save_csv(self, filename: Union[Path, str]) -> None: ''' Saves the relation in a file. Will save using the csv format as defined in RFC4180. ''' import csv with open(filename, 'w', newline='\n') 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) @staticmethod def create_from(header: Iterable[str], content: Iterable[List[str]]) -> 'Relation': ''' Iterator for the header, and iterator for the content. This will infer types. ''' header = Header(header) r_content = [] guessed_types = list(repeat({Rdate, float, int, str}, len(header))) for row in content: if len(row) != len(header): raise ValueError(_('Line %d contains an incorrect amount of values') % row) r_content.append(row) # Guess types for i, value in enumerate(row): guessed_types[i] = guessed_types[i].intersection(guess_type(value)) typed_content = [] for r in r_content: t = tuple(cast(v, guessed_types[i]) for i, v in enumerate(r)) typed_content.append(t) return Relation(header, frozenset(typed_content)) def __iter__(self): return iter(self.content) def __contains__(self, key): return key in self.content def _rearrange(self, other: 'Relation') -> 'Relation': '''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: str) -> 'Relation': ''' Selection, expr must be a valid Python expression; can contain field names. ''' try: c_expr = compile(expr, 'selection', 'eval') except: raise Exception(_('Failed to compile expression: %s') % expr) content = [] for i in self.content: # Fills the attributes dictionary with the values of the tuple attributes = {attr: i[j] for j, attr in enumerate(self.header) } try: if eval(c_expr, attributes): content.append(i) except Exception as e: raise Exception(_('Failed to evaluate {expr} with {i}\n{e}').format(expr=expr, i=i, e=e)) return Relation(self.header, frozenset(content)) def product(self, other: 'Relation') -> 'Relation': ''' 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') ) header = Header(self.header + other.header) content = frozenset(i+j for i, j in iproduct(self.content, other.content)) return Relation(header, content) def projection(self, *attributes) -> 'Relation': ''' 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')) header = Header((self.header[i] for i in ids)) content = frozenset(tuple((i[j] for j in ids)) for i in self.content) return Relation(header, content) def rename(self, params: Dict[str, str]) -> 'Relation': ''' 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'}) ''' header = self.header.rename(params) return Relation(header, self.content) def intersection(self, other: 'Relation') -> 'Relation': ''' 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 return Relation(self.header, self.content.intersection(other.content)) def difference(self, other: 'Relation') -> 'Relation': '''Difference operation. The result will contain items present in first operand but not in second one. ''' other = self._rearrange(other) # Rearranges attributes' order return Relation(self.header, self.content.difference(other.content)) def division(self, other: 'Relation') -> 'Relation': '''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: 'Relation') -> 'Relation': '''Union operation. The result will contain items present in first and second operands. ''' other = self._rearrange(other) # Rearranges attributes' order return Relation(self.header, self.content.union(other.content)) def thetajoin(self, other: 'Relation', expr: str) -> 'Relation': '''Defined as product and then selection with the given expression.''' return self.product(other).selection(expr) def outer(self, other: 'Relation') -> 'Relation': '''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: 'Relation') -> 'Relation': ''' Outer right join. Considers self as left and param as right. If the tuple has no corrispondence, empy attributes are filled with a None. Just like natural join, it works considering shared attributes. ''' return other.outer_left(self) def outer_left(self, other: 'Relation', swap=False) -> 'Relation': ''' See documentation for outer_right ''' shared = self.header.intersection(other.header) # 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) 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] content = [] 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)) content.append(tuple(item)) added = True # If it didn't partecipate, adds it if not added: item = chain(i, repeat(None, len(noid))) content.append(tuple(item)) return Relation(header, frozenset(content)) def join(self, other: 'Relation') -> 'Relation': ''' 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) # 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) 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] content = [] 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)) content.append(tuple(item)) return Relation(header, frozenset(content)) 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) -> str: return self.pretty_string(tty=False) def pretty_string(self, tty: bool) -> str: ''' Returns a printable string. If tty is enabled, it will attempt to add ANSI color codes ''' c = lambda i, ansi: i if not tty: colorize = c else: from os import isatty if isatty(1) and isatty(2): try: from xtermcolor import colorize # type: ignore except ModuleNotFoundError: colorize = c else: colorize = c m_len = [len(i) + 2 for i in self.header] # Maximum lenght string for f in self.content: for col, k in enumerate(str(val) for val in f): if len(k) + 2 > m_len[col]: m_len[col] = len(k) + 2 res = "" for j, attr in enumerate(self.header): res += colorize(attr.ljust(m_len[j]), ansi=3) for r in self.content: res += "\n" for col, i in enumerate(r): cell = str(i).ljust(m_len[col]) if isinstance(i, (int, float)): cell = colorize(cell, ansi=4) elif i is None: cell = colorize(cell, ansi=1) elif not isinstance(i, str): cell = colorize(cell, ansi=15) res += cell return res 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: Dict[str, str]) -> 'Header': '''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: 'Header') -> int: '''Returns how many attributes this header has in common with a given one''' return len(set(self).intersection(set(other))) def union(self, other: 'Header') -> Set[str]: '''Returns the union of the sets of attributes with another header.''' return set(self).union(set(other)) def intersection(self, other: 'Header') -> Set[str]: '''Returns the set of common attributes with another header.''' return set(self).intersection(set(other)) def getAttributesId(self, param: Iterable[str]) -> List[int]: '''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)) relational/relational/rtypes.py0000664000175000017500000000614114647215100016300 0ustar salvosalvo# Relational # Copyright (C) 2008-2020 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 keyword import re from typing import Union, Set, Any, Callable, Type, Optional from dataclasses import dataclass from gettext import gettext as _ RELATION_NAME_REGEXP = re.compile(r'^[_a-z][_a-z0-9]*$', re.IGNORECASE) _date_regexp = re.compile( r'^([0-9]{1,4})(\\|-|/)([0-9]{1,2})(\\|-|/)([0-9]{1,2})$' ) CastValue = Optional[Union[str, int, float, 'Rdate']] def guess_type(value: str) -> Set[Union[Callable[[Any], Any], Type['Rdate']]]: r: Set[Union[Callable[[Any], Any], Type['Rdate']]] = {str} if _date_regexp.match(value) is not None: r.add(Rdate) try: int(value) r.add(int) except ValueError: pass try: float(value) r.add(float) except ValueError: pass return r def cast(value: str, guesses: Set) -> CastValue: if int in guesses: return int(value) if Rdate in guesses: return Rdate.create(value) if float in guesses: return float(value) return value @dataclass(frozen=True) class Rdate: '''Represents a date''' year: int month: int day: int @property def intdate(self) -> datetime.date: return datetime.date(self.year, self.month, self.day) @property def weekday(self) -> int: return self.intdate.weekday() @staticmethod def create(date: str) -> 'Rdate': '''date: A string representing a date YYYY-MM-DD''' r = _date_regexp.match(date) if not r: raise ValueError(_('%s is not a valid date') % date) year = int(r.group(1)) month = int(r.group(3)) day = int(r.group(5)) return Rdate(year, month, day) def __str__(self): return self.intdate.__str__() 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 is_valid_relation_name(name: str) -> bool: '''Checks if a name is valid for a relation. Returns boolean''' return re.match(RELATION_NAME_REGEXP, name) != None and not keyword.iskeyword(name) relational/relational/optimizations.py0000664000175000017500000004556514647215100017700 0ustar salvosalvo# Relational # Copyright (C) 2009-2020 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 typing import Tuple, Dict, List from relational.relation import Relation from relational import parser from relational.parser import Binary, Unary, Node, PRODUCT, \ DIFFERENCE, UNION, INTERSECTION, DIVISION, JOIN, \ JOIN_LEFT, JOIN_RIGHT, JOIN_FULL, PROJECTION, \ SELECTION, RENAME, ARROW sel_op = ( '//=', '**=', 'and', 'not', 'in', '//', '**', '<<', '>>', '==', '!=', '>=', '<=', '+=', '-=', '*=', '/=', '%=', 'or', '+', '-', '*', '/', '&', '|', '^', '~', '<', '>', '%', '=', '(', ')', ',', '[', ']') def find_duplicates(node, dups=None): ''' Finds repeated subtrees in a parse tree. ''' if dups is None: dups = {} dups[str(node)] = node def duplicated_select(n: parser.Node) -> Tuple[parser.Node, int]: '''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 while isinstance(n, Unary) and n.name == SELECTION and isinstance(n.child, Unary) and n.child.name == SELECTION: changes += 1 prop = n.prop if n.prop != n.child.prop: # Nested but different, joining them prop = n.prop + " and " + n.child.prop # This adds parenthesis if they are needed if n.child.prop.startswith('(') or n.prop.startswith('('): prop = '(%s)' % prop n = Unary( SELECTION, prop, n.child.child, ) return n, changes def futile_union_intersection_subtraction(n: parser.Node) -> Tuple[parser.Node, int]: '''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) ''' if not isinstance(n, Binary): return n, 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: return n.left, 1 # selection and union of the same thing elif n.name == UNION: if n.left.name == SELECTION and isinstance(n.left, Unary) and n.left.child == n.right: return n.right, 1 elif n.right.name == SELECTION and isinstance(n.right, Unary) and n.right.child == n.left: return n.left, 1 # selection and intersection of the same thing elif n.name == INTERSECTION: if n.left.name == SELECTION and isinstance(n.left, Unary) and n.left.child == n.right: return n.left, 1 elif n.right.name == SELECTION and \ isinstance(n.right, Unary) and \ n.right.child == n.left: return n.right, 1 # Subtraction and selection of the same thing elif n.name == DIFFERENCE and \ isinstance(n, Binary) and \ n.right.name == SELECTION and \ isinstance(n.right, Unary) and \ n.right.child == n.left: return Unary( SELECTION, '(not (%s))' % n.right.prop, n.right.child), 1 # Subtraction of the same thing or with selection on the left child elif n.name == DIFFERENCE and \ isinstance(n, Binary) and \ (n.left == n.right or (n.left.name == SELECTION and isinstance(n.left, Unary) and n.left.child == n.right)): return Unary( SELECTION, 'False', n.get_left_leaf() ), 1 return n, 0 def down_to_unions_subtractions_intersections(n: parser.Node) -> Tuple[parser.Node, int]: '''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 isinstance(n, Unary) and n.name == SELECTION and n.child.name in _o: assert isinstance(n.child, Binary) l = Unary(SELECTION, n.prop, n.child.left) r = Unary(SELECTION, n.prop, n.child.right) return Binary(n.child.name, l, r), 1 return n, 0 def duplicated_projection(n: parser.Node) -> Tuple[parser.Node, int]: '''This function locates thing like π i ( π j (R)) and replaces them with π i (R)''' if isinstance(n, Unary) and n.name == PROJECTION and isinstance(n.child, Unary) and n.child.name == PROJECTION: return Unary( PROJECTION, n.prop, n.child.child), 1 return n, 0 def selection_inside_projection(n: parser.Node) -> Tuple[parser.Node, int]: '''This function locates things like σ j (π k(R)) and converts them into π k(σ j (R))''' if isinstance(n, Unary) and n.name == SELECTION and isinstance(n.child, Unary) and n.child.name == PROJECTION: child = Unary( SELECTION, n.prop, n.child.child ) return Unary(PROJECTION, n.child.prop, child), 0 return n, 0 def swap_union_renames(n: parser.Node) -> Tuple[parser.Node, int]: '''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''' if n.name in (DIFFERENCE, UNION, INTERSECTION) and \ isinstance(n, Binary) and \ n.left.name == RENAME and \ isinstance(n.left, Unary) and\ n.right.name == RENAME and \ isinstance(n.right, Unary): l_vars = n.left.get_rename_prop() r_vars = n.right.get_rename_prop() if r_vars == l_vars: child = Binary(n.name, n.left.child, n.right.child) return Unary(RENAME, n.left.prop, child), 1 return n, 0 def futile_renames(n: parser.Node) -> Tuple[parser.Node, int]: '''This function purges renames like ρ id->id,a->q (A) into ρ a->q (A) or removes the operation entirely if they all get removed ''' if isinstance(n, Unary) and n.name == RENAME: renames = n.get_rename_prop() changes = False for k, v in renames.items(): if k == v: changes = True del renames[k] if len(renames) == 0: # Nothing to rename, removing the rename return n.child, 1 elif changes: # Changing the node in place, no need to return to cause a recursive step n.set_rename_prop(renames) return n, 0 def subsequent_renames(n: parser.Node) -> Tuple[parser.Node, int]: '''This function removes redundant subsequent renames joining them into one ρ .. ρ .. (A) into ρ ... (A) ''' if isinstance(n, Unary) and \ n.name == RENAME and \ isinstance(n.child, Unary) and \ n.child.name == RENAME: # Located two nested renames. prop = n.prop + ',' + n.child.prop child = n.child.child n = Unary(RENAME, prop, child) # Creating a dictionary with the attributes renames = n.get_rename_prop() # Scans dictionary to locate things like "a->b,b->c" and replace them # with "a->c" for key, value in tuple(renames.items()): if value in renames: if renames[value] != key: # Double rename on attribute renames[key] = renames[renames[key]] # Sets value del renames[value] # Removes the unused one else: # Cycle rename a->b,b->a del renames[value] # Removes the unused one del renames[key] # Removes the unused one if len(renames) == 0: # Nothing to rename, removing the rename op return n.child, 1 else: n.set_rename_prop(renames) return n, 1 return n, 0 class LevelString(str): level = 0 def tokenize_select(expression: str) -> List[LevelString]: '''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) # 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 r = [] level = 0 for i in l: if not i: continue value = LevelString(i) value.level = level if value == '(': level += 1 elif value == ')': level -= 1 r.append(value) return r def swap_rename_projection(n: parser.Node) -> Tuple[parser.Node, int]: '''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 cut in the projection. ''' if isinstance(n, Unary) and \ n.name == PROJECTION and \ isinstance(n.child, Unary) and \ n.child.name == RENAME: # π index,name(ρ id➡index(R)) renames = n.child.get_rename_prop() projections = set(n.get_projection_prop()) # Use pre-rename names in the projection for k, v in renames.items(): if v in projections: projections.remove(v) projections.add(k) # Eliminate fields for i in list(renames.keys()): if i not in projections: del renames[i] child = Unary(PROJECTION,'' , n.child.child) child.set_projection_prop(list(projections)) n = Unary(RENAME, '', child) n.set_rename_prop(renames) return n, 1 return n, 0 def swap_rename_select(n: parser.Node) -> Tuple[parser.Node, int]: '''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.''' if isinstance(n, Unary) and \ n.name == SELECTION and \ isinstance(n.child, Unary) and \ n.child.name == RENAME: # This is an inverse mapping for the rename renames = {v: k for k, v in n.child.get_rename_prop().items()} # tokenizes expression in select tokens = tokenize_select(n.prop) # Renaming stuff, no enum because I edit the tokens for i in range(len(tokens)): splitted = tokens[i].split('.', 1) if splitted[0] in renames: tokens[i] = LevelString(renames[splitted[0]]) if len(splitted) > 1: tokens[i] = LevelString(tokens[i] + '.' + splitted[1]) child = Unary(SELECTION, ' '.join(tokens), n.child.child) return Unary(RENAME, n.child.prop, child), 1 return n, 0 def select_union_intersect_subtract(n: parser.Node) -> Tuple[parser.Node, int]: '''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''' if isinstance(n, Binary) and \ n.name in {UNION, INTERSECTION, DIFFERENCE} and \ isinstance(n.left, Unary) and \ n.left.name == SELECTION and \ isinstance(n.right, Unary) and \ n.right.name == SELECTION and \ n.left.child == n.right.child: d = {UNION: 'or', INTERSECTION: 'and', DIFFERENCE: 'and not'} op = d[n.name] 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 += ')' prop = t_str % (n.left.prop, op, n.right.prop) else: prop = '%s %s %s' % (n.left.prop, op, n.right.prop) return Unary(SELECTION, prop, n.left.child), 1 return n, 0 def union_and_product(n: parser.Node) -> Tuple[parser.Node, int]: ''' A * B ∪ A * C = A * (B ∪ C) Same thing with inner join ''' if isinstance(n, Binary) and \ n.name == UNION and \ isinstance(n.left, Binary) and \ n.left.name in {PRODUCT, JOIN} and \ isinstance(n.right, Binary) and \ n.left.name == n.right.name: if n.left.left == n.right.left or n.left.left == n.right.right: l = n.left.right r = n.right.left if n.left.left == n.right.right else n.right.right newchild = Binary(UNION, l, r) return Binary(n.left.name, n.left.left, newchild), 1 elif n.left.right == n.right.left or n.left.left == n.right.right: l = n.left.left r = n.right.left if n.right.left == n.right.right else n.right.right newchild = Binary(UNION, l, r) return Binary(n.left.name, n.left.right, newchild), 1 return n, 0 def projection_and_union(n: parser.Node, rels: Dict[str, Relation]) -> Tuple[parser.Node, int]: ''' 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 \ isinstance(n, Binary) and \ n.left.name == PROJECTION and \ isinstance(n.left, Unary) and \ n.right.name == PROJECTION and \ isinstance(n.right, Unary) and \ set(n.left.child.result_format(rels)) == set(n.right.child.result_format(rels)): child = Binary(UNION, n.left.child, n.right.child) return Unary(PROJECTION, n.right.prop, child), 0 return n, 0 def selection_and_product(n: parser.Node, rels: Dict[str, Relation]) -> Tuple[parser.Node, int]: '''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''' if isinstance(n, Unary) and n.name == SELECTION and \ isinstance(n.child, Binary) 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: List[List[LevelString]] = [] temp: List[LevelString] = [] for k in tokens: if k == 'and' and k.level == 0: groups.append(temp) temp = [] else: temp.append(k) if len(temp): groups.append(temp) del 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): t = j.split('.')[0] if t in l_attr: # Field in left l_fields = True if t in r_attr: # Field in right r_fields = True if l_fields and not r_fields: left.append(i) elif r_fields and not l_fields: right.append(i) else: # Unknown.. adding in both both.append(i) # Preparing left selection if left: l_prop = ' and '.join((' '.join(i) for i in left)) if '(' in l_prop: l_prop = '(%s)' % l_prop l_node: Node = Unary(SELECTION, l_prop, n.child.left) else: l_node = n.child.left # Preparing right selection if right: r_prop = ' and '.join((' '.join(i) for i in right)) if '(' in r_prop: r_prop = '(%s)' % r_prop r_node: Node = Unary(SELECTION, r_prop, n.child.right) else: r_node = n.child.right b_node = Binary(n.child.name, l_node, r_node) # Changing main selection if both: both_prop = ' and '.join((' '.join(i) for i in both)) if '(' in both_prop: both_prop = '(%s)' % both_prop r = Unary(SELECTION, both_prop, b_node) return r, len(left) + len(right) else: # No need for general select return b_node, 1 return n, 0 def useless_projection(n: parser.Node, rels: Dict[str, Relation]) -> Tuple[parser.Node, int]: ''' Removes projections that are over all the fields ''' if isinstance(n, Unary) and n.name == PROJECTION and \ set(n.child.result_format(rels)) == set(i.strip() for i in n.prop.split(',')): return n.child, 1 return n, 0 general_optimizations = [ duplicated_select, down_to_unions_subtractions_intersections, duplicated_projection, selection_inside_projection, subsequent_renames, futile_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, ] relational/relational/optimizer.py0000664000175000017500000001317214647215100016776 0ustar salvosalvo# Relational # Copyright (C) 2008-2020 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 typing import Union, Optional, Dict, Any, Tuple from relational.relation import Relation from relational import optimizations from relational.parser import Node, Variable, Unary, Binary, op_functions, tokenize, tree from relational import querysplit from relational.maintenance import UserInterface def optimize_program(code: str, rels: Dict[str, Relation]) -> str: ''' Optimize an entire program, composed by multiple expressions and assignments. ''' lines = code.split('\n') context: Dict[str, Node] = {} last_res = None for line in lines: # skip comments or empty lines line = line.strip() if line.startswith(';') or not line: continue res, query = UserInterface.split_query(line) last_res = res parsed = tree(query) _replace_leaves(parsed, context) context[res] = parsed if last_res is None: return '' node = optimize_all(context[last_res], rels, tostr=False) return querysplit.split(node, rels) def _replace_leaves(node: Node, context: Dict[str, Node]) -> None: ''' 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 isinstance(node, Unary): _replace_leaves(node.child, context) if isinstance(node.child, Variable) and node.child.name in context: node.child = context[node.child.name] elif isinstance(node, Binary): _replace_leaves(node.left, context) _replace_leaves(node.right, context) if isinstance(node.left, Variable) and node.left.name in context: node.left = context[node.left.name] if isinstance(node.right, Variable) and node.right.name in context: node.right = context[node.right.name] def optimize_all(expression: Union[str, Node], rels: Dict[str, Relation], specific: bool = True, general: bool = True, debug: Optional[list] = None, tostr: bool = True) -> Union[str, Node]: '''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') total = 1 while total != 0: total = 0 if specific: for i in optimizations.specific_optimizations: n, c = _recursive_scan(i, n, rels) if c != 0 and isinstance(debug, list): debug.append(str(n)) total += c if general: for j in optimizations.general_optimizations: n, c = _recursive_scan(j, n, None) if c != 0 and isinstance(debug, list): debug.append(str(n)) total += c if tostr: return str(n) else: return n def _recursive_scan(function, node: Node, rels: Optional[Dict[str, Any]]) -> Tuple[Node, int]: '''Does a recursive optimization on the tree. This function will recursively 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.''' args = [] if rels is not None: args.append(rels) changes = 0 node, c = function(node, *args) changes += c if isinstance(node, Unary): node.child, c = _recursive_scan(function, node.child, rels) changes += c elif isinstance(node, Binary): node.left, c = _recursive_scan(function, node.left, rels) changes += c node.right, c = _recursive_scan(function, node.right, rels) changes += c return node, changes relational/relational/parser.py0000664000175000017500000004011414647215100016244 0ustar salvosalvo# Relational # Copyright (C) 2008-2024 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: # https://ltworf.codeberg.page/relational/grammar.html from typing import Optional, Union, List, Any, Dict, Literal from dataclasses import dataclass from gettext import gettext as _ from relational import rtypes __all__ = [ 'PRODUCT', 'DIFFERENCE', 'UNION', 'INTERSECTION', 'DIVISION', 'JOIN', 'JOIN_LEFT', 'JOIN_RIGHT', 'JOIN_FULL', 'PROJECTION', 'SELECTION', 'RENAME', 'ARROW', 'TokenizerException', 'ParserException', 'CallableString', 'Node', 'Unary', 'Binary', 'Variable', 'tree', 'parse', ] 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) @dataclass class Node: '''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.''' name: str def __init__(self, name: str) -> None: raise NotImplementedError('This is supposed to be an abstract class') def toCode(self): #FIXME return type '''This method converts the AST into a python code object''' code = self._toPython() return compile(code, '', 'eval') def toPython(self) -> CallableString: '''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) -> str: raise NotImplementedError() def printtree(self, level: int = 0) -> str: '''returns a representation of the tree using indentation''' r = ' ' * level + self.name if self.name in b_operators and isinstance(self, Binary): r += self.left.printtree(level + 1) r += self.right.printtree(level + 1) elif self.name in u_operators and isinstance(self, Unary): r += '\t%s\n' % self.prop r += self.child.printtree(level + 1) return '\n' + r def get_left_leaf(self) -> 'Node': raise NotImplementedError() def result_format(self, rels: dict) -> list: #FIXME types '''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 isinstance(self, Variable): #FIXME this is ugly return list(rels[self.name].header) elif isinstance(self, Binary): if self.name in (DIFFERENCE, UNION, INTERSECTION): return self.left.result_format(rels) elif self.name == DIVISION: return list(set(self.left.result_format(rels)) - set(self.right.result_format(rels))) elif self.name == PRODUCT: return self.left.result_format(rels) + self.right.result_format(rels) 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)))) elif isinstance(self, Unary): if self.name == PROJECTION: return self.get_projection_prop() elif self.name == SELECTION: return self.child.result_format(rels) elif self.name == RENAME: _vars = self.get_rename_prop() _fields = self.child.result_format(rels) for i in range(len(_fields)): if _fields[i] in _vars: _fields[i] = _vars[_fields[i]] return _fields raise ValueError(_('What kind of alien object is this?')) def __eq__(self, other): #FIXME 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 @dataclass class Variable(Node): def _toPython(self) -> str: return self.name def __str__(self): return self.name def get_left_leaf(self) -> Node: return self @dataclass class Binary(Node): name: str left: Node right: Node def get_left_leaf(self) -> Node: return self.left.get_left_leaf() def _toPython(self) -> str: return '%s.%s(%s)' % (self.left._toPython(), op_functions[self.name], self.right._toPython()) def __str__(self): le = self.left.__str__() if isinstance(self.right, Binary): re = "(" + self.right.__str__() + ")" else: re = self.right.__str__() return (le + self.name + re) #TODO use fstrings @dataclass class Unary(Node): name: str prop: str child: Node def get_left_leaf(self) -> Node: return self.child.get_left_leaf() def __str__(self): return self.name + " " + self.prop + " (" + self.child.__str__() + ")" #TODO use fstrings def _toPython(self) -> str: prop = self.prop # Converting parameters if self.name == PROJECTION: prop = repr(self.get_projection_prop()) elif self.name == RENAME: prop = repr(self.get_rename_prop()) else: # Selection prop = repr(prop) return '%s.%s(%s)' % (self.child._toPython(), op_functions[self.name], prop) def get_projection_prop(self) -> List[str]: if self.name != PROJECTION: raise ValueError(_('This is only supported on projection nodes')) return [i.strip() for i in self.prop.split(',')] def set_projection_prop(self, p: List[str]) -> None: if self.name != PROJECTION: raise ValueError(_('This is only supported on projection nodes')) self.prop = ','.join(p) def get_rename_prop(self) -> Dict[str, str]: ''' Returns the dictionary that the rename operation wants ''' if self.name != RENAME: raise ValueError(_('This is only supported on rename nodes')) r = {} for i in self.prop.split(','): q = i.split(ARROW) r[q[0].strip()] = q[1].strip() return r def set_rename_prop(self, renames: Dict[str, str]) -> None: ''' Sets the prop field based on the dictionary for renames ''' if self.name != RENAME: raise ValueError(_('This is only supported on rename nodes')) self.prop = ','.join(f'{k}{ARROW}{v}' for k, v in renames.items()) def parse_tokens(expression: List[Union[list, str]]) -> Node: '''Generates the tree from the tokenized expression If no expression is specified then it will create an empty node''' # 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] if len(expression) == 0: raise ParserException(_('Failed to parse empty expression')) # The list contains only 1 string. Means it is the name of a relation if len(expression) == 1: assert isinstance(expression[0], str) if not rtypes.is_valid_relation_name(expression[0]): raise ParserException( _(f'{expression[0]!r} is not a valid relation name')) return Variable(expression[0]) #FIXME Move validation in the object # 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 if len(expression[:i]) == 0: raise ParserException( _('Expected left operand for %s') % repr(expression[i])) if len(expression[i + 1:]) == 0: raise ParserException( _('Expected right operand for %s') % repr(expression[i])) return Binary(expression[i], parse_tokens(expression[:i]), parse_tokens(expression[i + 1:])) # type: ignore '''Searches for unary operators, parsing from right to left''' for i in range(len(expression)): if expression[i] in u_operators: # Unary operator if len(expression) <= i + 2: raise ParserException( _('Expected more tokens in %s') % repr(expression[i])) elif len(expression) > i + 3: raise ParserException( _('Too many tokens in %s') % repr(expression[i])) return Unary( expression[i], # type: ignore prop=expression[1 + i].strip(), # type: ignore child=parse_tokens(expression[2 + i]) # type: ignore ) raise ParserException(_('Parse error on %s') % repr(expression)) def _find_matching_parenthesis(expression: str, start=0, openpar='(', closepar=')') -> Optional[int]: '''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 return None def _find_token(haystack: str, needle: str) -> int: ''' 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: str) -> list: '''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.''' # List for the tokens items = [] # type: List[Union[str,list]] expression = expression.strip() # Removes initial and ending spaces while len(expression) > 0: if expression.startswith('('): # Parenthesis state end = _find_matching_parenthesis(expression) if end is 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: str) -> Node: '''This function parses a relational algebra expression into a AST and returns the root node using the Node class.''' return parse_tokens(tokenize(expression)) def parse(expr: str) -> CallableString: '''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() relational/relational/maintenance.py0000664000175000017500000001657014647215100017243 0ustar salvosalvo# Relational # Copyright (C) 2008-2024 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 os.path import pickle import base64 from typing import Optional, Tuple from gettext import gettext as _ from relational.relation import Relation from relational import parser from relational.rtypes import is_valid_relation_name def send_survey(data: dict[str, str]) -> int: '''Sends the survey. Data must be a dictionary. returns the http response. returns 0 in case of error returns -1 in case of swearwords''' import urllib.parse from http.client import HTTPSConnection import ssl # Scan for swearwords SWEARWORDS = {'fuck', 'shit', 'suck', 'merda', 'mierda', 'merde'} post = '' for i in data.keys(): post += '%s: %s\n' % (i, data[i].strip()) lowpost = post.lower() for i in SWEARWORDS: if i in lowpost: return -1 # sends the string headers = { "Accept": "text/plain", "X-Survey": "relational", } for k, v in data.items(): headers[f'X-Survey-{k}'] = v connection = HTTPSConnection( 'tomaselli.page', context = ssl._create_unverified_context() # Of course python can't find the root cert ) try: connection.request("GET", "/feedback.py", headers=headers) return connection.getresponse().status except Exception: return 0 def check_latest_version() -> Optional[str]: '''Returns the latest version available. Heavely dependent on server and server configurations not granted to work forever.''' import json import urllib.request try: req = urllib.request.Request('https://codeberg.org/api/v1/repos/ltworf/relational/releases/') with urllib.request.urlopen(req) as f: data = json.load(f) return data[0]['name'] except: return None class UserInterface: '''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) -> None: self.session_reset() def load(self, filename: str, name: str) -> None: '''Loads a relation from file, and gives it a name to be used in subsequent queries. Files ending with .csv are loaded as csv, the others are loaded as json. ''' if filename.lower().endswith('.csv'): rel = Relation.load_csv(filename) else: rel = Relation.load(filename) self.set_relation(name, rel) def unload(self, name: str) -> None: '''Unloads an existing relation.''' del self.relations[name] def store(self, filename: str, name: str) -> None: '''Stores a relation to file.''' if filename.lower().endswith('.csv'): self.relations[name].save_csv(filename) else: self.relations[name].save(filename) def session_dump(self, filename: Optional[str] = None) -> Optional[str]: ''' 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 string. ''' if filename: with open(filename, 'wb') as f: pickle.dump(self.relations, f) return None return base64.b64encode(pickle.dumps(self.relations)).decode() def session_restore(self, session: Optional[bytes] = None, filename: Optional[str] = None) -> 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, 'rb') as f: self.relations = pickle.load(f) def session_reset(self) -> None: ''' Resets the session to a clean one ''' self.relations = {} def get_relation(self, name: str) -> Relation: '''Returns the relation corresponding to name.''' return self.relations[name] def set_relation(self, name: str, rel: Relation) -> None: '''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: str) -> Optional[str]: ''' 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 # Removing the extension try: pos = name.rindex('.') except ValueError: return None name = name[:pos] if not is_valid_relation_name(name): return None return name def execute(self, query: str, relname: str = 'last_') -> Relation: '''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: str, default_name='last_') -> Tuple[str, str]: ''' 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: str) -> Relation: '''Executes multiple queries, separated by \n They can have a syntax of [varname =] query to assign the result to a new relation ''' r = None 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) )) if r is None: raise Exception(_('No query executed')) return r relational/relational/querysplit.py0000664000175000017500000000561114647215100017174 0ustar salvosalvo# Relational # Copyright (C) 2016-2020 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 typing import List, Dict, Tuple from relational.parser import Node, Binary, Unary, Variable __all__ = ['split'] class Program: def __init__(self, rels) -> None: self.queries: List[Tuple[str, Node]] = [] self.dictionary: Dict[str, Node] = {} # 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: Node) -> Node: strnode = str(node) rel = self.dictionary.get(strnode) if rel: return rel qname = next(self.vgen) self.queries.append((qname, node)) n = Variable(qname) self.dictionary[strnode] = n return n def _separate(node: Node, program: Program) -> None: if isinstance(node, Unary) and isinstance(node.child, Variable): _separate(node.child, program) rel = program.append_query(node.child) node.child = rel elif isinstance(node, Binary): if not isinstance(node.left, Variable): _separate(node.left, program) rel = program.append_query(node.left) node.left = rel if not isinstance(node.right, Variable): _separate(node.right, program) rel = program.append_query(node.right) node.right = rel program.append_query(node) def _vargen(avoid: str, prefix: str=''): ''' 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) -> str: ''' Split a query into a program. The idea is that if there are duplicated subtrees they get executed only once. This is used by the optimizer module. ''' p = Program(rels) _separate(node, p) return str(p) relational/relational/__init__.py0000664000175000017500000000014014647215100016502 0ustar salvosalvo__all__ = ( "relation", "parser", "optimizer", "optimizations", "rtypes", ) relational/relational_readline/0000775000175000017500000000000014647215100016241 5ustar salvosalvorelational/relational_readline/linegui.py0000664000175000017500000002543014647215100020253 0ustar salvosalvo# Relational # Copyright (C) 2010-2020 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 typing import Optional from gettext import gettext as _ from relational import relation, parser, rtypes from relational import maintenance from xtermcolor import colorize # type: ignore PROMPT_COLOR = 0xffff00 ERROR_COLOR = 0xff0000 COLOR_GREEN = 0x00ff00 TTY = os.isatty(0) and os.isatty(1) version = '' def printtty(*args, **kwargs): ''' Prints only if stdout and stdin are a tty ''' if TTY: print(*args, **kwargs) class SimpleCompleter: '''Handles completion''' def __init__(self, options) -> None: '''Takes a list of valid completion options''' self.options = sorted(options) 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) 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 ui = maintenance.UserInterface() 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: str, defname: Optional[str]) -> Optional[str]: ''' Loads a relation into the set. Defname is the given name to the relation. Returns the name to the relation, or None if it was not loaded. ''' if not os.path.isfile(filename): print(colorize( _('%s is not a file') % filename, ERROR_COLOR), file=sys.stderr) return None if defname is None: f = filename.split('/') defname = 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 None try: ui.load(filename, defname) completer.add_completion(defname) printtty(colorize(_('Loaded relation %s') % defname, COLOR_GREEN)) return defname except Exception as e: print(colorize(str(e), ERROR_COLOR), file=sys.stderr) return None def survey() -> None: '''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 response = maintenance.send_survey(post) if response == -1: print(_('Yeah, not sending that.')) def help(command: str) -> None: '''Prints help on the various functions''' p = command.split(' ', 1) if len(p) == 1: print(_( 'HELP [command]\n' '\n' 'Comments are obtained starting with a ;\n' '\n' 'To execute a query:\n' '[relation =] query\n' '\n' 'If the 1st part is omitted, the result will be stored in the relation last_.\n' '\n' 'To prevent from printing the relation, append a ; to the end of the query.\n' '\n' 'To insert relational operators, type _OPNAME, they will be internally replaced with the correct symbol.\n' '\n' 'Rember: completion is enabled and can be very helpful if you can\'t remember something.' )) return cmd = p[1] cmdhelp = { 'QUIT': _('Quits the program'), 'LIST': _('Lists the relations loaded'), 'LOAD': _('LOAD filename [relationame]\nLoads a relation into memory'), 'UNLOAD': _('UNLOAD relationame\nUnloads a relation from memory'), 'SAVE': _('SAVE filename relationame\nSaves a relation in a file'), 'HELP': _('Prints the help on a command'), 'SURVEY': _('Fill and send a survey'), } print(cmdhelp.get(cmd, _('Unknown command: %s') % cmd)) def exec_line(command: str) -> None: ''' Executes a line. If it's a command, runs it, if it's a query runs it too ''' 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 ui.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] defname = None if len(pars) > 2: defname = pars[2] load_relation(filename, defname) elif command.startswith('UNLOAD '): pars = command.split(' ') if len(pars) < 2: print(colorize(_("Missing parameter"), ERROR_COLOR)) elif len(pars) > 2: print(colorize(_("Too many parameter"), ERROR_COLOR)) if pars[1] in ui.relations: ui.unload(pars[1]) completer.remove_completion(pars[1]) else: print(colorize(_("No such relation %s") % pars[1], ERROR_COLOR)) elif command.startswith('SAVE '): pars = command.split(' ') if len(pars) != 3: print(colorize(_("Missing parameter"), ERROR_COLOR)) return filename = pars[1] defname = pars[2] try: ui.store(filename, defname) except Exception as e: print(colorize(e, ERROR_COLOR)) else: exec_query(command) def replacements(query: str) -> str: '''This funcion replaces ascii easy operators with the correct ones''' rules = ( ('_PRODUCT', parser.PRODUCT), ('_UNION', parser.UNION), ('_INTERSECTION', parser.INTERSECTION), ('_DIFFERENCE', parser.DIFFERENCE), ('_JOIN', parser.JOIN), ('_LJOIN', parser.JOIN_LEFT), ('_RJOIN', parser.JOIN_RIGHT), ('_FJOIN', parser.JOIN_FULL), ('_PROJECTION', parser.PROJECTION), ('_RENAME_TO', parser.ARROW), ('_SELECTION', parser.SELECTION), ('_RENAME', parser.RENAME), ('_DIVISION', parser.DIVISION), ) for asciiop, op in rules: query = query.replace(asciiop, op) return query def exec_query(command: str) -> None: ''' Executes a query and prints the result on the screen if the command terminates with ";" the result will not be printed. Updates the set of relations. ''' # 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(ui.relations) printtty(colorize("-> query: %s" % pyquery, COLOR_GREEN)) if printrel: print() print(result.pretty_string(tty=True)) ui.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, None) 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/__init__.py0000664000175000017500000000000014647215100020340 0ustar salvosalvorelational/relational.desktop0000664000175000017500000000055214647215100015773 0ustar salvosalvo[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/COPYING0000664000175000017500000010451314647215100013303 0ustar salvosalvo 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/requirements.txt0000664000175000017500000000003314647215100015524 0ustar salvosalvotypedload pyqt6 xtermcolor relational/relational-cli.10000664000175000017500000000245414647215100015232 0ustar salvosalvo.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/setup/0000775000175000017500000000000014647215100013404 5ustar salvosalvorelational/setup/installer_common.py0000664000175000017500000000220214647215100017317 0ustar salvosalvo# Relational # Copyright (C) 2008-2024 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 setuptools import setup def c_setup(name): setup( version='3.3', name=name, packages=(name,), author="Salvo 'LtWorf' Tomaselli", author_email='tiposchi@tiscali.it', maintainer="Salvo 'LtWorf' Tomaselli", maintainer_email='tiposchi@tiscali.it', url='https://ltworf.codeberg.page/relational/', license='GPL3', ) relational/setup/relational-cli.setup.py0000664000175000017500000000152714647215100020021 0ustar salvosalvo# -*- 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/setup/relational.setup.py0000664000175000017500000000147214647215100017253 0ustar salvosalvo# 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/python3-relational.setup.py0000664000175000017500000000151614647215100020654 0ustar salvosalvo# -*- 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/tests_dir/0000775000175000017500000000000014647215100014244 5ustar salvosalvorelational/tests_dir/people_fjoin_personroom.result0000664000175000017500000000037014647215100022440 0ustar salvosalvo{"content": [[5, "duncan", 4, 30, 1], [4, "eve", 0, 25, 5], [0, "jack", 0, 22, 1], [2, "john", 1, 30, 2], [1, "carl", 0, 20, 4], [6, "paul", 4, 30, 5], [7, "alia", 1, 28, 1], [3, "dean", 1, 33, 2]], "header": ["id", "name", "chief", "age", "room"]}relational/tests_dir/subtraction2.result0000664000175000017500000000007114647215100020121 0ustar salvosalvo{"content": [], "header": ["id", "name", "chief", "age"]}relational/tests_dir/subtraction1.query0000664000175000017500000000004014647215100017743 0ustar salvosalvopeople - σ name=='eve'(people) relational/tests_dir/select_join_opt.result0000664000175000017500000000016114647215100020662 0ustar salvosalvo{"content": [[4, "eve", 0, 25, "C"], [0, "jack", 0, 22, "C"]], "header": ["id", "name", "chief", "age", "skill"]}relational/tests_dir/c_not_python.result0000664000175000017500000000010014647215100020176 0ustar salvosalvo{"content": [["eve"], ["john"], ["duncan"]], "header": ["name"]}relational/tests_dir/people_join_personroom.query0000664000175000017500000000002514647215100022116 0ustar salvosalvopeople⋈person_room relational/tests_dir/swap_fields.result0000664000175000017500000000033014647215100020000 0ustar salvosalvo{"content": [[1, "carl", 0, 20], [2, "john", 1, 30], [3, "dean", 1, 33], [5, "duncan", 4, 30], [0, "jack", 0, 22], [4, "eve", 0, 25], [6, "paul", 4, 30], [7, "alia", 1, 28]], "header": ["id", "name", "chief", "age"]}relational/tests_dir/commutative_fail_union2.fail0000664000175000017500000000005014647215100021716 0ustar salvosalvo(people⋈skills) ∪ π name (people) relational/tests_dir/younger.query0000664000175000017500000000011614647215100017021 0ustar salvosalvopeople-π id,name,chief,age(σ age>a(π a(ρ id➡i,age➡a(people))*people)) relational/tests_dir/people.query0000664000175000017500000000000714647215100016614 0ustar salvosalvopeople relational/tests_dir/people_rename_select.result0000664000175000017500000000020514647215100021653 0ustar salvosalvo{"content": [[4, "eve", 0, 25], [6, "paul", 4, 30], [2, "john", 1, 30], [0, "jack", 0, 22]], "header": ["i", "name", "chief", "age"]}relational/tests_dir/name_age.result0000664000175000017500000000023114647215100017234 0ustar salvosalvo{"content": [["eve", 25], ["duncan", 30], ["paul", 30], ["carl", 20], ["alia", 28], ["dean", 33], ["jack", 22], ["john", 30]], "header": ["name", "age"]}relational/tests_dir/people_join_rooms.query0000664000175000017500000000003714647215100021055 0ustar salvosalvopeople⧓person_room ⧓ rooms relational/tests_dir/union2.result0000664000175000017500000000033014647215100016712 0ustar salvosalvo{"content": [[1, "carl", 0, 20], [2, "john", 1, 30], [3, "dean", 1, 33], [5, "duncan", 4, 30], [0, "jack", 0, 22], [4, "eve", 0, 25], [6, "paul", 4, 30], [7, "alia", 1, 28]], "header": ["id", "name", "chief", "age"]}relational/tests_dir/dates.result0000664000175000017500000000035614647215100016610 0ustar salvosalvo{"content": [[{"day": 12, "year": 2008, "month": 12}], [{"day": 9, "year": 1985, "month": 5}], [{"day": 21, "year": 1988, "month": 4}], [{"day": 27, "year": 1992, "month": 7}], [{"day": 12, "year": 2007, "month": 8}]], "header": ["date"]}relational/tests_dir/union_and_select.result0000664000175000017500000000010614647215100021012 0ustar salvosalvo{"content": [[2, "C"], [0, "C"], [4, "C"]], "header": ["id", "skill"]}relational/tests_dir/10.fail0000664000175000017500000000001714647215100015317 0ustar salvosalvopeople - skillsrelational/tests_dir/pswap.result0000664000175000017500000000000514647215100016631 0ustar salvosalvoTrue relational/tests_dir/union4.query0000664000175000017500000000003514647215100016545 0ustar salvosalvopeople ∪ people ∩ people relational/tests_dir/php.query0000664000175000017500000000005714647215100016124 0ustar salvosalvoσ age<30 and skill=='PHP' (people ⋈ skills) relational/tests_dir/java_and_perl.result0000664000175000017500000000006614647215100020273 0ustar salvosalvo{"content": [["eve"], ["duncan"]], "header": ["name"]}relational/tests_dir/skill_of_best_person.query0000664000175000017500000000017014647215100021536 0ustar salvosalvoπname,age,skill((ratings-πid,rating(σ r>rating (ρrating➡r(πrating(ratings )) * ratings)) ⋈ people) ⋈ skills) relational/tests_dir/rel_eq.result0000664000175000017500000000000614647215100016747 0ustar salvosalvoFalse relational/tests_dir/pswap.python0000664000175000017500000000006514647215100016642 0ustar salvosalvopeople.projection("name","id","age","chief")==people relational/tests_dir/commutative_fail_union1.fail0000664000175000017500000000004514647215100021721 0ustar salvosalvoπ name (people)∪(people⋈skills) relational/tests_dir/select_people_join_rooms.query0000664000175000017500000000005714647215100022416 0ustar salvosalvoσ id is None (people⧓person_room ⧓ rooms) relational/tests_dir/full_join.result0000664000175000017500000000106514647215100017467 0ustar salvosalvo{"content": [[7, "C", "alia", 1, 28], [2, "PHP", "john", 1, 30], [4, "C++", "eve", 0, 25], [7, "Python", "alia", 1, 28], [6, null, "paul", 4, 30], [0, "Python", "jack", 0, 22], [2, "C", "john", 1, 30], [1, "Python", "carl", 0, 20], [1, "System Admin", "carl", 0, 20], [3, "C++", "dean", 1, 33], [5, "Perl", "duncan", 4, 30], [5, "C", "duncan", 4, 30], [7, "PHP", "alia", 1, 28], [1, "C++", "carl", 0, 20], [0, "C", "jack", 0, 22], [9, "Java", null, null, null], [4, "C", "eve", 0, 25], [4, "Perl", "eve", 0, 25]], "header": ["id", "skill", "name", "chief", "age"]} relational/tests_dir/phones_of_people_with_personal_room.result0000664000175000017500000000007214647215100025021 0ustar salvosalvo{"content": [[1041, "carl"]], "header": ["phone", "name"]}relational/tests_dir/9.fail0000664000175000017500000000002114647215100015242 0ustar salvosalvoskills ∩ peoplerelational/tests_dir/a_joinf_a.query0000664000175000017500000000002014647215100017230 0ustar salvosalvopeople⧓people relational/tests_dir/par1.query0000664000175000017500000000002614647215100016174 0ustar salvosalvoσ name=='(' (people) relational/tests_dir/people_join_personroom.result0000664000175000017500000000037014647215100022272 0ustar salvosalvo{"content": [[5, "duncan", 4, 30, 1], [4, "eve", 0, 25, 5], [0, "jack", 0, 22, 1], [2, "john", 1, 30, 2], [1, "carl", 0, 20, 4], [6, "paul", 4, 30, 5], [7, "alia", 1, 28, 1], [3, "dean", 1, 33, 2]], "header": ["id", "name", "chief", "age", "room"]}relational/tests_dir/a_join_a.query0000664000175000017500000000002014647215100017062 0ustar salvosalvopeople⋈people relational/tests_dir/people_join_rooms.result0000664000175000017500000000067614647215100021237 0ustar salvosalvo{"content": [[0, "jack", 0, 22, 1, 1516], [null, null, null, null, 6, 1424], [null, null, null, null, 3, 1601], [7, "alia", 1, 28, 1, 1516], [2, "john", 1, 30, 2, 1617], [3, "dean", 1, 33, 2, 1617], [5, "duncan", 4, 30, 1, 1516], [4, "eve", 0, 25, 5, 9212], [1, "carl", 0, 20, 4, 1041], [null, null, null, null, 0, 1515], [null, null, null, null, 7, 1294], [6, "paul", 4, 30, 5, 9212]], "header": ["id", "name", "chief", "age", "room", "phone"]} relational/tests_dir/union_join.result0000664000175000017500000000036714647215100017661 0ustar salvosalvo{"content": [[4, "eve", 0, 25, "C"], [5, "duncan", 4, 30, "C"], [0, "jack", 0, 22, "C"], [5, "duncan", 4, 30, "Perl"], [2, "john", 1, 30, "C"], [7, "alia", 1, 28, "C"], [4, "eve", 0, 25, "Perl"]], "header": ["id", "name", "chief", "age", "skill"]}relational/tests_dir/union_join.query0000664000175000017500000000011514647215100017477 0ustar salvosalvopeople⋈σ skill == 'Perl' (skills) ∪ (people⋈σ skill == 'C' (skills)) relational/tests_dir/quot1.query0000664000175000017500000000002514647215100016401 0ustar salvosalvoσ id=='\'' (people) relational/tests_dir/full_join.query0000664000175000017500000000002114647215100017305 0ustar salvosalvopeople ⧓skills relational/tests_dir/union4.result0000664000175000017500000000033014647215100016714 0ustar salvosalvo{"content": [[1, "carl", 0, 20], [2, "john", 1, 30], [3, "dean", 1, 33], [5, "duncan", 4, 30], [0, "jack", 0, 22], [4, "eve", 0, 25], [6, "paul", 4, 30], [7, "alia", 1, 28]], "header": ["id", "name", "chief", "age"]}relational/tests_dir/left_join.result0000664000175000017500000000102514647215100017453 0ustar salvosalvo{"content": [[2, "john", 1, 30, "PHP"], [5, "duncan", 4, 30, "Perl"], [2, "john", 1, 30, "C"], [6, "paul", 4, 30, null], [4, "eve", 0, 25, "Perl"], [1, "carl", 0, 20, "System Admin"], [3, "dean", 1, 33, "C++"], [4, "eve", 0, 25, "C++"], [1, "carl", 0, 20, "C++"], [1, "carl", 0, 20, "Python"], [0, "jack", 0, 22, "Python"], [7, "alia", 1, 28, "Python"], [5, "duncan", 4, 30, "C"], [7, "alia", 1, 28, "PHP"], [4, "eve", 0, 25, "C"], [0, "jack", 0, 22, "C"], [7, "alia", 1, 28, "C"]], "header": ["id", "name", "chief", "age", "skill"]}relational/tests_dir/par2.query0000664000175000017500000000003014647215100016170 0ustar salvosalvoσ (name=='(') (people) relational/tests_dir/18.fail0000664000175000017500000000002014647215100015321 0ustar salvosalvoskills ÷ peoplerelational/tests_dir/redoundant_union_select.query0000664000175000017500000000005214647215100022242 0ustar salvosalvoσ (id==2) (σ age>5 (people ∪ people)) relational/tests_dir/union1.result0000664000175000017500000000016214647215100016714 0ustar salvosalvo{"content": [[4, "eve", 0, 25], [0, "jack", 0, 22], [7, "alia", 1, 28]], "header": ["id", "name", "chief", "age"]}relational/tests_dir/5.fail0000664000175000017500000000001514647215100015241 0ustar salvosalvopeople*peoplerelational/tests_dir/swap_fields.query0000664000175000017500000000003714647215100017633 0ustar salvosalvoπ name,id,age,chief (people) relational/tests_dir/select_join_opt.query0000664000175000017500000000012314647215100020507 0ustar salvosalvoσ skill=='C' and chief==0 ((σ age<30 (people) ∪ σ age>40(people)) ⋈ skills) relational/tests_dir/fixed_len_name.result0000664000175000017500000000056514647215100020447 0ustar salvosalvo{"content": [[3, "dean", 1, 33, "C++"], [2, "john", 1, 30, "PHP"], [1, "carl", 0, 20, "C++"], [1, "carl", 0, 20, "Python"], [2, "john", 1, 30, "C"], [0, "jack", 0, 22, "Python"], [7, "alia", 1, 28, "Python"], [7, "alia", 1, 28, "PHP"], [1, "carl", 0, 20, "System Admin"], [0, "jack", 0, 22, "C"], [7, "alia", 1, 28, "C"]], "header": ["id", "name", "chief", "age", "skill"]}relational/tests_dir/python_and_c.query0000664000175000017500000000014014647215100017773 0ustar salvosalvoπname (σ skill=='C' (people ⋈ skills)) ∩ π name (σ skill=='Python' (people ⋈ skills)) relational/tests_dir/older_than_boss.result0000664000175000017500000000033614647215100020653 0ustar salvosalvo{"content": [["dean", 33, "carl", 20], ["duncan", 30, "eve", 25], ["john", 30, "carl", 20], ["alia", 28, "carl", 20], ["eve", 25, "jack", 22], ["paul", 30, "eve", 25]], "header": ["name", "age", "chief_name", "chief_age"]}relational/tests_dir/join.query0000664000175000017500000000002214647215100016264 0ustar salvosalvopeople ⋈ skills relational/tests_dir/4.fail0000664000175000017500000000001114647215100015234 0ustar salvosalvo((people)relational/tests_dir/select_join.result0000664000175000017500000000013314647215100017777 0ustar salvosalvo{"content": [[3, "C++", "dean", 1, 33]], "header": ["id", "skill", "name", "chief", "age"]}relational/tests_dir/a_joinr_a.query0000664000175000017500000000002014647215100017244 0ustar salvosalvopeople⧒people relational/tests_dir/23.fail0000664000175000017500000000003714647215100015325 0ustar salvosalvopeople ∪ (ratings ⋈ people)relational/tests_dir/dates_sel.result0000664000175000017500000000016414647215100017450 0ustar salvosalvo{"content": [[{"day": 12, "year": 2008, "month": 12}], [{"day": 12, "year": 2007, "month": 8}]], "header": ["date"]}relational/tests_dir/select_people_join_rooms.result0000664000175000017500000000032414647215100022564 0ustar salvosalvo{"content": [[null, null, null, null, 0, 1515], [null, null, null, null, 7, 1294], [null, null, null, null, 3, 1601], [null, null, null, null, 6, 1424]], "header": ["id", "name", "chief", "age", "room", "phone"]}relational/tests_dir/c_programmers.result0000664000175000017500000000027614647215100020351 0ustar salvosalvo{"content": [[5, "duncan", 4, 30, "C"], [0, "jack", 0, 22, "C"], [4, "eve", 0, 25, "C"], [2, "john", 1, 30, "C"], [7, "alia", 1, 28, "C"]], "header": ["id", "name", "chief", "age", "skill"]}relational/tests_dir/union_or_select.result0000664000175000017500000000013714647215100020674 0ustar salvosalvo{"content": [[3, "dean", 1, 33], [1, "carl", 0, 20]], "header": ["id", "name", "chief", "age"]}relational/tests_dir/size.py0000664000175000017500000000006714647215100015573 0ustar salvosalvoassert len(people) == 8 assert len(people.header) == 4 relational/tests_dir/union1.query0000664000175000017500000000007014647215100016541 0ustar salvosalvoσ age<30 (σ (id%2==0) (people) ∪ σ age>22(people)) relational/tests_dir/multiline_optimization.py0000664000175000017500000000041214647215100021423 0ustar salvosalvofrom relational.optimizer import optimize_program a = optimize_program('''ppl_skills = people ⧓skills ppl_skills1 = ppl_skills ∪ (people ⧓skills) ppl_skills ∩ ppl_skills1 ⧓ dates''', {}) assert a == '''optm_a = people⧓skills optm_b = optm_a⧓dates''' relational/tests_dir/phones_of_people_with_personal_room.query0000664000175000017500000000023614647215100024652 0ustar salvosalvoπname,phone(((πname,id(people)- π name,id(πid(σ i!=id and room==r(ρ id➡i,room➡r(person_room)*person_room)) ⋈ people)) ⋈ person_room) ⋈ rooms) relational/tests_dir/skill_of_best_person.result0000664000175000017500000000015414647215100021711 0ustar salvosalvo{"content": [["eve", 25, "C++"], ["eve", 25, "C"], ["eve", 25, "Perl"]], "header": ["name", "age", "skill"]}relational/tests_dir/11.fail0000664000175000017500000000001714647215100015320 0ustar salvosalvoskills - peoplerelational/tests_dir/par4.result0000664000175000017500000000007114647215100016350 0ustar salvosalvo{"content": [], "header": ["id", "name", "chief", "age"]}relational/tests_dir/right_join.query0000664000175000017500000000002214647215100017461 0ustar salvosalvopeople ⧒ skills relational/tests_dir/a_joinl_a.result0000664000175000017500000000033014647215100017413 0ustar salvosalvo{"content": [[1, "carl", 0, 20], [2, "john", 1, 30], [3, "dean", 1, 33], [5, "duncan", 4, 30], [0, "jack", 0, 22], [4, "eve", 0, 25], [6, "paul", 4, 30], [7, "alia", 1, 28]], "header": ["id", "name", "chief", "age"]}relational/tests_dir/par3.result0000664000175000017500000000007114647215100016347 0ustar salvosalvo{"content": [], "header": ["id", "name", "chief", "age"]}relational/tests_dir/union_not_select.result0000664000175000017500000000007414647215100021054 0ustar salvosalvo{"content": [[7, "C"], [5, "C"]], "header": ["id", "skill"]}relational/tests_dir/14.fail0000664000175000017500000000001314647215100015317 0ustar salvosalvoπ (people)relational/tests_dir/join.result0000664000175000017500000000077314647215100016452 0ustar salvosalvo{"content": [[2, "john", 1, 30, "PHP"], [5, "duncan", 4, 30, "Perl"], [2, "john", 1, 30, "C"], [4, "eve", 0, 25, "Perl"], [1, "carl", 0, 20, "System Admin"], [3, "dean", 1, 33, "C++"], [4, "eve", 0, 25, "C++"], [1, "carl", 0, 20, "C++"], [1, "carl", 0, 20, "Python"], [0, "jack", 0, 22, "Python"], [7, "alia", 1, 28, "Python"], [5, "duncan", 4, 30, "C"], [7, "alia", 1, 28, "PHP"], [4, "eve", 0, 25, "C"], [0, "jack", 0, 22, "C"], [7, "alia", 1, 28, "C"]], "header": ["id", "name", "chief", "age", "skill"]}relational/tests_dir/fake_union.fail0000664000175000017500000000010414647215100017212 0ustar salvosalvoρ name➡n,age➡a(σTrue(people)) ᑌ ρ age➡a,name➡n(people) relational/tests_dir/a_join_a.result0000664000175000017500000000033014647215100017237 0ustar salvosalvo{"content": [[1, "carl", 0, 20], [2, "john", 1, 30], [3, "dean", 1, 33], [5, "duncan", 4, 30], [0, "jack", 0, 22], [4, "eve", 0, 25], [6, "paul", 4, 30], [7, "alia", 1, 28]], "header": ["id", "name", "chief", "age"]}relational/tests_dir/7.fail0000664000175000017500000000002114647215100015240 0ustar salvosalvoskills ∪ peoplerelational/tests_dir/intersection1.result0000664000175000017500000000011214647215100020265 0ustar salvosalvo{"content": [[4, "eve", 0, 25]], "header": ["id", "name", "chief", "age"]}relational/tests_dir/younger.result0000664000175000017500000000011314647215100017167 0ustar salvosalvo{"content": [[1, 20, 0, "carl"]], "header": ["id", "age", "chief", "name"]}relational/tests_dir/intersection2.result0000664000175000017500000000011214647215100020266 0ustar salvosalvo{"content": [[4, "eve", 0, 25]], "header": ["id", "name", "chief", "age"]}relational/tests_dir/union_or_select.query0000664000175000017500000000005114647215100020516 0ustar salvosalvoσ age<21 (people) ∪ σage >30(people) relational/tests_dir/17.fail0000664000175000017500000000001714647215100015326 0ustar salvosalvopeople * skillsrelational/tests_dir/15.fail0000664000175000017500000000001014647215100015315 0ustar salvosalvoπpeoplerelational/tests_dir/1.fail0000664000175000017500000000000214647215100015231 0ustar salvosalvo((relational/tests_dir/redoundant_union_select.result0000664000175000017500000000011314647215100022411 0ustar salvosalvo{"content": [[2, "john", 1, 30]], "header": ["id", "name", "chief", "age"]}relational/tests_dir/subtraction2.query0000664000175000017500000000003114647215100017744 0ustar salvosalvoσ age>15(people)-people relational/tests_dir/par1.result0000664000175000017500000000007114647215100016345 0ustar salvosalvo{"content": [], "header": ["id", "name", "chief", "age"]}relational/tests_dir/people_fjoin_personroom.query0000664000175000017500000000002514647215100022264 0ustar salvosalvopeople⧓person_room relational/tests_dir/8.fail0000664000175000017500000000002114647215100015241 0ustar salvosalvopeople ∩ skillsrelational/tests_dir/union_not_select.query0000664000175000017500000000005414647215100020701 0ustar salvosalvoσ skill=='C' (skills) - σ id%2==0(skills) relational/tests_dir/2.fail0000664000175000017500000000000114647215100015231 0ustar salvosalvo)relational/tests_dir/people_rename.result0000664000175000017500000000032314647215100020315 0ustar salvosalvo{"content": [[1, "carl", 0, 20], [2, "john", 1, 30], [3, "dean", 1, 33], [5, "duncan", 4, 30], [0, "jack", 0, 22], [4, "eve", 0, 25], [6, "paul", 4, 30], [7, "alia", 1, 28]], "header": ["id", "n", "chief", "a"]}relational/tests_dir/union_projection.result0000664000175000017500000000023314647215100021066 0ustar salvosalvo{"content": [["jack", "C"], ["eve", "C"], ["duncan", "C"], ["alia", "C"], ["eve", "Perl"], ["duncan", "Perl"], ["john", "C"]], "header": ["name", "skill"]}relational/tests_dir/right_join.result0000664000175000017500000000103314647215100017635 0ustar salvosalvo{"content": [[7, "C", "alia", 1, 28], [2, "PHP", "john", 1, 30], [4, "C++", "eve", 0, 25], [7, "Python", "alia", 1, 28], [0, "Python", "jack", 0, 22], [2, "C", "john", 1, 30], [1, "Python", "carl", 0, 20], [1, "System Admin", "carl", 0, 20], [3, "C++", "dean", 1, 33], [5, "Perl", "duncan", 4, 30], [5, "C", "duncan", 4, 30], [7, "PHP", "alia", 1, 28], [1, "C++", "carl", 0, 20], [0, "C", "jack", 0, 22], [9, "Java", null, null, null], [4, "C", "eve", 0, 25], [4, "Perl", "eve", 0, 25]], "header": ["id", "skill", "name", "chief", "age"]} relational/tests_dir/a_joinl_a.query0000664000175000017500000000002014647215100017236 0ustar salvosalvopeople⧑people relational/tests_dir/union3.result0000664000175000017500000000033014647215100016713 0ustar salvosalvo{"content": [[1, "carl", 0, 20], [2, "john", 1, 30], [3, "dean", 1, 33], [5, "duncan", 4, 30], [0, "jack", 0, 22], [4, "eve", 0, 25], [6, "paul", 4, 30], [7, "alia", 1, 28]], "header": ["id", "name", "chief", "age"]}relational/tests_dir/20.fail0000664000175000017500000000001014647215100015311 0ustar salvosalvo"people"relational/tests_dir/12.fail0000664000175000017500000000002114647215100015314 0ustar salvosalvoρ i➡id(people)relational/tests_dir/0.fail0000664000175000017500000000001514647215100015234 0ustar salvosalvoσ , (people)relational/tests_dir/maxdate.query0000664000175000017500000000006214647215100016754 0ustar salvosalvodates-πdate(σ d>date (ρdate➡d(dates)*dates)) relational/tests_dir/select_join.query0000664000175000017500000000003414647215100017626 0ustar salvosalvoσ id==3(people ⧓ skills) relational/tests_dir/22.fail0000664000175000017500000000003514647215100015322 0ustar salvosalvoratings ⋈ people ∪ peoplerelational/tests_dir/union_and_select.query0000664000175000017500000000005614647215100020645 0ustar salvosalvoσ skill=='C'(skills) ∩ σ id%2==0 (skills) relational/tests_dir/union3.query0000664000175000017500000000004314647215100016543 0ustar salvosalvoσ name=='eve' (people) ∪ people relational/tests_dir/19.fail0000664000175000017500000000000414647215100015324 0ustar salvosalvopeplrelational/tests_dir/dates_sel.query0000664000175000017500000000005514647215100017276 0ustar salvosalvoσ date.year>2000 and date.day+10<30 (dates) relational/tests_dir/21.fail0000664000175000017500000000000314647215100015314 0ustar salvosalvoa+brelational/tests_dir/6.fail0000664000175000017500000000002114647215100015237 0ustar salvosalvopeople ∪ skillsrelational/tests_dir/par2.result0000664000175000017500000000007114647215100016346 0ustar salvosalvo{"content": [], "header": ["id", "name", "chief", "age"]}relational/tests_dir/people_join_select_args_on_both_tables.result0000664000175000017500000000013114647215100025417 0ustar salvosalvo{"content": [[0, "jack", 0, 22, "C"]], "header": ["id", "name", "chief", "age", "skill"]}relational/tests_dir/a_joinf_a.result0000664000175000017500000000033014647215100017405 0ustar salvosalvo{"content": [[1, "carl", 0, 20], [2, "john", 1, 30], [3, "dean", 1, 33], [5, "duncan", 4, 30], [0, "jack", 0, 22], [4, "eve", 0, 25], [6, "paul", 4, 30], [7, "alia", 1, 28]], "header": ["id", "name", "chief", "age"]}relational/tests_dir/people.result0000664000175000017500000000033014647215100016764 0ustar salvosalvo{"content": [[1, "carl", 0, 20], [2, "john", 1, 30], [3, "dean", 1, 33], [5, "duncan", 4, 30], [0, "jack", 0, 22], [4, "eve", 0, 25], [6, "paul", 4, 30], [7, "alia", 1, 28]], "header": ["id", "name", "chief", "age"]}relational/tests_dir/a_joinr_a.result0000664000175000017500000000033014647215100017421 0ustar salvosalvo{"content": [[1, "carl", 0, 20], [2, "john", 1, 30], [3, "dean", 1, 33], [5, "duncan", 4, 30], [0, "jack", 0, 22], [4, "eve", 0, 25], [6, "paul", 4, 30], [7, "alia", 1, 28]], "header": ["id", "name", "chief", "age"]}relational/tests_dir/rel_eq.python0000664000175000017500000000001714647215100016754 0ustar salvosalvopeople=='ciao' relational/tests_dir/people_rename.query0000664000175000017500000000010414647215100020141 0ustar salvosalvoρ name➡n,age➡a(σTrue(people)) ∪ ρ age➡a,name➡n(people) relational/tests_dir/max_rating_in_age_range.query0000664000175000017500000000036214647215100022143 0ustar salvosalvo(σ age<25(people) ∪ σ age>30(people)) ⋈ ratings-πid,name,chief,age,rating(σ rating30(people)) ⋈ ratings))) * (σ age<25(people) ∪ σ age>30(people)) ⋈ ratings)) relational/tests_dir/union_projection.query0000664000175000017500000000014714647215100020721 0ustar salvosalvoπname,skill(σ skill == 'Perl' (people⋈skills)) ∪ πname,skill(σ skill == 'C' (people⋈skills)) relational/tests_dir/fixed_len_name.query0000664000175000017500000000004514647215100020267 0ustar salvosalvoσ (len(name)==4)(people ⋈ skills) relational/tests_dir/par4.query0000664000175000017500000000002614647215100016177 0ustar salvosalvoσ name==')' (people) relational/tests_dir/c_not_python.query0000664000175000017500000000013614647215100020036 0ustar salvosalvoπname (σ skill=='C' (people ⋈ skills)) - π name (σ skill=='Python' (people ⋈ skills)) relational/tests_dir/people_rename_select.query0000664000175000017500000000003714647215100021505 0ustar salvosalvoσ i%2==0 (ρ id➡i (people)) relational/tests_dir/maxdate.result0000664000175000017500000000011314647215100017122 0ustar salvosalvo{"content": [[{"day": 12, "year": 2008, "month": 12}]], "header": ["date"]}relational/tests_dir/par3.query0000664000175000017500000000003014647215100016171 0ustar salvosalvoσ (name==')') (people) relational/tests_dir/java_and_perl.query0000664000175000017500000000014214647215100020115 0ustar salvosalvoπname (σ skill=='Perl' (people ⋈ skills)) ∪ π name (σ skill=='Java' (people ⋈ skills)) relational/tests_dir/php.result0000664000175000017500000000013314647215100016270 0ustar salvosalvo{"content": [[7, "alia", 1, 28, "PHP"]], "header": ["id", "name", "chief", "age", "skill"]}relational/tests_dir/name_age.query0000664000175000017500000000010714647215100017065 0ustar salvosalvoρn➡name,a➡age(πn,a(ρid➡i,name➡n,chief➡c,age➡a(people))) relational/tests_dir/16.fail0000664000175000017500000000001714647215100015325 0ustar salvosalvoskills * peoplerelational/tests_dir/subtraction1.result0000664000175000017500000000030514647215100020120 0ustar salvosalvo{"content": [[3, "dean", 1, 33], [5, "duncan", 4, 30], [1, "carl", 0, 20], [0, "jack", 0, 22], [2, "john", 1, 30], [6, "paul", 4, 30], [7, "alia", 1, 28]], "header": ["id", "name", "chief", "age"]}relational/tests_dir/max_rating_in_age_range.result0000664000175000017500000000013014647215100022305 0ustar salvosalvo{"content": [[1, "carl", 0, 20, 6]], "header": ["id", "name", "chief", "age", "rating"]}relational/tests_dir/quot1.result0000664000175000017500000000007114647215100016553 0ustar salvosalvo{"content": [], "header": ["id", "name", "chief", "age"]}relational/tests_dir/python_and_c.result0000664000175000017500000000006514647215100020152 0ustar salvosalvo{"content": [["alia"], ["jack"]], "header": ["name"]}relational/tests_dir/intersection1.query0000664000175000017500000000004314647215100020117 0ustar salvosalvoσ name=='eve' (people) ∩ people relational/tests_dir/c_programmers.query0000664000175000017500000000004114647215100020166 0ustar salvosalvoσ skill=='C'(people ⋈ skills) relational/tests_dir/dates.query0000664000175000017500000000000614647215100016427 0ustar salvosalvodates relational/tests_dir/people_join_select_args_on_both_tables.query0000664000175000017500000000007414647215100025254 0ustar salvosalvoσ skill=='C' and age<25 and skill!=name(people ⋈ skills) relational/tests_dir/13.fail0000664000175000017500000000001714647215100015322 0ustar salvosalvoπ i,id(people)relational/tests_dir/older_than_boss.query0000664000175000017500000000020714647215100020477 0ustar salvosalvoρn➡chief_name,a➡chief_age(πname,age,n,a(σ i==chief and age>a (π i,c,n,a(ρage➡a,id➡i,chief➡c,name➡n(people))*people))) relational/tests_dir/union2.query0000664000175000017500000000004314647215100016542 0ustar salvosalvopeople ∪ σ name=='eve' (people) relational/tests_dir/intersection2.query0000664000175000017500000000004314647215100020120 0ustar salvosalvopeople ∩ σ name=='eve' (people) relational/tests_dir/left_join.query0000664000175000017500000000002114647215100017275 0ustar salvosalvopeople ⧑skills relational/tests_dir/3.fail0000664000175000017500000000001114647215100015233 0ustar salvosalvo(people))relational/SECURITY.md0000664000175000017500000000074014647215100014036 0ustar salvosalvo# Security Policy This project makes heavy use of `eval` and similar concepts. Queries are not meant to come from untrusted sources. My advice is to never run this as an online service. ## Supported Versions Only the latest release is supported. I will not backport fixes. ## Reporting a Vulnerability For vulnerabilities that do not require a compromised user account: contact me at tiposchi@tiscali.it My PGP key is on this file, on git. debian/upstream/signing-key.asc relational/Makefile0000664000175000017500000000703414647215100013710 0ustar salvosalvo.PHONY: all all: gui translations .PHONY: gui gui: relational_gui/survey.py relational_gui/maingui.py relational_gui/rel_edit.py relational_gui/maingui.py relational_gui/survey.py relational_gui/rel_edit.py: relational_gui/maingui.ui relational_gui/rel_edit.ui relational_gui/survey.ui # Create .py file pyuic6 $(basename $@).ui > $@ # Use my custom editor class sed -i 's/QtWidgets.QPlainTextEdit/editor.Editor/g' $@ echo 'from . import editor' >> $@ # Use gettext instead of Qt translations echo 'from gettext import gettext as _' >> $@ sed -i \ -e 's/_translate("MainWindow", /_(/g' \ -e 's/_translate("Dialog", /_(/g' \ -e 's/_translate("Form", /_(/g' \ $@ .PHONY: mypy mypy: mypy relational relational_readline .PHONY: test test: ./driver.py deb-pkg: dist mv relational_*.orig.tar.gz* /tmp cd /tmp; tar -xf relational_*.orig.tar.gz cp -r debian /tmp/relational/ cd /tmp/relational/; dpkg-buildpackage --changes-option=-S mkdir deb-pkg mv /tmp/relational* /tmp/python3-relational_*.deb deb-pkg $(RM) -r /tmp/relational lintian --pedantic -E --color auto -i -I deb-pkg/*changes .PHONY: dist dist: clean $(RM) -r /tmp/relational/ $(RM) -r /tmp/relational-* mkdir /tmp/relational/ cp -R * /tmp/relational/ $(RM) -r /tmp/relational/windows $(RM) -r /tmp/relational/debian/ #mv /tmp/relational /tmp/relational-`head -1 CHANGELOG` #(cd /tmp; tar -zcf relational.tar.gz relational-*/) (cd /tmp; tar -zcf relational.tar.gz relational/) mv /tmp/relational.tar.gz ./relational_`head -1 CHANGELOG`.orig.tar.gz gpg --sign --armor --detach-sign ./relational_`head -1 CHANGELOG`.orig.tar.gz .PHONY: clean clean: $(RM) -r deb-pkg $(RM) -r `find -name "*~"` $(RM) -r `find -name "*pyc"` $(RM) -r `find -name "*pyo"` $(RM) -r relational*.tar.gz $(RM) -r relational*.tar.gz.asc $(RM) -r data $(RM) -r *tar.bz $(RM) -r *.deb $(RM) relational_gui/survey.py $(RM) relational_gui/maingui.py $(RM) relational_gui/rel_edit.py $(RM) po/*.mo $(RM) -r build $(RM) -r *.egg-info .PHONY: install-relational-cli install-relational-cli: python3 setup/relational-cli.setup.py install --root=$${DESTDIR:-/}; $(RM) -r build; install -D relational.py $${DESTDIR:-/}/usr/bin/relational-cli install -D relational-cli.1 $${DESTDIR:-/}/usr/share/man/man1/relational-cli.1 .PHONY: install-python3-relational install-python3-relational: install_translations python3 setup/python3-relational.setup.py install --root=$${DESTDIR:-/}; $(RM) -r build; .PHONY: install-relational install-relational: python3 setup/relational.setup.py install --root=$${DESTDIR:-/}; $(RM) -r build; install -D relational.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 .PHONY: install install: install-relational-cli install-python3-relational install-relational po/messages.pot: relational.py relational/*.py relational_readline/*.py relational_gui/*.py xgettext --from-code=utf-8 -L Python -j -o po/messages.pot --package-name=relational \ relational.py \ relational_readline/*.py \ relational_gui/*.py \ relational/*.py po/it.po: po/messages.pot msgmerge --update $@ po/messages.pot po/it.mo: po/it.po msgfmt po/it.po --output-file $@ .PHONY: translations translations: po/it.mo .PHONY: install_translations install_translations: install -m644 -D po/it.mo $${DESTDIR:-/}/usr/share/locale/it/LC_MESSAGES/relational.mo relational/driver.py0000775000175000017500000002057114647215100014121 0ustar salvosalvo#!/usr/bin/env python3 # Relational # Copyright (C) 2010-2020 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 = 'tests_dir/' def readfile(fname): '''Reads a file as string and returns its content''' with open(fname, encoding='utf-8') as fd: expr = fd.read() 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.load_csv('%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)) exp_result = None result = None 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.pretty_string(tty=True)) print("Got %s" % result.pretty_string(tty=True)) 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.load('%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.pretty_string(tty=True)) print(colorize("Result", COLOR_RED)) print(result.pretty_string(tty=True)) print(colorize("Optimized result", COLOR_RED)) print(o_result.pretty_string(tty=True)) 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/CODE_OF_CONDUCT.md0000664000175000017500000000634614647215100015054 0ustar salvosalvoInternational code of conduct ============================= No USA cultural imperialism allowed ----------------------------------- This project welcomes every contributor from any background. For this reason we can't let the USA and USA influenced politically correct culture dictate conduct for everyone. Diversity is beautiful, let's not ask of people to forgo their culture to contribute. Achieving social justice is important. Being superficial about it only to feel morally superior is not the way to achieve it and is not tolerated here. The code of conduct only pertains this project ---------------------------------------------- This document only applies to the project and the communication channels. It does not apply to anything any contributor might say or do outside of project channels. It only applies to contributors. People whose only contribution is a code of conduct complaint are not contributors. Language -------- Try to be nice and constructive. Harassing and intentionally offending other people is not allowed. Foul language is allowed. People often contribute to this project in their own time and are not paid, for this reason asking contributors to behave "professionally" makes no sense. Hobbies do not require professionality. Jokes are allowed. It can happen to unintentionally offend someone. Do not reiterate the offensive behaviour, provided that the request is reasonable. People who are easily offended by things not intended to be offensive must try to become more tolerant towards other people, other cultures and their ways of expressing themselves. For example, a person might consider offensive the sight of a woman with or without a headscarf. This person needs to try to become more tolerant to other people's culture. It is not allowed to be offended on behalf of others. Please do not presume to know what others are thinking. Examples of allowed language: * This software is retarded * This program runs like shit * This bug is annoying Examples of disallowed language: * You are retarded * You are shitty and so is your program Skill discrimination is absolutely fine --------------------------------------- Unlike other code of conducts, this allows skill discrimination. Everyone is welcome to contribute according to their skill level and more experienced contributors are encouraged to act as mentors. It is nice if they have time and patience to mentor potential contributors, but since time is a limited resource, it is also fine to turn down low quality and low effort contributions with little explaination. New contributors are expected to respond to comments and be willing to improve the quality of their contribution. Conflict resolution ------------------- This code of conduct is inevitably vague. Follow the intention rather than the letter. The final word rests with the project owners or their delegates. Changes to license ------------------ It is not allowed to ask for license change and complain about copyleft. If you disagree with the license, feel free to start your own project from scratch without getting in touch and never look at the source code, to avoid copyright issues. See also -------- * [International code of conduct](https://codeberg.org/ltworf/international_code_of_conduct) relational/samples/0000775000175000017500000000000014647215100013710 5ustar salvosalvorelational/samples/people.csv0000664000175000017500000000016314647215100015711 0ustar salvosalvoid,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/dates.csv0000664000175000017500000000010514647215100015521 0ustar salvosalvo"date" "2008-12-12" "2007-08-12" "1985-05-09" "1988-4-21" "1992-7-27"relational/samples/rooms.csv0000664000175000017500000000014614647215100015565 0ustar salvosalvo"room","phone" "0","1515" "1","1516" "2","1617" "3","1601" "4","1041" "5","9212" "6","1424" "7","1294"relational/samples/person_room.csv0000664000175000017500000000011314647215100016762 0ustar salvosalvo"id","room" "0","1" "1","4" "2","2" "3","2" "4","5" "5","1" "6","5" "7","1"relational/samples/ratings.csv0000664000175000017500000000007014647215100016071 0ustar salvosalvoid,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/samples/skills.csv0000664000175000017500000000030214647215100015721 0ustar salvosalvo"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/po/0000775000175000017500000000000014647215100012662 5ustar salvosalvorelational/po/it.po0000664000175000017500000004672614647215100013655 0ustar salvosalvo# Header entry was created by Lokalize. # # Salvo Tomaselli , 2020, 2024. msgid "" msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-07-21 15:43+0200\n" "PO-Revision-Date: 2024-07-21 15:53+0200\n" "Last-Translator: Salvo Tomaselli \n" "Language-Team: Italian \n" "Language: it\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "X-Generator: Lokalize 22.12.3\n" #: relational.py:37 msgid "" "Copyright (C) 2008-2020 Salvo 'LtWorf' Tomaselli.\n" "\n" "This program comes with ABSOLUTELY NO WARRANTY.\n" "This is free software, and you are welcome to redistribute it\n" "under certain conditions.\n" "For details see the GPLv3 Licese.\n" "\n" "Written by Salvo 'LtWorf' Tomaselli \n" "\n" "https://ltworf.codeberg.pages/relational/" msgstr "" #: relational.py:56 msgid " -v Print version and exits" msgstr " -v mostra le informazioni sulla versione ed esce" #: relational.py:57 msgid " -h Print this help and exits" msgstr " -h mostra questo aiuto ed esce" #: relational.py:58 msgid " -q Uses Qt user interface" msgstr " -q Usa l'interfaccia Qt" #: relational.py:59 msgid " -r Uses readline user interface" msgstr " -r Usa l'interfaccia readline" #: relational.py:92 msgid "" "Module relational_gui is missing.\n" "Please install relational package or run make." msgstr "" "Il modulo relational_gui manca. Installare il pacchetto relational o " "eseguire make." #: relational.py:128 msgid "" "Module relational_readline is missing.\n" "Please install relational-cli package." msgstr "" "Il modulo relational_readline manca. Installare il pacchetto relational-cli." #: relational_readline/linegui.py:126 #, python-format msgid "%s is not a file" msgstr "%s non è un file" #: relational_readline/linegui.py:137 #, python-format msgid "%s is not a valid relation name" msgstr "%s non è un nome valido per una relazione" #: relational_readline/linegui.py:143 #, python-format msgid "Loaded relation %s" msgstr "Relazione caricata %s" #: relational_readline/linegui.py:161 relational_gui/surveyForm.py:92 msgid "Yeah, not sending that." msgstr "Non manderò questo." #: relational_readline/linegui.py:169 msgid "" "HELP [command]\n" "\n" "Comments are obtained starting with a ;\n" "\n" "To execute a query:\n" "[relation =] query\n" "\n" "If the 1st part is omitted, the result will be stored in the relation " "last_.\n" "\n" "To prevent from printing the relation, append a ; to the end of the query.\n" "\n" "To insert relational operators, type _OPNAME, they will be internally " "replaced with the correct symbol.\n" "\n" "Rember: completion is enabled and can be very helpful if you can't remember " "something." msgstr "" "HELP [comando] I commenti si ottengono iniziando una riga con ; Per eseguire " "una query: [relazione =] query Se la prima parte è omessa, il risultato " "verrà salvato nella relazione last_. Per non stampare la relazione, " "aggiungere un ; alla fine della query. Per inserire gli operatori " "relazionali, scrivere _NOMEOP, questi saranno internamente sostituiti dal " "simbolo corretto. Ricordare: Il completamento è abilitato e può essere utile " "se non si ricorda qualcosa." #: relational_readline/linegui.py:188 msgid "Quits the program" msgstr "Termina il programma" #: relational_readline/linegui.py:189 msgid "Lists the relations loaded" msgstr "Elenca le relazioni caricate" #: relational_readline/linegui.py:190 msgid "" "LOAD filename [relationame]\n" "Loads a relation into memory" msgstr "LOAD nomefile {nomerelazione} Carica una relazione in memoria" #: relational_readline/linegui.py:191 msgid "" "UNLOAD relationame\n" "Unloads a relation from memory" msgstr "UNLOAD nomerelazione Rimuove una relazione dalla memoria" #: relational_readline/linegui.py:192 msgid "" "SAVE filename relationame\n" "Saves a relation in a file" msgstr "SAVE nomefile nomerelazione Salva la relazione in un file" #: relational_readline/linegui.py:193 msgid "Prints the help on a command" msgstr "Stampa la guida di un comando" #: relational_readline/linegui.py:194 msgid "Fill and send a survey" msgstr "Compila e invia un sondaggio" #: relational_readline/linegui.py:196 #, python-format msgid "Unknown command: %s" msgstr "Comando sconosciuto: %s" #: relational_readline/linegui.py:222 relational_readline/linegui.py:234 #: relational_readline/linegui.py:245 msgid "Missing parameter" msgstr "Parametro mancante" #: relational_readline/linegui.py:236 msgid "Too many parameter" msgstr "Troppi parametri" #: relational_readline/linegui.py:241 #, python-format msgid "No such relation %s" msgstr "Nessuna relazione %s" #: relational_readline/linegui.py:322 msgid "; Type HELP to get the HELP" msgstr "; Scrivere HELP per leggere la guida" #: relational_readline/linegui.py:324 msgid "; Completion is activated using the tab (if supported by the terminal)" msgstr "" "; Il completamento è attivato con il tasto tab (se il terminale lo supporta)" #: relational_gui/creator.py:91 relational_gui/creator.py:102 #: relational_gui/guihandler.py:283 relational_gui/guihandler.py:315 #: relational_gui/guihandler.py:325 relational_gui/guihandler.py:342 #: relational_gui/surveyForm.py:94 relational_gui/guihandler.py:289 #: relational_gui/guihandler.py:321 relational_gui/guihandler.py:331 #: relational_gui/guihandler.py:348 msgid "Error" msgstr "Errore" #: relational_gui/creator.py:92 msgid "Header error!" msgstr "Errore nell'header!" #: relational_gui/creator.py:102 #, python-format msgid "Unset value in %d,%d!" msgstr "Valore non impostato in %d,%d!" #: relational_gui/guihandler.py:119 relational_gui/guihandler.py:125 msgid "Network error" msgstr "Errore di rete" #: relational_gui/guihandler.py:121 relational_gui/guihandler.py:127 #, python-format msgid "New version available online: %s." msgstr "Nuova versione disponibile online: %s." #: relational_gui/guihandler.py:123 relational_gui/guihandler.py:129 msgid "Latest version installed." msgstr "Ultima versione installata." #: relational_gui/guihandler.py:125 relational_gui/guihandler.py:131 msgid "You are using an unstable version." msgstr "Si sta usando una versione non stabile." #: relational_gui/guihandler.py:127 relational_gui/guihandler.py:133 msgid "Version" msgstr "Versione" #: relational_gui/guihandler.py:241 relational_gui/guihandler.py:247 msgid "Empty relation" msgstr "Relazione vuota" #: relational_gui/guihandler.py:283 relational_gui/guihandler.py:289 msgid "Select a relation first." msgstr "Selezionare una relazione" #: relational_gui/guihandler.py:287 relational_gui/guihandler.py:293 msgid "Save Relation" msgstr "Salva relazione" #: relational_gui/guihandler.py:289 relational_gui/guihandler.py:295 msgid "Json relations (*.json);;CSV relations (*.csv)" msgstr "Relazioni json (*.json);;Relazioni CSV (*.csv)" #: relational_gui/guihandler.py:333 relational_gui/guihandler.py:339 msgid "New relation" msgstr "Nuova relazione" #: relational_gui/guihandler.py:334 relational_gui/guihandler.py:340 msgid "Insert the name for the new relation" msgstr "Inserire il nome per la nuova relazione" #: relational_gui/guihandler.py:342 relational_gui/guihandler.py:348 #, python-brace-format msgid "Wrong name for destination relation: {name}." msgstr "Nome errato per la relazione di destinazione: {name}." #: relational_gui/guihandler.py:410 relational_gui/guihandler.py:416 msgid "Load Relation" msgstr "Apri relazione" #: relational_gui/guihandler.py:412 relational_gui/guihandler.py:418 msgid "Relations (*.json *.csv);;Text Files (*.txt);;All Files (*)" msgstr "Relazioni (*.json *.csv);;File di testo (*.txt);;Tutti i file (*)" #: relational_gui/maingui.py:558 msgid "Relational" msgstr "Relational" #: relational_gui/maingui.py:559 msgid "result=query" msgstr "risultato=query" #: relational_gui/maingui.py:560 relational_gui/maingui.py:572 msgid "⌫" msgstr "⌫" #: relational_gui/maingui.py:561 relational_gui/maingui.py:573 msgid "Ctrl+Shift+Backspace" msgstr "Ctrl+Maiusc+Backspace" #: relational_gui/maingui.py:562 relational_gui/maingui.py:574 msgid "Execute" msgstr "Esegui" #: relational_gui/maingui.py:563 relational_gui/maingui.py:575 msgid "Ctrl+Return" msgstr "Ctrl+Invio" #: relational_gui/maingui.py:564 relational_gui/maingui.py:566 msgid "Optimize" msgstr "Ottimizza" #: relational_gui/maingui.py:565 relational_gui/maingui.py:568 msgid "Undo optimize" msgstr "Annulla ottimizza" #: relational_gui/maingui.py:567 msgid "Ctrl+Shift+O" msgstr "Ctrl+Maiusc+O" #: relational_gui/maingui.py:569 msgid "Ctrl+Shift+U" msgstr "Ctrl+Maiusc+U" #: relational_gui/maingui.py:570 msgid "Clear history" msgstr "Cancella cronologia" #: relational_gui/maingui.py:571 msgid "Ctrl+Shift+C" msgstr "Ctrl+Maiusc+C" #: relational_gui/maingui.py:576 msgid "Processing…" msgstr "Calcolo..." #: relational_gui/maingui.py:577 msgid "&File" msgstr "&File" #: relational_gui/maingui.py:578 msgid "Help" msgstr "Aiuto" #: relational_gui/maingui.py:579 msgid "Relations" msgstr "Relazioni" #: relational_gui/maingui.py:580 msgid "Setti&ngs" msgstr "Impostazio&ni" #: relational_gui/maingui.py:581 msgid "Operators" msgstr "Operatori" #: relational_gui/maingui.py:582 msgid "Left outer join" msgstr "Join esterno sinistro" #: relational_gui/maingui.py:583 msgid "Alt+J, Alt+L" msgstr "Alt+J, Alt+L" #: relational_gui/maingui.py:584 msgid "Alt+A" msgstr "" #: relational_gui/maingui.py:585 msgid "Union" msgstr "Unione" #: relational_gui/maingui.py:586 msgid "Alt+U" msgstr "" #: relational_gui/maingui.py:587 msgid "Difference" msgstr "Differenza" #: relational_gui/maingui.py:588 msgid "Rename" msgstr "Rinomina" #: relational_gui/maingui.py:589 msgid "Alt+R" msgstr "" #: relational_gui/maingui.py:590 msgid "Division" msgstr "Divisione" #: relational_gui/maingui.py:591 msgid "Alt+D" msgstr "" #: relational_gui/maingui.py:592 msgid "Full outer join" msgstr "Join esterno completo" #: relational_gui/maingui.py:593 msgid "Alt+J, Alt+O" msgstr "" #: relational_gui/maingui.py:594 msgid "Intersection" msgstr "Intersezione" #: relational_gui/maingui.py:595 msgid "Alt+I" msgstr "" #: relational_gui/maingui.py:596 msgid "Product" msgstr "Prodotto" #: relational_gui/maingui.py:597 msgid "Right outer join" msgstr "Join esterno destro" #: relational_gui/maingui.py:598 msgid "Alt+J, Alt+R" msgstr "" #: relational_gui/maingui.py:599 msgid "Projection" msgstr "Proiezione" #: relational_gui/maingui.py:600 msgid "Alt+P" msgstr "" #: relational_gui/maingui.py:601 msgid "Selection" msgstr "Selezione" #: relational_gui/maingui.py:602 msgid "Alt+S" msgstr "" #: relational_gui/maingui.py:603 msgid "Natural join" msgstr "Join naturale" #: relational_gui/maingui.py:604 msgid "Alt+J, Alt+J" msgstr "" #: relational_gui/maingui.py:605 msgid "Attrib&utes" msgstr "Attrib&uti" #: relational_gui/maingui.py:606 msgid "Re&lations" msgstr "Re&lazioni" #: relational_gui/maingui.py:608 msgid "New" msgstr "Nuova" #: relational_gui/maingui.py:609 relational_gui/rel_edit.py:66 msgid "Edit" msgstr "Modifica" #: relational_gui/maingui.py:610 msgid "Load" msgstr "Apri" #: relational_gui/maingui.py:611 msgid "Save" msgstr "Salva" #: relational_gui/maingui.py:612 msgid "Unload all" msgstr "Chiudi tutte" #: relational_gui/maingui.py:613 msgid "Unload" msgstr "Chiudi" #: relational_gui/maingui.py:614 msgid "Menu" msgstr "Menu" #: relational_gui/maingui.py:615 msgid "About" msgstr "Informazioni su Relational" #: relational_gui/maingui.py:616 relational_gui/survey.py:124 msgid "Survey" msgstr "Sondaggio" #: relational_gui/maingui.py:617 msgid "&About" msgstr "Informazioni su" #: relational_gui/maingui.py:618 msgid "&Load relation" msgstr "Apri re&lazione" #: relational_gui/maingui.py:619 msgid "Ctrl+O" msgstr "" #: relational_gui/maingui.py:620 msgid "&Save relation" msgstr "&Salva relazione" #: relational_gui/maingui.py:621 msgid "Ctrl+S" msgstr "" #: relational_gui/maingui.py:622 msgid "&Quit" msgstr "&Esci" #: relational_gui/maingui.py:623 msgid "Ctrl+Q" msgstr "" #: relational_gui/maingui.py:624 msgid "&Check for new versions" msgstr "&Controlla nuove versioni" #: relational_gui/maingui.py:625 msgid "&New relation" msgstr "&Nuova relazione" #: relational_gui/maingui.py:626 msgid "Ctrl+N" msgstr "" #: relational_gui/maingui.py:627 msgid "&Edit relation" msgstr "Modifica r&elazione" #: relational_gui/maingui.py:628 msgid "Ctrl+E" msgstr "" #: relational_gui/maingui.py:629 msgid "&Unload relation" msgstr "Chi&udi relazione" #: relational_gui/maingui.py:630 msgid "&Multi-line mode" msgstr "&Modalità multi riga" #: relational_gui/maingui.py:631 msgid "Ctrl+L" msgstr "" #: relational_gui/maingui.py:632 msgid "Show history" msgstr "Mostra cronologia" #: relational_gui/rel_edit.py:65 msgid "Relation editor" msgstr "Editor di relazioni" #: relational_gui/rel_edit.py:67 msgid "Add tuple" msgstr "Aggiungi tupla" #: relational_gui/rel_edit.py:68 msgid "Remove tuple" msgstr "Rimuovi tupla" #: relational_gui/rel_edit.py:69 msgid "Add column" msgstr "Aggiungi colonna" #: relational_gui/rel_edit.py:70 msgid "Remove column" msgstr "Rimuovi colonna" #: relational_gui/rel_edit.py:71 msgid "" "Remember that new relations and modified relations are not automatically " "saved" msgstr "" "Ricorda che le relazioni nuove e modificate non sono salvate automaticamente" #: relational_gui/surveyForm.py:90 msgid "Thanks" msgstr "Grazie" #: relational_gui/surveyForm.py:90 msgid "Thanks for sending!" msgstr "Grazie per l'invio!" #: relational_gui/surveyForm.py:92 msgid "Seriously?" msgstr "Sul serio?" #: relational_gui/surveyForm.py:94 msgid "Unable to send the data!" msgstr "Impossibile inviare i dati" #: relational_gui/survey.py:125 msgid "Country" msgstr "Nazione" #: relational_gui/survey.py:126 msgid "School" msgstr "Scuola" #: relational_gui/survey.py:127 msgid "Age" msgstr "Età" #: relational_gui/survey.py:128 msgid "How did you find relational" msgstr "Come hai trovato Relational" #: relational_gui/survey.py:129 msgid "System" msgstr "Sistema" #: relational_gui/survey.py:130 msgid "Comments" msgstr "Commenti" #: relational_gui/survey.py:131 msgid "Email (only if you want a reply)" msgstr "Email (solo se si desidera una risposta)" #: relational_gui/survey.py:132 msgid "Cancel" msgstr "Annulla" #: relational_gui/survey.py:133 msgid "Clear" msgstr "Cancella" #: relational_gui/survey.py:134 msgid "Send" msgstr "Invia" #: relational/maintenance.py:157 relational/maintenance.py:188 #: relational/maintenance.py:167 relational/maintenance.py:198 msgid "Invalid name for destination relation" msgstr "Nome non valido per la relazione di destinazione" #: relational/maintenance.py:230 relational/maintenance.py:240 #, python-format msgid "" "Error in query: %s\n" "%s" msgstr "Errore nella query: %s %s" #: relational/maintenance.py:235 relational/maintenance.py:245 msgid "No query executed" msgstr "Nessuna query eseguita" #: relational/parser.py:310 relational/parser.py:307 msgid "Failed to parse empty expression" msgstr "Espressione vuota" #: relational/parser.py:335 relational/parser.py:332 #, python-format msgid "Expected left operand for %s" msgstr "Expected left operand for %s" #: relational/parser.py:339 relational/parser.py:336 #, python-format msgid "Expected right operand for %s" msgstr "Atteso operatore destro per %s" #: relational/parser.py:346 relational/parser.py:343 #, python-format msgid "Expected more tokens in %s" msgstr "Attesi più token in %s" #: relational/parser.py:349 relational/parser.py:346 #, python-format msgid "Too many tokens in %s" msgstr "Troppi token in %s" #: relational/parser.py:356 relational/parser.py:353 #, python-format msgid "Parse error on %s" msgstr "Errore di parsing in %s" #: relational/parser.py:426 relational/parser.py:423 #, python-format msgid "Missing matching ')' in '%s'" msgstr "')' corrispondente mancante in '%s'" #: relational/relation.py:92 relational/relation.py:140 #, python-format msgid "Line %d contains an incorrect amount of values" msgstr "La riga %d contiene un numero incorretto di valori" #: relational/relation.py:173 #, python-format msgid "Relations differ: [%s] [%s]" msgstr "Le relazioni differiscono: [%s] [%s]" #: relational/relation.py:184 #, python-format msgid "Failed to compile expression: %s" msgstr "Compilazione dell'espressione fallita: %s" #: relational/relation.py:197 #, python-brace-format msgid "" "Failed to evaluate {expr} with {i}\n" "{e}" msgstr "Impossibile valutare {expr} con {i} {e}" #: relational/relation.py:209 msgid "Unable to perform product on relations with colliding attributes" msgstr "" "Impossibile eseguire il prodotto su relazioni con attributi che collidono" #: relational/relation.py:235 msgid "Invalid attributes for projection" msgstr "Attributi invalidi per la proiezione" #: relational/relation.py:476 #, python-format msgid "\"%s\" is not a valid attribute name" msgstr "\"%s\" non è un nome di attributo valido" #: relational/relation.py:492 #, python-format msgid "%s is not a valid attribute name" msgstr "%s non è un nome di attributo valido" #: relational/relation.py:497 #, python-format msgid "Field not found: %s" msgstr "File non trovato: %s" #: relational/rtypes.py:87 #, python-format msgid "%s is not a valid date" msgstr "%s non è una data valida" #: relational_gui/creator.py:59 msgid "Relation contains a None value and cannot be edited from the GUI" msgstr "" "La relazione contiene un valore None e non può essere modificata nella GUI" #: relational_gui/creator.py:74 msgid "Field name 1" msgstr "Campo 1" #: relational_gui/creator.py:75 msgid "Field name 2" msgstr "Campo 2" #: relational_gui/creator.py:76 msgid "Value 1" msgstr "Valore 1" #: relational_gui/creator.py:77 msgid "Value 2" msgstr "Valore 2" #: relational.py:37 msgid "" "Copyright (C) 2008-2024 Salvo 'LtWorf' Tomaselli.\n" "\n" "This program comes with ABSOLUTELY NO WARRANTY.\n" "This is free software, and you are welcome to redistribute it\n" "under certain conditions.\n" "For details see the GPLv3 Licese.\n" "\n" "Written by Salvo 'LtWorf' Tomaselli \n" "\n" "https://ltworf.codeberg.page/relational/" msgstr "" "Copyright (C) 2008-2024 Salvo 'LtWorf' Tomaselli.\n" "\n" "Questo programma viene fornito SENZA GARANZIA.\n" "Questo è software gratuito e si è liberi di redistribuirlo\n" "a determinate condizioni.\n" "Per ulteriori dettagli, consultare la licenza GPLv3.\n" "\n" "Scritto da Salvo 'LtWorf' Tomaselli \n" "\n" "https://ltworf.codeberg.page/relational/" #: relational/parser.py:193 msgid "What kind of alien object is this?" msgstr "Che razza di oggetto alieno è?" #: relational/parser.py:268 relational/parser.py:273 msgid "This is only supported on projection nodes" msgstr "Questo è supportato solo sui nodi di proiezione" #: relational/parser.py:281 relational/parser.py:293 msgid "This is only supported on rename nodes" msgstr "Questo è supportato solo sui nodi di rinomina" #: relational/parser.py:314 msgid "{expression[0]!r} is not a valid relation name" msgstr "{expression[0]!r} non è un nome valido per una relazione" #: relational/relation.py:168 msgid "Expected an instance of the same class" msgstr "Attesa una istanza della stessa classe" #: relational/relation.py:206 msgid "Operand must be a relation" msgstr "L'operando deve essere una relazione" #: relational/relation.py:479 msgid "Attribute names must be unique" msgstr "I nomi degli attributi devono essere unici" #: relational/relation.py:517 #, python-format msgid "One of the fields is not in the relation: %s" msgstr "Uno dei campi non è nella relazione: %s" relational/po/messages.pot0000664000175000017500000003637514647215100015233 0ustar salvosalvo# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the relational package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: relational\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-07-21 15:43+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: relational.py:37 msgid "" "Copyright (C) 2008-2020 Salvo 'LtWorf' Tomaselli.\n" "\n" "This program comes with ABSOLUTELY NO WARRANTY.\n" "This is free software, and you are welcome to redistribute it\n" "under certain conditions.\n" "For details see the GPLv3 Licese.\n" "\n" "Written by Salvo 'LtWorf' Tomaselli \n" "\n" "https://ltworf.codeberg.pages/relational/" msgstr "" #: relational.py:56 msgid " -v Print version and exits" msgstr "" #: relational.py:57 msgid " -h Print this help and exits" msgstr "" #: relational.py:58 msgid " -q Uses Qt user interface" msgstr "" #: relational.py:59 msgid " -r Uses readline user interface" msgstr "" #: relational.py:92 msgid "" "Module relational_gui is missing.\n" "Please install relational package or run make." msgstr "" #: relational.py:128 msgid "" "Module relational_readline is missing.\n" "Please install relational-cli package." msgstr "" #: relational_readline/linegui.py:126 #, python-format msgid "%s is not a file" msgstr "" #: relational_readline/linegui.py:137 #, python-format msgid "%s is not a valid relation name" msgstr "" #: relational_readline/linegui.py:143 #, python-format msgid "Loaded relation %s" msgstr "" #: relational_readline/linegui.py:161 relational_gui/surveyForm.py:92 msgid "Yeah, not sending that." msgstr "" #: relational_readline/linegui.py:169 msgid "" "HELP [command]\n" "\n" "Comments are obtained starting with a ;\n" "\n" "To execute a query:\n" "[relation =] query\n" "\n" "If the 1st part is omitted, the result will be stored in the relation " "last_.\n" "\n" "To prevent from printing the relation, append a ; to the end of the query.\n" "\n" "To insert relational operators, type _OPNAME, they will be internally " "replaced with the correct symbol.\n" "\n" "Rember: completion is enabled and can be very helpful if you can't remember " "something." msgstr "" #: relational_readline/linegui.py:188 msgid "Quits the program" msgstr "" #: relational_readline/linegui.py:189 msgid "Lists the relations loaded" msgstr "" #: relational_readline/linegui.py:190 msgid "" "LOAD filename [relationame]\n" "Loads a relation into memory" msgstr "" #: relational_readline/linegui.py:191 msgid "" "UNLOAD relationame\n" "Unloads a relation from memory" msgstr "" #: relational_readline/linegui.py:192 msgid "" "SAVE filename relationame\n" "Saves a relation in a file" msgstr "" #: relational_readline/linegui.py:193 msgid "Prints the help on a command" msgstr "" #: relational_readline/linegui.py:194 msgid "Fill and send a survey" msgstr "" #: relational_readline/linegui.py:196 #, python-format msgid "Unknown command: %s" msgstr "" #: relational_readline/linegui.py:222 relational_readline/linegui.py:234 #: relational_readline/linegui.py:245 msgid "Missing parameter" msgstr "" #: relational_readline/linegui.py:236 msgid "Too many parameter" msgstr "" #: relational_readline/linegui.py:241 #, python-format msgid "No such relation %s" msgstr "" #: relational_readline/linegui.py:322 msgid "; Type HELP to get the HELP" msgstr "" #: relational_readline/linegui.py:324 msgid "; Completion is activated using the tab (if supported by the terminal)" msgstr "" #: relational_gui/creator.py:91 relational_gui/creator.py:102 #: relational_gui/guihandler.py:283 relational_gui/guihandler.py:315 #: relational_gui/guihandler.py:325 relational_gui/guihandler.py:342 #: relational_gui/surveyForm.py:94 relational_gui/guihandler.py:289 #: relational_gui/guihandler.py:321 relational_gui/guihandler.py:331 #: relational_gui/guihandler.py:348 msgid "Error" msgstr "" #: relational_gui/creator.py:92 msgid "Header error!" msgstr "" #: relational_gui/creator.py:102 #, python-format msgid "Unset value in %d,%d!" msgstr "" #: relational_gui/guihandler.py:119 relational_gui/guihandler.py:125 msgid "Network error" msgstr "" #: relational_gui/guihandler.py:121 relational_gui/guihandler.py:127 #, python-format msgid "New version available online: %s." msgstr "" #: relational_gui/guihandler.py:123 relational_gui/guihandler.py:129 msgid "Latest version installed." msgstr "" #: relational_gui/guihandler.py:125 relational_gui/guihandler.py:131 msgid "You are using an unstable version." msgstr "" #: relational_gui/guihandler.py:127 relational_gui/guihandler.py:133 msgid "Version" msgstr "" #: relational_gui/guihandler.py:241 relational_gui/guihandler.py:247 msgid "Empty relation" msgstr "" #: relational_gui/guihandler.py:283 relational_gui/guihandler.py:289 msgid "Select a relation first." msgstr "" #: relational_gui/guihandler.py:287 relational_gui/guihandler.py:293 msgid "Save Relation" msgstr "" #: relational_gui/guihandler.py:289 relational_gui/guihandler.py:295 msgid "Json relations (*.json);;CSV relations (*.csv)" msgstr "" #: relational_gui/guihandler.py:333 relational_gui/guihandler.py:339 msgid "New relation" msgstr "" #: relational_gui/guihandler.py:334 relational_gui/guihandler.py:340 msgid "Insert the name for the new relation" msgstr "" #: relational_gui/guihandler.py:342 relational_gui/guihandler.py:348 #, python-brace-format msgid "Wrong name for destination relation: {name}." msgstr "" #: relational_gui/guihandler.py:410 relational_gui/guihandler.py:416 msgid "Load Relation" msgstr "" #: relational_gui/guihandler.py:412 relational_gui/guihandler.py:418 msgid "Relations (*.json *.csv);;Text Files (*.txt);;All Files (*)" msgstr "" #: relational_gui/maingui.py:558 msgid "Relational" msgstr "" #: relational_gui/maingui.py:559 msgid "result=query" msgstr "" #: relational_gui/maingui.py:560 relational_gui/maingui.py:572 msgid "⌫" msgstr "" #: relational_gui/maingui.py:561 relational_gui/maingui.py:573 msgid "Ctrl+Shift+Backspace" msgstr "" #: relational_gui/maingui.py:562 relational_gui/maingui.py:574 msgid "Execute" msgstr "" #: relational_gui/maingui.py:563 relational_gui/maingui.py:575 msgid "Ctrl+Return" msgstr "" #: relational_gui/maingui.py:564 relational_gui/maingui.py:566 msgid "Optimize" msgstr "" #: relational_gui/maingui.py:565 relational_gui/maingui.py:568 msgid "Undo optimize" msgstr "" #: relational_gui/maingui.py:567 msgid "Ctrl+Shift+O" msgstr "" #: relational_gui/maingui.py:569 msgid "Ctrl+Shift+U" msgstr "" #: relational_gui/maingui.py:570 msgid "Clear history" msgstr "" #: relational_gui/maingui.py:571 msgid "Ctrl+Shift+C" msgstr "" #: relational_gui/maingui.py:576 msgid "Processing…" msgstr "" #: relational_gui/maingui.py:577 msgid "&File" msgstr "" #: relational_gui/maingui.py:578 msgid "Help" msgstr "" #: relational_gui/maingui.py:579 msgid "Relations" msgstr "" #: relational_gui/maingui.py:580 msgid "Setti&ngs" msgstr "" #: relational_gui/maingui.py:581 msgid "Operators" msgstr "" #: relational_gui/maingui.py:582 msgid "Left outer join" msgstr "" #: relational_gui/maingui.py:583 msgid "Alt+J, Alt+L" msgstr "" #: relational_gui/maingui.py:584 msgid "Alt+A" msgstr "" #: relational_gui/maingui.py:585 msgid "Union" msgstr "" #: relational_gui/maingui.py:586 msgid "Alt+U" msgstr "" #: relational_gui/maingui.py:587 msgid "Difference" msgstr "" #: relational_gui/maingui.py:588 msgid "Rename" msgstr "" #: relational_gui/maingui.py:589 msgid "Alt+R" msgstr "" #: relational_gui/maingui.py:590 msgid "Division" msgstr "" #: relational_gui/maingui.py:591 msgid "Alt+D" msgstr "" #: relational_gui/maingui.py:592 msgid "Full outer join" msgstr "" #: relational_gui/maingui.py:593 msgid "Alt+J, Alt+O" msgstr "" #: relational_gui/maingui.py:594 msgid "Intersection" msgstr "" #: relational_gui/maingui.py:595 msgid "Alt+I" msgstr "" #: relational_gui/maingui.py:596 msgid "Product" msgstr "" #: relational_gui/maingui.py:597 msgid "Right outer join" msgstr "" #: relational_gui/maingui.py:598 msgid "Alt+J, Alt+R" msgstr "" #: relational_gui/maingui.py:599 msgid "Projection" msgstr "" #: relational_gui/maingui.py:600 msgid "Alt+P" msgstr "" #: relational_gui/maingui.py:601 msgid "Selection" msgstr "" #: relational_gui/maingui.py:602 msgid "Alt+S" msgstr "" #: relational_gui/maingui.py:603 msgid "Natural join" msgstr "" #: relational_gui/maingui.py:604 msgid "Alt+J, Alt+J" msgstr "" #: relational_gui/maingui.py:605 msgid "Attrib&utes" msgstr "" #: relational_gui/maingui.py:606 msgid "Re&lations" msgstr "" #: relational_gui/maingui.py:608 msgid "New" msgstr "" #: relational_gui/maingui.py:609 relational_gui/rel_edit.py:66 msgid "Edit" msgstr "" #: relational_gui/maingui.py:610 msgid "Load" msgstr "" #: relational_gui/maingui.py:611 msgid "Save" msgstr "" #: relational_gui/maingui.py:612 msgid "Unload all" msgstr "" #: relational_gui/maingui.py:613 msgid "Unload" msgstr "" #: relational_gui/maingui.py:614 msgid "Menu" msgstr "" #: relational_gui/maingui.py:615 msgid "About" msgstr "" #: relational_gui/maingui.py:616 relational_gui/survey.py:124 msgid "Survey" msgstr "" #: relational_gui/maingui.py:617 msgid "&About" msgstr "" #: relational_gui/maingui.py:618 msgid "&Load relation" msgstr "" #: relational_gui/maingui.py:619 msgid "Ctrl+O" msgstr "" #: relational_gui/maingui.py:620 msgid "&Save relation" msgstr "" #: relational_gui/maingui.py:621 msgid "Ctrl+S" msgstr "" #: relational_gui/maingui.py:622 msgid "&Quit" msgstr "" #: relational_gui/maingui.py:623 msgid "Ctrl+Q" msgstr "" #: relational_gui/maingui.py:624 msgid "&Check for new versions" msgstr "" #: relational_gui/maingui.py:625 msgid "&New relation" msgstr "" #: relational_gui/maingui.py:626 msgid "Ctrl+N" msgstr "" #: relational_gui/maingui.py:627 msgid "&Edit relation" msgstr "" #: relational_gui/maingui.py:628 msgid "Ctrl+E" msgstr "" #: relational_gui/maingui.py:629 msgid "&Unload relation" msgstr "" #: relational_gui/maingui.py:630 msgid "&Multi-line mode" msgstr "" #: relational_gui/maingui.py:631 msgid "Ctrl+L" msgstr "" #: relational_gui/maingui.py:632 msgid "Show history" msgstr "" #: relational_gui/rel_edit.py:65 msgid "Relation editor" msgstr "" #: relational_gui/rel_edit.py:67 msgid "Add tuple" msgstr "" #: relational_gui/rel_edit.py:68 msgid "Remove tuple" msgstr "" #: relational_gui/rel_edit.py:69 msgid "Add column" msgstr "" #: relational_gui/rel_edit.py:70 msgid "Remove column" msgstr "" #: relational_gui/rel_edit.py:71 msgid "" "Remember that new relations and modified relations are not automatically " "saved" msgstr "" #: relational_gui/surveyForm.py:90 msgid "Thanks" msgstr "" #: relational_gui/surveyForm.py:90 msgid "Thanks for sending!" msgstr "" #: relational_gui/surveyForm.py:92 msgid "Seriously?" msgstr "" #: relational_gui/surveyForm.py:94 msgid "Unable to send the data!" msgstr "" #: relational_gui/survey.py:125 msgid "Country" msgstr "" #: relational_gui/survey.py:126 msgid "School" msgstr "" #: relational_gui/survey.py:127 msgid "Age" msgstr "" #: relational_gui/survey.py:128 msgid "How did you find relational" msgstr "" #: relational_gui/survey.py:129 msgid "System" msgstr "" #: relational_gui/survey.py:130 msgid "Comments" msgstr "" #: relational_gui/survey.py:131 msgid "Email (only if you want a reply)" msgstr "" #: relational_gui/survey.py:132 msgid "Cancel" msgstr "" #: relational_gui/survey.py:133 msgid "Clear" msgstr "" #: relational_gui/survey.py:134 msgid "Send" msgstr "" #: relational/maintenance.py:157 relational/maintenance.py:188 #: relational/maintenance.py:167 relational/maintenance.py:198 msgid "Invalid name for destination relation" msgstr "" #: relational/maintenance.py:230 relational/maintenance.py:240 #, python-format msgid "" "Error in query: %s\n" "%s" msgstr "" #: relational/maintenance.py:235 relational/maintenance.py:245 msgid "No query executed" msgstr "" #: relational/parser.py:310 relational/parser.py:307 msgid "Failed to parse empty expression" msgstr "" #: relational/parser.py:335 relational/parser.py:332 #, python-format msgid "Expected left operand for %s" msgstr "" #: relational/parser.py:339 relational/parser.py:336 #, python-format msgid "Expected right operand for %s" msgstr "" #: relational/parser.py:346 relational/parser.py:343 #, python-format msgid "Expected more tokens in %s" msgstr "" #: relational/parser.py:349 relational/parser.py:346 #, python-format msgid "Too many tokens in %s" msgstr "" #: relational/parser.py:356 relational/parser.py:353 #, python-format msgid "Parse error on %s" msgstr "" #: relational/parser.py:426 relational/parser.py:423 #, python-format msgid "Missing matching ')' in '%s'" msgstr "" #: relational/relation.py:92 relational/relation.py:140 #, python-format msgid "Line %d contains an incorrect amount of values" msgstr "" #: relational/relation.py:173 #, python-format msgid "Relations differ: [%s] [%s]" msgstr "" #: relational/relation.py:184 #, python-format msgid "Failed to compile expression: %s" msgstr "" #: relational/relation.py:197 #, python-brace-format msgid "" "Failed to evaluate {expr} with {i}\n" "{e}" msgstr "" #: relational/relation.py:209 msgid "Unable to perform product on relations with colliding attributes" msgstr "" #: relational/relation.py:235 msgid "Invalid attributes for projection" msgstr "" #: relational/relation.py:476 #, python-format msgid "\"%s\" is not a valid attribute name" msgstr "" #: relational/relation.py:492 #, python-format msgid "%s is not a valid attribute name" msgstr "" #: relational/relation.py:497 #, python-format msgid "Field not found: %s" msgstr "" #: relational/rtypes.py:87 #, python-format msgid "%s is not a valid date" msgstr "" #: relational_gui/creator.py:59 msgid "Relation contains a None value and cannot be edited from the GUI" msgstr "" #: relational_gui/creator.py:74 msgid "Field name 1" msgstr "" #: relational_gui/creator.py:75 msgid "Field name 2" msgstr "" #: relational_gui/creator.py:76 msgid "Value 1" msgstr "" #: relational_gui/creator.py:77 msgid "Value 2" msgstr "" #: relational.py:37 msgid "" "Copyright (C) 2008-2024 Salvo 'LtWorf' Tomaselli.\n" "\n" "This program comes with ABSOLUTELY NO WARRANTY.\n" "This is free software, and you are welcome to redistribute it\n" "under certain conditions.\n" "For details see the GPLv3 Licese.\n" "\n" "Written by Salvo 'LtWorf' Tomaselli \n" "\n" "https://ltworf.codeberg.page/relational/" msgstr "" #: relational/parser.py:193 msgid "What kind of alien object is this?" msgstr "" #: relational/parser.py:268 relational/parser.py:273 msgid "This is only supported on projection nodes" msgstr "" #: relational/parser.py:281 relational/parser.py:293 msgid "This is only supported on rename nodes" msgstr "" #: relational/parser.py:314 msgid "{expression[0]!r} is not a valid relation name" msgstr "" #: relational/relation.py:168 msgid "Expected an instance of the same class" msgstr "" #: relational/relation.py:206 msgid "Operand must be a relation" msgstr "" #: relational/relation.py:479 msgid "Attribute names must be unique" msgstr "" #: relational/relation.py:517 #, python-format msgid "One of the fields is not in the relation: %s" msgstr "" relational/po/.gitignore0000664000175000017500000000000514647215100014645 0ustar salvosalvo*.mo relational/feedback/0000775000175000017500000000000014647215100013770 5ustar salvosalvorelational/feedback/feedback.py0000664000175000017500000000333514647215100016072 0ustar salvosalvo#!/usr/bin/env python3 # Relational # Copyright (C) 2023 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 # # Used to receive feedback from relational from os import environ from syslog import * HEADERHTTP='HTTP/1.0 200 Ok\r\nContent-Type: text/html; charset=UTF-8\r\nConnection: close\r\n\r\n' NOTFOUND='HTTP/1.0 404 Not found\r\nContent-Type: text/html; charset=UTF-8\r\nConnection: close\r\n\r\n

Not found

' def main(): if 'HTTP_X_SURVEY' not in environ: syslog(LOG_ERR, "Got invalid survey") print(NOTFOUND) return syslog(LOG_INFO, "Got valid survey") import datetime with open('/srv/www/survey.txt', 'at') as f: print(datetime.datetime.now(), file=f) for k, v in environ.items(): if k.startswith('HTTP_X_SURVEY'): print(f'{k} = {v}', file=f) print(file=f) print(HEADERHTTP) if __name__ == '__main__': openlog('feedback') try: main() except Exception as e: syslog(LOG_ERR, repr(e)) from sys import exit exit(1) relational/relational.10000664000175000017500000000156514647215100014467 0ustar salvosalvo.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/test-requirements.txt0000664000175000017500000000003214647215100016500 0ustar salvosalvomypy typedload xtermcolor relational/relational.py0000775000175000017500000000760014647215100014756 0ustar salvosalvo#!/usr/bin/env python3 # Relational # Copyright (C) 2008-2024 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 import gettext gettext.bindtextdomain('relational') gettext.textdomain('relational') _ = gettext.gettext version = "3.3" def printver(exit=True): print ("Relational %s" % version) print (_("Copyright (C) 2008-2024 Salvo 'LtWorf' Tomaselli.\n" "\n" "This program comes with ABSOLUTELY NO WARRANTY.\n" "This is free software, and you are welcome to redistribute it\n" "under certain conditions.\n" "For details see the GPLv3 Licese.\n" "\n" "Written by Salvo 'LtWorf' Tomaselli \n" "\n" "https://ltworf.codeberg.page/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')) print (_(' -q Uses Qt user interface')) 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) from PyQt6 import QtWidgets try: from relational_gui import guihandler, about, surveyForm except: print ( _('Module relational_gui is missing.\nPlease 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/pages/0000775000175000017500000000000014647215100013343 5ustar salvosalvo