Parse-Dia-SQL-0.31/0000755000175000017500000000000013672477315011730 5ustar affaffParse-Dia-SQL-0.31/installer/0000755000175000017500000000000013672477314013724 5ustar affaffParse-Dia-SQL-0.31/installer/parsediasql-setup.nsi0000755000175000017500000001445613672475055020122 0ustar affaff# Parse-Dia-Sql - Convert Dia class diagrams into SQL # # Copyright (C) 2009-2012 Steffen Macke # # 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 2 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, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # NOTE: this .NSI script is designed for NSIS v2.0 Name Parse-Dia-Sql SetCompressor lzma # Defines !define REGKEY "SOFTWARE\$(^Name)" !define VERSION 0.23.0 !define COMPANY "The Parse-Dia-Sql developers" !define URL http://dia-installer.de/parse-dia-sql/ # MUI defines !define MUI_ICON "${NSISDIR}\Contrib\Graphics\Icons\orange-install.ico" !define MUI_FINISHPAGE_NOAUTOCLOSE !define MUI_STARTMENUPAGE_REGISTRY_ROOT HKLM !define MUI_STARTMENUPAGE_REGISTRY_KEY ${REGKEY} !define MUI_STARTMENUPAGE_REGISTRY_VALUENAME StartMenuGroup !define MUI_STARTMENUPAGE_DEFAULTFOLDER Parse-Dia-Sql !define MUI_UNICON "${NSISDIR}\Contrib\Graphics\Icons\orange-uninstall.ico" !define MUI_UNFINISHPAGE_NOAUTOCLOSE !define MUI_FINISHPAGE_LINK "dia-installer.de/parse-dia-sql" !define MUI_FINISHPAGE_LINK_LOCATION "http://dia-installer.de/parse-dia-sql/" # Included files !include Sections.nsh !include MUI.nsh !include Library.nsh !include WinVer.nsh # Variables Var StartMenuGroup # Installer pages !insertmacro MUI_PAGE_WELCOME !insertmacro MUI_PAGE_LICENSE ..\LICENSE !insertmacro MUI_PAGE_DIRECTORY !insertmacro MUI_PAGE_STARTMENU Application $StartMenuGroup !insertmacro MUI_PAGE_INSTFILES !insertmacro MUI_PAGE_FINISH !insertmacro MUI_UNPAGE_CONFIRM !insertmacro MUI_UNPAGE_INSTFILES !insertmacro MUI_LANGUAGE English # Installer attributes OutFile parse-dia-sql-setup-${VERSION}.exe InstallDir $PROGRAMFILES\Parse-Dia-Sql CRCCheck on XPStyle on ShowInstDetails show VIProductVersion ${VERSION}.0 VIAddVersionKey /LANG=${LANG_ENGLISH} ProductName Parse-Dia-SQL VIAddVersionKey /LANG=${LANG_ENGLISH} ProductVersion "${VERSION}" VIAddVersionKey /LANG=${LANG_ENGLISH} CompanyName "${COMPANY}" VIAddVersionKey /LANG=${LANG_ENGLISH} CompanyWebsite "${URL}" VIAddVersionKey /LANG=${LANG_ENGLISH} FileVersion "${VERSION}" VIAddVersionKey /LANG=${LANG_ENGLISH} FileDescription "" VIAddVersionKey /LANG=${LANG_ENGLISH} LegalCopyright "" InstallDirRegKey HKLM "${REGKEY}" Path ShowUninstDetails show # Installer sections Section -Main SEC0000 SetOutPath $INSTDIR\bin SetOverwrite on File parsediasql.exe File C:\strawberry\c\bin\libstdc++-6.dll File C:\strawberry\c\bin\libexpat-1_.dll File c:\strawberry\c\bin\LIBGCC_S_SJLJ-1.DLL SetOutPath $INSTDIR File ..\LICENSE File /oname=LIBEXPAT_COPYING C:\strawberry\licenses\libexpat\COPYING SectionEnd Section -post SEC0001 WriteRegStr HKLM "${REGKEY}" Path $INSTDIR SetOutPath $INSTDIR WriteUninstaller $INSTDIR\uninstall-parse-dia-sql.exe SetOutPath $SMPROGRAMS\$StartMenuGroup CreateShortcut "$SMPROGRAMS\$StartMenuGroup\Parse-Dia-Sql command line.lnk" $SYSDIR\cmd.exe "/K PATH=%PATH%;$INSTDIR\bin" WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" DisplayName "$(^Name)" WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" DisplayVersion "${VERSION}" WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" Publisher "${COMPANY}" WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" URLInfoAbout "${URL}" WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" DisplayIcon $INSTDIR\uninstall-parse-dia-sql.exe WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" UninstallString $INSTDIR\uninstall-parse-dia-sql.exe WriteRegDWORD HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" NoModify 1 WriteRegDWORD HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" NoRepair 1 SectionEnd # Macro for selecting uninstaller sections !macro SELECT_UNSECTION SECTION_NAME UNSECTION_ID Push $R0 ReadRegStr $R0 HKLM "${REGKEY}\Components" "${SECTION_NAME}" StrCmp $R0 1 0 next${UNSECTION_ID} !insertmacro SelectSection "${UNSECTION_ID}" GoTo done${UNSECTION_ID} next${UNSECTION_ID}: !insertmacro UnselectSection "${UNSECTION_ID}" done${UNSECTION_ID}: Pop $R0 !macroend # Uninstaller sections Section "Uninstall" Delete /REBOOTOK $INSTDIR\bin\parsediasql.exe Delete /REBOOTOK $INSTDIR\bin\libstdc++-6.dll Delete /REBOOTOK $INSTDIR\bin\libexpat-1_.dll Delete /REBOOTOK $INSTDIR\bin\LIBGCC_S_SJLJ-1.DLL Delete /REBOOTOK $INSTDIR\LICENSE Delete /REBOOTOK $INSTDIR\LIBEXPAT_COPYING DeleteRegValue HKLM "${REGKEY}\Components" Main DeleteRegKey HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" Delete /REBOOTOK "$SMPROGRAMS\$MUI_STARTMENUPAGE_DEFAULTFOLDER\Parse-Dia-Sql command line.lnk" Delete /REBOOTOK $INSTDIR\uninstall-parse-dia-sql.exe DeleteRegValue HKLM "${REGKEY}" StartMenuGroup DeleteRegValue HKLM "${REGKEY}" Path DeleteRegKey /IfEmpty HKLM "${REGKEY}\Components" DeleteRegKey /IfEmpty HKLM "${REGKEY}" RmDir /REBOOTOK $SMPROGRAMS\$MUI_STARTMENUPAGE_DEFAULTFOLDER RmDir /REBOOTOK $INSTDIR\bin RmDir /REBOOTOK $INSTDIR Push $R0 StrCpy $R0 $StartMenuGroup 1 StrCmp $R0 ">" no_smgroup no_smgroup: Pop $R0 SectionEnd # Installer functions Function .onInit InitPluginsDir ${If} ${AtLeastWin7} ${Else} MessageBox MB_OK "Windows 7 or higher is required for this Parse-Dia-Sql version." Abort "Windows 7 or higher is required for this Parse-Dia-Sql version." ${EndIf} FunctionEnd # Uninstaller functions Function un.onInit ReadRegStr $INSTDIR HKLM "${REGKEY}" Path !insertmacro MUI_STARTMENU_GETFOLDER Application $StartMenuGroup FunctionEnd Parse-Dia-SQL-0.31/TODO0000644000175000017500000000253013672475055012417 0ustar affaff - Implement support for Dia's new Database shape. - Warn if there are typemaps for databases in the model that are not used to generate output. - Add general support for synonyms (replace hack in Parse::Dia::SQL::Utils::get_base_type). - Support index options on individual indices. - Add test for missing FK (formerly fkNamesFromAttList) - Add support for loading statements from external files. - Warn on identical (or near-identical) statements in smallpackages. - Warn attempts to create index on non-existent columns - Add option tablespace to create statements. - Add $VERSION to all modules. - Make sure pre and post statement end up at the right place. - Add options to parsediasql (identical to those of tedia2sql) - For all classes: - verify create table,view,index,constraint syntax - verify drop table,view,index,constraint syntax - Parse::Dia::SQL::Output::MySQL - sub _get_create_table_sql must handle AUTO_INCREMENT - Download DDL's from http://tedia2sql.tigris.org/ and ensure Parse::Dia::SQL produces roughly the same code. - Test with larger dia files. - Optimize with Devel::DProf, and consider a faster XML parser. - Be consistent in subroutine names (e.g. Output.pm) E.g. get__<(create|drop)>_sql - Apply stricter Perl::Critic (current level 'stern', consider 'harsh'). - Update pod in all modules. Parse-Dia-SQL-0.31/LICENSE0000644000175000017500000004305113672475055012737 0ustar affaff GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) 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 this service 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 make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. 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. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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. 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 convey 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision 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, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This 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 Library General Public License instead of this License. Parse-Dia-SQL-0.31/AUTHORS0000644000175000017500000000152013672475055012775 0ustar affaff Contributing Authors to-date: Tim Ellis -- Main program, general direction -- mailto: ttiimmeelleessss at tigris dot org Martin Gebert, Edward Epstein -- MySQL InnoDB support and Constraint enforcement Andrew S. Halper -- Ingres Support Greg Copeland -- Bug fixes & patches Christopher Bowland -- Windows-without-Cygwin fixes Peter Lamb -- UML mode and automatic generation of PK, FK and join tables Martin Bögelund -- SAS DB Support (mainly fixing SQL comment style) Neal Stephenson -- Macro expasion support (small objects defined once for many tables) Paul Suda -- Auto-increment MySQL support Mike Ginou -- Debian friendliness and drop index support Norbert Volf -- Comments for PostgreSQL support Patryk Sciborek -- Datatype equivalence generic algorithm Andreas Faafeng -- CPAN rewrite, test suite. Peter Langton -- SQLite3, HTML support. Parse-Dia-SQL-0.31/lib/0000755000175000017500000000000013672477314012475 5ustar affaffParse-Dia-SQL-0.31/lib/Parse/0000755000175000017500000000000013672477314013547 5ustar affaffParse-Dia-SQL-0.31/lib/Parse/Dia/0000755000175000017500000000000013672477314014244 5ustar affaffParse-Dia-SQL-0.31/lib/Parse/Dia/SQL/0000755000175000017500000000000013672477314014703 5ustar affaffParse-Dia-SQL-0.31/lib/Parse/Dia/SQL/Output.pm0000644000175000017500000007667113672475055016562 0ustar affaffpackage Parse::Dia::SQL::Output; # $Id: Output.pm,v 1.33 2011/02/16 10:23:11 aff Exp $ =pod =head1 NAME Parse::Dia::SQL::Output - Create SQL base class. =head1 SYNOPSIS use Parse::Dia::SQL; my $dia = Parse::Dia::SQL->new(...); my $output = $dia->get_output_instance(); print $output->get_sql(); =head1 DESCRIPTION This is the base sql formatter class for creating sql. It contains basic functionality, which can be overridden in subclasses, one for each RDBMS. =head1 SEE ALSO Parse::Dia::SQL::Output::DB2 Parse::Dia::SQL::Output::Oracle =cut use warnings; use strict; use open qw/:std :utf8/; use Text::Table; use Data::Dumper; use Config; use lib q{lib}; use Parse::Dia::SQL::Utils; use Parse::Dia::SQL::Logger; use Parse::Dia::SQL::Const; =head1 METHODS =over =item new() The constructor. Arguments: db - the target database type =cut sub new { my ($class, %param) = @_; my $self = { # command line options files => $param{files} || [], # dia files db => $param{db} || undef, uml => $param{uml} || undef, fk_auto_gen => $param{fk_auto_gen} || undef, pk_auto_gen => $param{pk_auto_gen} || undef, default_pk => $param{default_pk} || undef, # opt_p # formatting options indent => $param{indent} || q{ } x 3, newline => $param{newline} || "\n", end_of_statement => $param{end_of_statement} || ";", column_separator => $param{column_separator} || ",", sql_comment => $param{sql_comment} || "-- ", # sql options index_options => $param{index_options} || [], object_name_max_length => $param{object_name_max_length} || undef, table_postfix_options => $param{table_postfix_options} || [], table_postfix_options_separator => $param{table_postfix_options_separator} || ' ', # parsed datastructures associations => $param{associations} || [], # foreign keys, indices classes => $param{classes} || [], # tables and views components => $param{components} || [], # insert statements small_packages => $param{small_packages} || [], typemap => $param{typemap} || {}, # custom type mapping loglevel => $param{loglevel} || undef, backticks => $param{backticks} || undef, # MySQL-InnoDB only # references to components log => undef, const => undef, utils => undef, }; bless($self, $class); $self->_init_log(); $self->_init_const(); $self->_init_utils(loglevel => $param{loglevel}); return $self; } # Initialize logger sub _init_log { my $self = shift; my $logger = Parse::Dia::SQL::Logger::->new(loglevel => $self->{loglevel}); $self->{log} = $logger->get_logger(__PACKAGE__); return 1; } # Initialize Constants component sub _init_const { my $self = shift; $self->{const} = Parse::Dia::SQL::Const::->new(); return 1; } # Initialize Parse::Dia::SQL::Utils class. sub _init_utils { my $self = shift; $self->{utils} = Parse::Dia::SQL::Utils::->new( db => $self->{db}, loglevel => $self->{loglevel}, ); return 1; } # Return string with comment containing target database, $VERSION, time # and list of files etc. sub _get_comment { my $self = shift; my $files_word = (scalar(@{ $self->{files} }) > 1) ? q{Input files} : q{Input file}; my @arr = ( [ q{Parse::SQL::Dia}, qq{version $Parse::Dia::SQL::VERSION} ], [ q{Documentation}, q{http://search.cpan.org/dist/Parse-Dia-SQL/} ], [ q{Environment}, qq{Perl $], $^X} ], [ q{Architecture}, qq{$Config{archname}} ], [ q{Target Database}, $self->{db} ], [ $files_word, join(q{, }, @{ $self->{files} }) ], [ q{Generated at}, scalar localtime() ], ); # Add typemap for given database my $typemap_str = "not found in input file"; if (exists($self->{typemap}->{ $self->{db} })) { $typemap_str = "found in input file"; } push @arr, [ "Typemap for " . $self->{db}, $typemap_str ]; # Add the sql_comment to first sub-element of all elements @arr = map { $_->[0] = $self->{sql_comment} . $_->[0]; $_ } @arr; my $tb = Text::Table->new(); $tb->load(@arr); return scalar $tb->table(); } =item get_sql() Return all sql. The sequence of statements is as follows: constraints drop permissions drop view drop schema drop smallpackage pre sql schema create view create permissions create inserts smallpackage post sql associations create (indices first, then foreign keys) =cut sub get_sql { my $self = shift; ## No critic (NoWarnings) no warnings q{uninitialized}; return $self->_get_comment() . $self->{newline} . "-- get_constraints_drop " . $self->{newline} . $self->get_constraints_drop() . $self->{newline} . "-- get_permissions_drop " . $self->{newline} . $self->get_permissions_drop() . $self->{newline} . "-- get_view_drop" . $self->{newline} . $self->get_view_drop() . $self->{newline} . "-- get_schema_drop" . $self->{newline} . $self->get_schema_drop() . $self->{newline} . "-- get_smallpackage_pre_sql " . $self->{newline} . $self->get_smallpackage_pre_sql() . $self->{newline} . "-- get_schema_create" . $self->{newline} . $self->get_schema_create() . $self->{newline} . "-- get_view_create" . $self->{newline} . $self->get_view_create() . $self->{newline} . "-- get_permissions_create" . $self->{newline} . $self->get_permissions_create() . $self->{newline} . "-- get_inserts" . $self->{newline} . $self->get_inserts() . $self->{newline} . "-- get_smallpackage_post_sql" . $self->{newline} . $self->get_smallpackage_post_sql() . $self->{newline} . "-- get_associations_create" . $self->{newline} . $self->get_associations_create(); } # Return insert statements. These are based on content of the # I, and split on the linefeed character ("\n"). # # Add $self->{end_of_statement} to each statement. sub get_inserts { my $self = shift; my $sqlstr = ''; # Expect array ref of hash refs return unless $self->_check_components(); $self->{log}->debug(Dumper($self->{components})) if $self->{log}->is_debug; foreach my $component (@{ $self->{components} }) { foreach my $vals (split("\n", $component->{text})) { $sqlstr .= qq{insert into } . $component->{name} . qq{ values($vals) } . $self->{end_of_statement} . $self->{newline}; } } return $sqlstr; } # Drop all constraints (e.g. foreign keys and indices) # # This sub is split into two parts to make it easy sub subclass either. sub get_constraints_drop { my $self = shift; # Allow undefined values no warnings q[uninitialized]; return $self->_get_fk_drop() . $self->_get_index_drop(); } # Drop all foreign keys sub _get_fk_drop { my $self = shift; my $sqlstr = ''; return unless $self->_check_associations(); # drop fk foreach my $association (@{ $self->{associations} }) { my ($table_name, $constraint_name, undef, undef, undef, undef) = @{$association}; # Shorten constraint name, if necessary (DB2 only) $constraint_name = $self->_create_constraint_name($constraint_name); $sqlstr .= qq{alter table $table_name drop constraint $constraint_name } . $self->{end_of_statement} . $self->{newline}; } return $sqlstr; } # Drop all indices sub _get_index_drop { my $self = shift; my $sqlstr = q{}; return unless $self->_check_classes(); # drop index foreach my $table (@{ $self->{classes} }) { foreach my $operation (@{ $table->{ops} }) { if (ref($operation) ne 'ARRAY') { $self->{log}->error( q{Error in ops input - expect an ARRAY ref, got } . ref($operation)); next OPERATION; } my ($opname, $optype) = ($operation->[0], $operation->[1]); # 2nd element can be index, unique index, grant, etc next if ($optype !~ qr/^(unique )?index$/i); $sqlstr .= $self->_get_drop_index_sql($table->{name}, $opname); } } return $sqlstr; } # Create drop index for index on table with given name. Note that the # tablename is not used here, but many of the overriding subclasses use # it, so we include both the tablename and the indexname as arguments to # keep the interface consistent. sub _get_drop_index_sql { my ($self, $tablename, $indexname) = @_; return qq{drop index $indexname} . $self->{end_of_statement} . $self->{newline}; } # Create drop view for all views sub get_view_drop { my $self = shift; my $sqlstr = ''; return unless $self->_check_classes(); CLASS: foreach my $object (@{ $self->{classes} }) { next CLASS if ($object->{type} ne q{view}); # Sanity checks on internal state if (!defined($object) || ref($object) ne q{HASH} || !exists($object->{name})) { $self->{log} ->error(q{Error in table input - cannot create drop table sql!}); next; } $sqlstr .= qq{drop view } . $object->{name} . $self->{end_of_statement} . $self->{newline}; } return $sqlstr; } # Sanity check on internal state. # # Return true if and only if # # $self->{components} should be a defined array ref with 1 or more # hash ref elements having two keys 'name' and 'text' # # otherwise false. sub _check_components { my $self = shift; # Sanity checks on internal state if (!defined($self->{components})) { $self->{log}->warn(q{no components in schema}); return; } elsif (ref($self->{components}) ne 'ARRAY') { $self->{log}->warn(q{components is not an ARRAY ref}); return; } elsif (scalar(@{ $self->{components} } == 0)) { $self->{log}->info(q{components is an empty ARRAY ref}); return; } foreach my $comp (@{ $self->{components} }) { if (ref($comp) ne q{HASH}) { $self->{log}->warn(q{component element must be a HASH ref}); return; } if ( !exists($comp->{text}) || !exists($comp->{name})) { $self->{log}->warn( q{component element must be a HASH ref with elements 'text' and 'name'} ); return; } } return 1; } # Sanity check on internal state. # # Return true if and only if # # $self->{classes} should be a defined array ref with 1 or more # elements, all of which must be defined # # otherwise false. sub _check_classes { my $self = shift; # Sanity checks on internal state if (!defined($self->{classes})) { $self->{log}->warn(q{no classes in schema}); return; } elsif (ref($self->{classes}) ne 'ARRAY') { $self->{log}->warn(q{classes is not an ARRAY ref}); return; } elsif (scalar(@{ $self->{classes} } == 0)) { $self->{log}->info(q{classes is an empty ARRAY ref}); return; } if (grep(!defined($_), (@{ $self->{classes} }))) { $self->{log} ->warn(q{the classes array reference contains an undefined element!}); return; } return 1; } # Sanity check on internal state. # # Return true if and only if # # $self->{associations} should be a defined array ref with 1 or more # elements # # otherwise false. sub _check_associations { my $self = shift; # Sanity checks on internal state if (!defined($self->{associations})) { $self->{log}->warn(q{no associations in schema}); return; } elsif (ref($self->{associations}) ne 'ARRAY') { $self->{log}->warn(q{associations is not an ARRAY ref}); return; } elsif (scalar(@{ $self->{associations} } == 0)) { $self->{log}->info(q{associations is an empty ARRAY ref}); return; } return 1; } # Sanity check on given reference. # # Return true if and only if # # $arg should be a defined hash ref with 1 or more elements # $arg->{name} exists and is a defined scalar # $arg->{attList} exists and is a defined array ref. # # otherwise false. sub _check_attlist { my $self = shift; my $arg = shift; # Sanity checks on internal state if (!defined($arg) || ref($arg) ne q{HASH} || !exists($arg->{name})) { $self->{log}->error(q{Error in ref input!}); return; } if (!exists($arg->{attList}) || ref($arg->{attList}) ne 'ARRAY') { $self->{log}->error(q{Error in ref attList input!}); return; } return 1; } sub _check_small_packages { my $self = shift; # Sanity checks on internal state if (!defined($self->{small_packages}) || ref($self->{small_packages}) ne q{ARRAY}) { $self->{log}->error(q{small_packages error}); return; } my %seen = (); # Check for duplicate entries foreach my $sp (@{ $self->{small_packages} }) { if (ref($sp) ne 'HASH') { $self->{log}->error(q{Error in small_package input!}); return; } ++$seen{$_} for (keys %{$sp}); } foreach my $key (keys %seen) { $self->{log}->info(qq{Duplicate entry in small_package for key '$key' (} . $seen{$key} . q{ times)}) if $seen{$key} > 1; } return 1; } # create drop table for all tables # # TODO: Consider rename to get_table[s]_drop sub get_schema_drop { my $self = shift; my $sqlstr = ''; return unless $self->_check_classes(); CLASS: foreach my $object (@{ $self->{classes} }) { next CLASS if ($object->{type} ne q{table}); # Sanity checks on internal state if (!defined($object) || ref($object) ne q{HASH} || !exists($object->{name})) { $self->{log} ->error(q{Error in table input - cannot create drop table sql!}); next; } $sqlstr .= $self->_get_drop_schema_sql($object->{name}); } return $sqlstr; } sub _get_drop_schema_sql { my ($self, $tablename) = @_; return qq{drop table if exists } . $self->_quote_identifier($tablename) . $self->{end_of_statement} . $self->{newline}; } # Create revoke sql sub get_permissions_drop { my $self = shift; my $sqlstr = ''; # Check classes return unless $self->_check_classes(); # loop through classes looking for grants foreach my $table (@{ $self->{classes} }) { foreach my $operation (@{ $table->{ops} }) { if (ref($operation) ne 'ARRAY') { $self->{log}->error( q{Error in ops input - expect an ARRAY ref, got } . ref($operation)); next OPERATION; } my ($opname, $optype, $colref) = ($operation->[0], $operation->[1], $operation->[2]); # 2nd element can be index, unique index, grant, etc next if ($optype ne q{grant}); # Add backticks if option is set and dbtype is correct my $tablename = $self->_quote_identifier($table->{name}); $sqlstr .= qq{revoke $opname on } . $tablename . q{ from } . join(q{,}, @{$colref}) . $self->{end_of_statement} . $self->{newline}; } } return $sqlstr; } # Create grant sql sub get_permissions_create { my $self = shift; my $sqlstr = ''; # Check classes return unless $self->_check_classes(); # loop through classes looking for grants foreach my $table (@{ $self->{classes} }) { foreach my $operation (@{ $table->{ops} }) { if (ref($operation) ne 'ARRAY') { $self->{log}->error( q{Error in ops input - expect an ARRAY ref, got } . ref($operation)); next OPERATION; } my ($opname, $optype, $colref) = ($operation->[0], $operation->[1], $operation->[2]); # 2nd element can be index, unique index, grant, etc next if ($optype ne q{grant}); # Add backticks if option is set and dbtype is correct my $tablename = $self->_quote_identifier($table->{name}); $sqlstr .= qq{$optype $opname on } . $tablename . q{ to } . join(q{,}, @{$colref}) . $self->{end_of_statement} . $self->{newline}; } } return $sqlstr; } # Create associations statements: # # This includes the following elements, in the following sequence # # - index (unique and non-unique) # - foreign key sub get_associations_create { my $self = shift; my $sqlstr = ''; # Check both ass. (fk) and classes (index) before operating on the # array refs. # indices if ($self->_check_classes()) { foreach my $object (@{ $self->{classes} }) { $sqlstr .= $self->_get_create_index_sql($object); } } # foreign keys if ($self->_check_associations()) { foreach my $object (@{ $self->{associations} }) { $sqlstr .= $self->_get_create_association_sql($object); } } return $sqlstr; } # Create table statements sub get_schema_create { my $self = shift; my $sqlstr = ''; return unless $self->_check_classes(); CLASS: foreach my $object (@{ $self->{classes} }) { next CLASS if ($object->{type} ne q{table}); $sqlstr .= $self->_get_create_table_sql($object); } return $sqlstr; } # Create view statements sub get_view_create { my $self = shift; my $sqlstr = ''; return unless $self->_check_classes(); VIEW: foreach my $object (@{ $self->{classes} }) { next VIEW if ($object->{type} ne q{view}); $sqlstr .= $self->_get_create_view_sql($object); } return $sqlstr; } # Create primary key clause, e.g. # # constraint pk_ primary key (,..,) # # Returns undefined if list of primary key is empty (i.e. if there are # no primary keys on given table). sub _create_pk_string { my ($self, $tablename, @pks) = @_; if (!$tablename) { $self->{log} ->error(q{Missing argument tablename - cannot create pk string!}); return; } # Return undefined if list of primary key is empty if (scalar(@pks) == 0) { $self->{log}->debug(qq{table '$tablename' has no primary keys}); return; } return qq{constraint pk_$tablename primary key (} . join(q{,}, @pks) . q{)}; } # Create sql for given table. Use _format_columns() to # format columns nicely (without the comment column) sub _get_create_table_sql { my ($self, $table) = @_; my @columns = (); my @primary_keys = (); my @comments = (); # Sanity checks on table ref return unless $self->_check_attlist($table); # Save the original table name (in case backticks are added) my $original_table_name = $table->{name}; # Add backticks if option is set and dbtype is correct $table->{name} = $self->_quote_identifier($table->{name}); # Check not null and primary key property for each column. Column # visibility is given in $columns[3]. A value of 2 in this field # signifies a primary key (which also must be defined as 'not null'. foreach my $column (@{ $table->{attList} }) { if (ref($column) ne 'ARRAY') { $self->{log} ->error(q{Error in view attList input - expect an ARRAY ref!}); next COLUMN; } # Don't warn on uninitialized values here since there are lots # of them. ## no critic (ProhibitNoWarnings) no warnings q{uninitialized}; $self->{log}->debug("column before: " . join(q{,}, @$column)); # Field sequence: my ($col_name, $col_type, $col_val, $col_vis, $col_com, $col_nullable) = @$column; # Add 'not null' if field is primary key or marked "not nullable" # (Dia database shape only) if ($col_vis == 2) { $col_val = 'not null'; } elsif ($col_nullable eq q{false}) { $col_val = 'not null'; } # Add column name to list of primary keys if $col_vis == 2 push @primary_keys, $col_name if ($col_vis == 2); # Add 'default' keyword to defined values different from (not) # null when the column is not a primary key: # TODO: Special handling for SAS (in subclass) if ($col_val ne q{} && $col_val !~ /^(not )?null$/i && $col_vis != 2) { $col_val = qq{ default $col_val}; } # Prefix non-empty comments with the comment character $col_com = $self->{sql_comment} . qq{ $col_com} if $col_com; if (!$self->{typemap}) { $self->{log}->debug("no typemap"); } if (exists($self->{typemap}->{ $self->{db} })) { # typemap replace $col_type = $self->map_user_type($col_type); } else { $self->{log}->debug("no typemap for " . $self->{db}); } # Add backticks to column name if option is enabled $col_name = $self->_quote_identifier($col_name); $self->{log}->debug( "column after : " . join(q{,}, $col_name, $col_type, $col_val, $col_com)); # Create a line with out the comment push @columns, [ $col_name, $col_type, $col_val ]; # Comments are added separately *after* comma on each line push @comments, $col_com; # possibly undef } $self->{log}->warn("No columns in table") if !scalar @columns; # Format columns nicely (without the comment column) @columns = $self->_format_columns(@columns); $self->{log}->debug("columns:" . Dumper(\@columns)); $self->{log}->debug("comments:" . Dumper(\@comments)); # Add comma + newline + indent between the lines. # Note that _create_pk_string can return undef. @columns = ( split( /$self->{newline}/, join( $self->{column_separator} . $self->{newline} . $self->{indent}, @columns, $self->_create_pk_string($original_table_name, @primary_keys) ) ) ); # Add the comment column, ensure the comma comes before the comment (if any) { ## no critic (ProhibitNoWarnings) no warnings q{uninitialized}; @columns = map { $_ . shift(@comments) } @columns; } $self->{log}->debug("columns:" . Dumper(\@columns)); # Add custom table postfix options if 'comment' section is defined $self->{log}->debug("table comment:" . Dumper($table->{comment})); if ($table->{comment}) { # Use comment only if it starts with given database type: if ($table->{comment} =~ m/^$self->{db}:\s*(.*)$/) { # Remove db-type my $table_comment = $1; # TODO: Add error checks on 'comment' input $self->{table_postfix_options} = [$table_comment]; } } return qq{create table } . $table->{name} . " (" . $self->{newline} . $self->{indent} . join($self->{newline}, @columns) . $self->get_smallpackage_column_sql($table->{name}) . $self->{newline} . ")" . $self->{indent} . join( $self->{table_postfix_options_separator}, @{ $self->{table_postfix_options} } ) . $self->{end_of_statement} . $self->{newline}; } # Format columns in tabular form using Text::Table. # # Input: arrayref of arrayrefs # Output: arrayref of arrayrefs sub _format_columns { my ($self, @columns) = @_; my @columns_out = (); $self->{log}->debug("input: " . Dumper(\@columns)) if $self->{log}->is_debug(); my $tb = Text::Table->new(); $tb->load(@columns); # Take out one by one the formatted columns, remove newline character push @columns_out, map { s/\n//g; $_ } $tb->body($_) for (0 .. $tb->body_height()); $self->{log}->debug("output: " . Dumper(@columns_out)) if $self->{log}->is_debug(); return @columns_out; } # Create sql for given view. # # Similar to _get_create_table_sql, but must handle # 'from', # 'where', # 'order by', # 'group by', # # TODO: ADD support for 'having' clause. sub _get_create_view_sql { my ($self, $view) = @_; my @columns = (); my @from = (); my @where = (); my @orderby = (); my @groupby = (); # Sanity checks on view ref return unless $self->_check_attlist($view); COLUMN: foreach my $column (@{ $view->{attList} }) { $self->{log}->debug(q{column: } . Dumper($column)); if (ref($column) ne 'ARRAY') { $self->{log} ->error(q{Error in view attList input - expect an ARRAY ref, got } . ref($column)); next COLUMN; } my $col_name = $column->[0]; # Pick first column $self->{log}->debug(qq{col_name: $col_name}); push @columns, join(q{ }, $col_name); # TODO: remove trailing whitespace } OPERATION: foreach my $operation (@{ $view->{ops} }) { $self->{log}->debug($view->{name} . q{: operation: } . Dumper($operation)); if (ref($operation) ne 'ARRAY') { $self->{log} ->error(q{Error in view attList input - expect an ARRAY ref, got } . ref($operation)); next OPERATION; } my ($opname, $optype) = ($operation->[0], $operation->[1]); # skip grants next OPERATION if $optype eq q{grant}; if ($optype eq q{from}) { push @from, $opname; } elsif ($optype eq q{where}) { push @where, $opname; } elsif ($optype eq q{order by}) { push @orderby, $opname; } elsif ($optype eq q{group by}) { push @groupby, $opname; } else { # unsupported view operation type $self->{log}->warn(qq{ unsupported view operation type '$optype'}); } } my $retval = qq{create view } . $view->{name} . q{ as select } . $self->{newline} . $self->{indent} . join($self->{column_separator}, @columns) . $self->{newline} . $self->{indent} . q{ from } . join($self->{column_separator}, @from) . $self->{newline} . $self->{indent}; # optional values $retval .= q{ where } . join($self->{newline} . $self->{indent}, @where) . $self->{newline} . $self->{indent} if (scalar(@where)); $retval .= q{ group by } . join($self->{column_separator}, @groupby) if (scalar(@groupby)); $retval .= q{ order by } . join($self->{column_separator}, @orderby) if (scalar(@orderby)); # add semi colon or equivalent $retval .= $self->{end_of_statement} . $self->{newline}; if ($self->{log}->is_debug()) { $self->{log}->debug(q{view: $retval}); } return $retval; } # Create sql for given association. sub _get_create_association_sql { my ($self, $association) = @_; # Sanity checks on input if (ref($association) ne 'ARRAY') { $self->{log} ->error(q{Error in association input - cannot create association sql!}); return; } my ( $table_name, $constraint_name, $key_column, $ref_table, $ref_column, $constraint_action ) = @{$association}; # Shorten constraint name, if necessary (DB2 only) $constraint_name = $self->_create_constraint_name($constraint_name); # Add backticks to table names if option is enabled $table_name = $self->_quote_identifier($table_name); $ref_table = $self->_quote_identifier($ref_table); return qq{alter table $table_name add constraint $constraint_name } . $self->{newline} . $self->{indent} . qq{ foreign key ($key_column)} . $self->{newline} . $self->{indent} . qq{ references $ref_table ($ref_column) $constraint_action} . $self->{end_of_statement} . $self->{newline}; } # Added only so that it can be overridden (e.g. in DB2.pm) sub _create_constraint_name { my ($self, $tablename) = @_; return if !$tablename; return $tablename; } # Create sql for all indices for given table. sub _get_create_index_sql { my ($self, $table) = @_; my $sqlstr = q{}; # Sanity checks on input if (ref($table) ne 'HASH') { $self->{log}->error(q{Error in table input - cannot create index sql!}); return; } OPERATION: foreach my $operation (@{ $table->{ops} }) { if (ref($operation) ne 'ARRAY') { $self->{log}->error( q{Error in ops input - expect an ARRAY ref, got } . ref($operation)); next OPERATION; } # Extract elements (the stereotype is not in use) my ($opname, $optype, $colref, $opstereotype, $opcomment) = ( $operation->[0], $operation->[1], $operation->[2], $operation->[3], $operation->[4] ); # 2nd element can be index, unique index, grant, etc. # Accept "index" only in this context. if ($optype !~ qr/^(unique )?index$/i) { $self->{log}->debug(qq{Skipping optype '$optype' - not (unique) index}); next OPERATION; } # Use operation comment as index option if defined, otherwise # use default (if any) my $idx_opt = (defined $opcomment && $opcomment ne q{}) ? $opcomment : join(q{,}, @{ $self->{index_options} }); $sqlstr .= qq{create $optype $opname on } . $table->{name} . q{ (} . join(q{,}, @{$colref}) . q{) } . $idx_opt . $self->{end_of_statement} . $self->{newline}; } return $sqlstr; } # Common function for all smallpackage statements. Returns statements # for the parsed small packages that matches both db name and the # given keyword (e.g. 'post'). sub _get_smallpackage_sql { my ($self, $keyword, $table_name) = @_; my @statements = (); return unless $self->_check_small_packages(); # Each small package is a hash ref foreach my $sp (@{ $self->{small_packages} }) { # Foreach key in hash, pick those values whose # keys that contains db name and 'keyword': if ($table_name) { push @statements, map { $sp->{$_} } grep(/$self->{db}.*:\s*$keyword\s*\($table_name\)/, keys %{$sp}); } else { push @statements, map { $sp->{$_} } grep(/$self->{db}.*:\s*$keyword/, keys %{$sp}); } } return join($self->{newline}, @statements); } # Add SQL statements BEFORE generated code sub get_smallpackage_pre_sql { my $self = shift; return $self->_get_smallpackage_sql(q{pre}); } # Add SQL statements AFTER generated code sub get_smallpackage_post_sql { my $self = shift; return $self->_get_smallpackage_sql(q{post}); } # SQL clauses to add at the end of the named table definitions sub get_smallpackage_table_sql { my $self = shift; return $self->{log}->logdie("NOTIMPL"); } # SQL clauses to add at the end of the named table primary key # constraints sub get_smallpackage_pk_sql { my $self = shift; return $self->{log}->logdie("NOTIMPL"); } # SQL clauses to add at the end of the named table column definitions sub get_smallpackage_column_sql { my $self = shift; my ($table_name) = @_; my $clause = $self->_get_smallpackage_sql(q{columns}, $table_name); if ($clause ne '') { $clause =~ s/\n(.*?)/\n$self->{indent}$1/g; $clause = ',' . $self->{newline} . $self->{indent} . $clause; return $clause; } return ''; } # SQL clauses to add at the end of the named table index definitions sub get_smallpackage_index_sql { my $self = shift; return $self->{log}->logdie("NOTIMPL"); } # store macro for generating statements BEFORE generated code sub get_smallpackage_macropre_sql { my $self = shift; return $self->{log}->logdie("NOTIMPL"); } # store macro for generating statements AFTER generated code sub get_smallpackage_macropost_sql { my $self = shift; return $self->{log}->logdie("NOTIMPL"); } # typemap replace sub map_user_type { my ($self, $col_type) = @_; return $col_type if !$self->{typemap}; return $col_type if !exists($self->{typemap}->{ $self->{db} }); #$self->{log}->debug("typemap: " . Dumper($self->{typemap})); my ($orgname, $orgsize) = $self->{utils}->split_type($col_type); #return $col_type if !exists( $self->{typemap}->{ $self->{db} }->{$orgname} ); if (exists($self->{typemap}->{ $self->{db} }->{$orgname})) { my $arref = $self->{typemap}->{ $self->{db} }->{$orgname}; no warnings q[uninitialized]; my ($newname, $newsize) = @$arref; #$self->{log}->debug("typemap arref match: " . Dumper($arref)); # return newname + newsize if orgsize is undef return $newname . $newsize if !$orgsize; # return newname + newsize if orgsize equals newsize return $newname . $newsize if $orgsize eq $newsize; # return newname + orgsize if newsize is undef return $newname . $orgsize if !$newsize; # else error $self->{log} ->error(qq[Error in typemap usage: Cannot map from $col_type to $newname] . $newsize); } # Return the original type is we can't find a typemap replacement return $col_type; } # Add quotes (backticks) to identifier if option is set and db-type # supports it (i.e. mysql-innodb). See also Output/MySQL/InnoDB.pm sub _quote_identifier { my ($self, $identifier) = @_; return $identifier; } 1; __END__ =back Parse-Dia-SQL-0.31/lib/Parse/Dia/SQL/Output/0000755000175000017500000000000013672477314016203 5ustar affaffParse-Dia-SQL-0.31/lib/Parse/Dia/SQL/Output/MySQL/0000755000175000017500000000000013672477314017150 5ustar affaffParse-Dia-SQL-0.31/lib/Parse/Dia/SQL/Output/MySQL/MyISAM.pm0000644000175000017500000000265413672475055020554 0ustar affaffpackage Parse::Dia::SQL::Output::MySQL::MyISAM; # $Id: MyISAM.pm,v 1.4 2009/03/02 13:41:39 aff Exp $ =pod =head1 NAME Parse::Dia::SQL::Output::MySQL::MyISAM - Create SQL for MySQL MyISAM. =head1 DESCRIPTION Note that MySQL has support for difference storage engines. Each storage engine has its' own properties and the respective SQL differs. =head1 SEE ALSO Parse::Dia::SQL::Output Parse::Dia::SQL::Output::MySQL Parse::Dia::SQL::Output::MySQL::InnoDB =cut use warnings; use strict; use Data::Dumper; use File::Spec::Functions qw(catfile); use lib q{lib}; use base q{Parse::Dia::SQL::Output::MySQL}; # extends require Parse::Dia::SQL::Logger; require Parse::Dia::SQL::Const; =head2 new The constructor. =cut sub new { my ( $class, %param ) = @_; my $self = {}; $param{db} = q{mysql-myisam}; $param{table_postfix_options} = ['ENGINE=MyISAM','DEFAULT CHARSET=latin1'], $self = $class->SUPER::new(%param); bless( $self, $class ); return $self; } =head2 get_view_create Views are not supported on MyISAM. Warn and return undef. =cut sub get_view_create { my $self = shift; $self->{log}->error(q{Views are not supported on MyISAM - Views not created.}); return; } =head2 get_view_drop Views are not supported on MyISAM. Warn and return undef. =cut sub get_view_drop { my $self = shift; $self->{log}->error(q{Views are not supported on MyISAM - Views not dropped.}); return; } 1; __END__ Parse-Dia-SQL-0.31/lib/Parse/Dia/SQL/Output/MySQL/InnoDB.pm0000644000175000017500000000424413672475055020623 0ustar affaffpackage Parse::Dia::SQL::Output::MySQL::InnoDB; # $Id: InnoDB.pm,v 1.4 2009/03/13 16:05:59 aff Exp $ =pod =head1 NAME Parse::Dia::SQL::Output::MySQL::InnoDB - Create SQL for MySQL InnoDB. =head1 DESCRIPTION Note that MySQL has support for difference storage engines. Each storage engine has its' own properties and the respective SQL differs. =head1 SEE ALSO Parse::Dia::SQL::Output Parse::Dia::SQL::Output::MySQL Parse::Dia::SQL::Output::MySQL::InnoDB =cut use warnings; use strict; use Data::Dumper; use File::Spec::Functions qw(catfile); use lib q{lib}; use base q{Parse::Dia::SQL::Output::MySQL}; # extends require Parse::Dia::SQL::Logger; require Parse::Dia::SQL::Const; =head2 new() The constructor. =cut sub new { my ($class, %param) = @_; my $self = {}; $param{db} = q{mysql-innodb}; $param{table_postfix_options} = [ 'ENGINE=InnoDB', 'DEFAULT CHARSET=latin1' ], $self = $class->SUPER::new(%param); bless($self, $class); #die "backticks:" . $self->{backticks}; # MySQL-InnoDB only $self->{BACKTICK_CHAR} = q{`}; return $self; } # Drop all foreign keys sub _get_fk_drop { my $self = shift; my $sqlstr = ''; return unless $self->_check_associations(); # drop fk foreach my $association (@{ $self->{associations} }) { my ($table_name, $constraint_name, undef, undef, undef, undef) = @{$association}; # Add backticks to column name if option is enabled $table_name = $self->_quote_identifier($table_name); $constraint_name = $self->_quote_identifier($constraint_name); $sqlstr .= qq{alter table $table_name drop foreign key $constraint_name } . $self->{end_of_statement} . $self->{newline}; } return $sqlstr; } # Add quotes (`backticks`) to identifier if option is set and db-type # supports it (i.e. mysql-innodb). Used to enclosed table name, index # name etc with `backticks` sub _quote_identifier { my ( $self, $identifier ) = @_; # Add backticks to column name if option is enabled if ($self->{backticks}) { $identifier = $self->{BACKTICK_CHAR} . $identifier . $self->{BACKTICK_CHAR}; } return $identifier; } 1; __END__ Parse-Dia-SQL-0.31/lib/Parse/Dia/SQL/Output/Oracle.pm0000644000175000017500000000244113672475055017747 0ustar affaffpackage Parse::Dia::SQL::Output::Oracle; # $Id: Oracle.pm,v 1.2 2009/03/02 13:41:39 aff Exp $ =pod =head1 NAME Parse::Dia::SQL::Output::Oracle - Create SQL for Oracle. =head1 SEE ALSO Parse::Dia::SQL::Output =cut use warnings; use strict; use Data::Dumper; use File::Spec::Functions qw(catfile); use lib q{lib}; use base q{Parse::Dia::SQL::Output}; # extends require Parse::Dia::SQL::Logger; require Parse::Dia::SQL::Const; =head2 new The constructor. Arguments: =cut sub new { my ( $class, %param ) = @_; my $self = {}; # Set defaults for oracle $param{db} = q{oracle}; $param{object_name_max_length} = $param{object_name_max_length} || 30; $self = $class->SUPER::new(%param); bless( $self, $class ); return $self; } =head2 _get_drop_index_sql Create drop index sql for given index. Discard tablename. =cut sub _get_drop_index_sql { my ( $self, $tablename, $indexname ) = @_; return qq{drop index $indexname cascade constraints} . $self->{end_of_statement} . $self->{newline}; } =head2 _get_drop_schema_sql Oracle do not support keyword 'if exists' in 'drop table' statement =cut sub _get_drop_schema_sql { my ($self, $tablename) = @_; return qq{drop table $tablename} . $self->{end_of_statement} . $self->{newline}; } 1; __END__ Parse-Dia-SQL-0.31/lib/Parse/Dia/SQL/Output/Informix.pm0000644000175000017500000000141613672475055020336 0ustar affaffpackage Parse::Dia::SQL::Output::Informix; # $Id: Informix.pm,v 1.2 2009/03/02 13:41:39 aff Exp $ =pod =head1 NAME Parse::Dia::SQL::Output::Informix - Create SQL for Informix. =head1 SEE ALSO Parse::Dia::SQL::Output =cut use warnings; use strict; use Data::Dumper; use File::Spec::Functions qw(catfile); use lib q{lib}; use base q{Parse::Dia::SQL::Output}; # extends require Parse::Dia::SQL::Logger; require Parse::Dia::SQL::Const; =head2 new The constructor. Arguments: =cut sub new { my ( $class, %param ) = @_; my $self = {}; # Set defaults for informix $param{db} = q{informix}; $param{object_name_max_length} = $param{object_name_max_length} || 30; $self = $class->SUPER::new(%param); bless( $self, $class ); return $self; } 1; __END__ Parse-Dia-SQL-0.31/lib/Parse/Dia/SQL/Output/HTML.pm0000644000175000017500000007110513672475055017311 0ustar affaffpackage Parse::Dia::SQL::Output::HTML; # $Id: $ =pod =head1 NAME Parse::Dia::SQL::Output::HTML - Create HTML documentation. =head1 SYNOPSIS use Parse::Dia::SQL; my $dia = Parse::Dia::SQL->new( file => 'foo.dia', db => 'html' [ , htmlformat => {formatfile} ] ); print $dia->get_sql(); =head1 DESCRIPTION This sub-class creates HTML formatted database documentation. HTML formatting is controlled by templates selected with the optional I parameter which supplies a format file. See L for more. The generated HTML is intended to be useful rather than beautiful. This sub-class follows the same structure as the rdbms output sub-classes with the intent of maintaining consistency, even though this give less than optimum efficiency. =cut use warnings; use strict; use Text::Table; use Data::Dumper; use File::Spec::Functions qw(catfile); use lib q{lib}; use base q{Parse::Dia::SQL::Output}; # extends use Config; require Parse::Dia::SQL::Logger; require Parse::Dia::SQL::Const; =head2 new The constructor. Object names in HTML have no inherent limit. 64 has been arbitrarily chosen. =cut sub new { my ( $class, %param ) = @_; my $self = {}; # Set defaults for sqlite $param{db} = q{html}; $param{object_name_max_length} = $param{object_name_max_length} || 64; $param{htmlformat} = $param{htmlformat} || ''; $self = $class->SUPER::new( %param ); bless( $self, $class ); $self->{dbdata} = {}; # table data, keyed by tablename $self->{htmltemplate} = {}; # html template elements $self->set_html_template($param{htmlformat}); # find the template elements based on the selected format return $self; } =head2 get_sql Return all sql documentation. First build the data structures: schema create view create permissions create inserts associations create (indices first, then foreign keys) Then generate the output: html start html comments body start generate main html body end html end =cut sub get_sql { my $self = shift; ## no critic (NoWarnings) no warnings q{uninitialized}; $self->get_schema_create(); $self->get_view_create(); $self->get_permissions_create(); $self->get_inserts(); $self->get_associations_create(); my $html = '' . $self->_get_preamble() . $self->_get_comment() . $self->get_smallpackage_pre_sql() . $self->generate_html() . $self->get_smallpackage_post_sql() . $self->_get_postscript() ; return $html; } =head2 _get_preamble HTML Header =cut sub _get_preamble { my $self = shift; my $files_word = (scalar(@{ $self->{files} }) > 1) ? q{Input files} : q{Input file}; my $data = $self->{htmltemplate}{htmlpreamble}; # File name my $value = $self->{files}[0]; $data =~ s/{filename}/$value/mgi; # todo: meta tags? return $data } =head2 _get_comment Comment for HTML Header =cut sub _get_comment { my $self = shift; my $files_word = (scalar(@{ $self->{files} }) > 1) ? q{Input files} : q{Input file}; $self->{gentime} = scalar localtime(); my @arr = ( [ q{Parse::SQL::Dia}, qq{version $Parse::Dia::SQL::VERSION} ], [ q{Documentation}, q{http://search.cpan.org/dist/Parse-Dia-SQL/} ], [ q{Environment}, qq{Perl $], $^X} ], [ q{Architecture}, qq{$Config{archname}} ], [ q{Target Database}, $self->{db} ], [ $files_word, join(q{, }, @{ $self->{files} }) ], [ q{Generated at}, $self->{gentime} ], ); $self->{filename} = join(q{, }, @{ $self->{files} }); my $value = ''; my $data = $self->{htmltemplate}{htmlcomment}; my $tb = Text::Table->new(); $tb->load(@arr); $value = scalar $tb->table(); $data =~ s/{htmlcomment}/$value/mgi; return $data; } =head2 get_smallpackage_pre_sql HTML Body start =cut sub get_smallpackage_pre_sql { my $self = shift; my $data; $data = $self->{htmltemplate}{htmlstartbody}; return $data } =head2 get_smallpackage_post_sql HTML Body close =cut sub get_smallpackage_post_sql { my $self = shift; my $data; $data = $self->{htmltemplate}{htmlendbody}; $data =~ s/{gentime}/$self->{gentime}/mgi; return $data } =head2 _get_postscript HTML close =cut sub _get_postscript { my $self = shift; my $data = ''; $data = $self->{htmltemplate}{htmlend}; return $data } =head2 _get_create_table_sql Extracts the documentation details for a single table. =cut sub _get_create_table_sql { my ( $self, $table ) = @_; #my $sqlstr = ''; my $temp; my $comment; my $tablename; my $update; my $primary_keys = ''; my $order = 0; my $tabletemplate = ''; my $tablerowemplate = ''; my $tabledata = ''; my $tablerowdata = ''; # Table name $tablename = $table->{name}; $self->{'dbdata'}{$tablename} = {}; # Comments 1 - strip the autoupdate bits $comment = $table->{comment}; if ( !defined( $comment ) ) { $comment = ''; } if ( $comment ne '' ) { $comment =~ s/\n//g; $comment =~ s///mgi; } # Comments 2 - just the autoupdate bits $update = $table->{comment}; if ( !defined( $update ) ) { $update = ''; } if ( $update =~ //mi ) { $update = $3; # update code } # Set up build the table documentation $self->{'dbdata'}{$tablename}{'name'} = $tablename; $self->{'dbdata'}{$tablename}{'comment'} = $comment; $self->{'dbdata'}{$tablename}{'autoupdate'} = $update; $self->{'dbdata'}{$tablename}{'fields'} = {}; # field list, keyed by field name $self->{'dbdata'}{$tablename}{'keyfields'} = {}; # primary key fields $self->{'dbdata'}{$tablename}{'ref_by'} = {}; # tables that use this as a FK $self->{'dbdata'}{$tablename}{'ref_to'} = {}; # tables that this uses for FK $self->{'dbdata'}{$tablename}{'permissions'} = []; # permissions array $self->{'dbdata'}{$tablename}{'indices'} = {}; # indices keyed by index name # Fields # Check not null and primary key property for each column. Column # visibility is given in $columns[3]. A value of 2 in this field # signifies a primary key (which also must be defined as 'not null'. $tablerowdata = ''; foreach my $column (@{ $table->{attList} }) { if (ref($column) ne 'ARRAY') { $self->{log} ->error(q{Error in view attList input - expect an ARRAY ref!}); next COLUMN; } # Don't warn on uninitialized values here since there are lots # of them. ## no critic (ProhibitNoWarnings) no warnings q{uninitialized}; # Field sequence: my ($col_name, $col_type, $col_val, $col_vis, $col_com) = @{$column}; $self->{'dbdata'}{$tablename}{'fields'}{$col_name} = { 'name' => $col_name, 'type' => $col_type, 'default' => $col_val, 'comment' => $col_com, 'order' => $order, }; $order ++; ## Add 'not null' if field is primary key if ($col_vis == 2) { $self->{'dbdata'}{$tablename}{'fields'}{$col_name}{'default'} = 'not null'; $self->{'dbdata'}{$tablename}{'keyfields'}{$col_name} = 1; } } return ''; } =head2 get_schema_drop Do nothing =cut sub get_schema_drop { return ''; } =head2 get_view_drop Do nothing =cut sub get_view_drop { return ''; } =head2 _get_fk_drop Do nothing =cut sub _get_fk_drop { return ''; } =head2 _get_drop_index_sql Do nothing =cut sub _get_drop_index_sql { return ''; } =head2 get_permissions_create Permissions are formatted as C<{type} {name} to {list of roles}> where: C is the operation C, C etc C is the permission name C