-
-
\ No newline at end of file
diff --git a/lib/NCover/Explorer/ActiproEULA.html b/lib/NCover/Explorer/ActiproEULA.html
deleted file mode 100644
index 1f05a9df..00000000
--- a/lib/NCover/Explorer/ActiproEULA.html
+++ /dev/null
@@ -1,287 +0,0 @@
-
-
- End-User License Agreement (EULA)
-
-
-
-
-
-
END-USER LICENSE AGREEMENT FOR ACTIPRO SOFTWARE LLC SOFTWARE
-
-
-IMPORTANT - READ CAREFULLY: This Actipro Software LLC ("Actipro") End-User License Agreement ("EULA")
-is a legal agreement between you (“Licensee”), a developer of software applications, and Actipro for the Actipro software product
-accompanying this EULA, which includes computer software and may include associated source code, media, printed materials,
-and "on-line" or electronic documentation ("SOFTWARE PRODUCT"). By installing, copying, or otherwise using the SOFTWARE PRODUCT,
-you agree to be bound by the terms of this EULA. If you do not agree to the terms of this EULA, do not install, use, distribute
-in any manner, or replicate in any manner, any part, file or portion of the SOFTWARE PRODUCT.
-
-
-
-The SOFTWARE PRODUCT is protected by copyright laws and international copyright treaties, as well as other intellectual property laws and treaties. The SOFTWARE PRODUCT is licensed, not sold.
-
-
-
-The Licensee is considered to be an authorized licensee (“Authorized”) if the Licensee has legitimately obtained a registered license for the SOFTWARE PRODUCT from Actipro or an authorized Actipro reseller.
-
-
-
-RIGOROUS ENFORCEMENT OF INTELLECTUAL PROPERTY RIGHTS.
-If the licensed right of use for this SOFTWARE PRODUCT is purchased by the Licensee with any intent to reverse engineer,
-decompile, create derivative works, and the exploitation or unauthorized transfer of, any Actipro intellectual property and
-trade secrets, to include any exposed methods or source code where provided, no licensed right of use shall exist, and any products
-created as a result shall be judged illegal by definition of all applicable law. Any sale or resale of intellectual property or
-created derivatives so obtained will be prosecuted to the fullest extent of all local, federal and international law.
-
-
-
-GRANT OF LICENSE. This EULA, if legally executed as defined herein, licenses and so grants the Licensee the following rights:
-
-
-
-Evaluation. If the downloaded SOFTWARE PRODUCT is designated as an Evaluation Release (“Evaluation Release”),
-the Licensee is granted a license for a period of only fifteen (15) days after installation of the Evaluation Release
-of the SOFTWARE PRODUCT ("Evaluation Period"). After the Evaluation Period, the Licensee must either:
-
-
Delete the SOFTWARE PRODUCT and all related files from ALL computers onto which it was installed or copied, or
-
Contact Actipro or one of its authorized resellers to purchase the SOFTWARE PRODUCT.
-
-
-
-
-The Licensee may use the Evaluation Release of the SOFTWARE PRODUCT for evaluation purposes only.
-The Licensee may not distribute ANY of the files, in any form or manner, provided with the Evaluation Release of the
-SOFTWARE PRODUCT to ANY PARTIES.
-
-
-
-Development. Actipro grants the Licensee the non-exclusive license to install and use multiple copies of the
-SOFTWARE PRODUCT or any prior version for the sole purpose of developing any number of end user applications that
-operate in conjunction with the SOFTWARE PRODUCT. If the Licensee is not Authorized, the Licensee may not use the
-SOFTWARE PRODUCT beyond the Evaluation Period.
-
-
-
-If the Licensee has purchased a single developer license (“Single Developer License”), the Licensee is Authorized
-to use the SOFTWARE PRODUCT indefinitely beyond the Evaluation Period. A Single Developer License for the SOFTWARE PRODUCT
-may not be shared or used concurrently by more than one individual developer. In a project that uses the SOFTWARE PRODUCT,
-each individual developer on the project requires a separate Single Developer License, regardless of whether they directly
-use the component or not. Single Developer Licenses may also be obtained in team discount packs.
-
-
-
-If the Licensee has purchased a site license (“Site License”), each of the developers at a single physical location is
-considered Authorized according to the terms and conditions of the Single Developer License. Each additional physical
-location requires an additional Site License to be considered Authorized.
-
-
-
-If the Licensee has purchased an enterprise license (“Enterprise License”), all developers in the Licensee's organization,
-regardless of location, are considered Authorized according to the terms and conditions of the Single Developer License.
-
-
-
-If the Licensee has purchased a blueprint license (“Blueprint License”), each of the Authorized developers for the SOFTWARE PRODUCT is
-considered Authorized to access source code for the SOFTWARE PRODUCT ("Source Code").
-The Blueprint License must be purchased at the same time as a Site License or Enterprise License.
-Source Code may exclude Actipro proprietary licensing code.
-The sale of Blueprint Licenses is considered final and neither the SOFTWARE PRODUCT nor Source Code may be returned under any circumstances.
-
-
-
-Duplication and Distribution. The SOFTWARE PRODUCT may include certain files ("Redistributables") intended for distribution
-by the Licensee to the users of programs the Licensee creates. Redistributables include, for example, those files identified in
-printed or electronic documentation as redistributable files, or those files pre-selected for deployment by an install utility
-provided with the SOFTWARE PRODUCT (if any). In any event, the Redistributables for the SOFTWARE PRODUCT are only those files
-specifically designated as such by Actipro.
-
-
-
-Subject to all of the terms and conditions in this EULA, if the Licensee is Authorized, Actipro grants the Licensee the non-exclusive,
-royalty-free license to duplicate the Redistributables and to distribute them solely in conjunction with software products
-developed by the Licensee that use them. The Licensee may not supply any means by which end users could incorporate the
-SOFTWARE PRODUCT or portions thereof into their own products.
-
-
-
-Source Code. If the Licensee has purchased a Blueprint License and is Authorized, the Licensee is provided Source Code
-for the SOFTWARE PRODUCT. The following stipulations and restrictions apply to Source Code:
-
-
Source Code shall be considered as part the SOFTWARE PRODUCT and all requirements stated above still apply,
- meaning that developers at a separate site from the one which purchased the Blueprint License are NOT able to work on
- any project created that uses the Source Code, unless that site has also purchased a Blueprint License.
- The only exception is when an Enterprise License has been purchased along with the Blueprint License,
- in which case the Source Code may be used by developers at any site.
-
Actipro grants the Licensee the non-exclusive license to view and modify the Source Code for the sole purposes of education and troubleshooting.
- If the Licensee troubleshoots the Source Code, the Licensee may compile the corrected source code and use and distribute the
- resulting object code solely as a replacement for the corresponding Redistributables the Source Code compiles into.
-
The Licensee may NOT distribute or sell the Source Code, or portions or modifications or derivative works thereof, to any third party
- not Authorized by the Licensee’s Blueprint License(s), without explicit permission by Actipro.
-
The Licensee may not compete against Actipro by repackaging, recompiling, or renaming the SOFTWARE PRODUCT for which the
- Licensee purchased Source Code. Any derivative works based on the Source Code are illegal to be created or sold if they compete
- in any way with the SOFTWARE PRODUCT or other Actipro products.
-
Any object code that is created by using the Source Code or derivative code based on the Source Code must be obfuscated.
-
Any object code that is created by using the Source Code or derivative code based on the Source Code may NOT bear "ActiproSoftware"
- or the name of the SOFTWARE PRODUCT in the object code assembly name.
-
All Source Code must be kept in its proper "ActiproSoftware" namespace.
-
Actipro shall retain all rights, title and interest in and to all corrections, modifications and derivative works of the Source Code
- created by the Licensee, including all copyrights subsisting therein, to the extent such corrections, modifications or
- derivative works contain copyrightable code or expression derived from the Source Code.
-
The Licensee acknowledges that the Source Code contains valuable and proprietary trade secrets of Actipro, and agrees to expend
- every effort to insure its confidentiality.
-
Source Code may be obtained by coordinating with Actipro during the support period for the Blueprint License, typically one year
- in duration, starting on the date of purchase of the Blueprint License.
-
-
-
-
-Storage/Network Use. The Licensee may also store or install a copy of the SOFTWARE PRODUCT on a storage device,
-such as a network server, used only to install or run the SOFTWARE PRODUCT on the the Licensee’s other computers over an internal network;
-however, the Licensee must acquire and dedicate a Single Developer License for each separate individual developer who wishes to use
-the SOFTWARE PRODUCT.
-
-
-
-DESCRIPTION OF OTHER RIGHTS AND LIMITATIONS.
-
-
-
-Not for Resale Software. If the SOFTWARE PRODUCT is labeled and provided as "Not for Resale" or "NFR", then, notwithstanding
-other sections of this EULA, the Licensee may not resell, distribute, or otherwise transfer for value or benefit in any manner,
-the SOFTWARE PRODUCT or any derivative work using the SOFTWARE PRODUCT. The Licensee may not transfer, rent, lease, lend, copy,
-modify, translate, sublicense, time-share or electronically transmit the SOFTWARE PRODUCT, media or documentation.
-This also applies to any and all intermediate files, source code, and compiled executables.
-
-
-
-Limitations on Reverse Engineering, Decompilation, and Disassembly. The Licensee may not reverse engineer, decompile,
-create derivative works, modify, translate, or disassemble the SOFTWARE PRODUCT, and only to the extent that such activity is
-expressly permitted by applicable law notwithstanding this limitation. The Licensee agrees to take all reasonable, legal and
-appropriate measures to prohibit the illegal dissemination of the SOFTWARE PRODUCT or any of its constituent parts and redistributables
-to the fullest extent of all applicable local, US Codes and International Laws and Treaties regarding anti-circumvention, including
-but not limited to, the Geneva and Berne World Intellectual Property Organization (WIPO) Diplomatic Conferences.
-
-
-
-Rental. The Licensee may not rent, lease, or lend the SOFTWARE PRODUCT.
-
-
-
-Separation of Components, Their Constituent Parts and Redistributables. The SOFTWARE PRODUCT is licensed as a single product.
-The SOFTWARE PRODUCT and its constituent parts and any provided redistributables may not be reverse engineered, decompiled, disassembled,
-nor placed for distribution, sale, or resale as individual creations by the Licensee or any individual not expressly given
-such permission by Actipro. The provision of Source Code, if included with the SOFTWARE PRODUCT, does not constitute transfer of any
-legal rights to such code, and resale or distribution of all or any portion of all Source Code and intellectual property will be prosecuted
-to the fullest extent of all applicable local, federal and international laws. All Actipro libraries, Source Code, Redistributables and
-other files remain Actipro's exclusive property. The Licensee may not distribute any files, except those that Actipro has expressly
-designated as Redistributable.
-
-
-
-Installation and Use. The license granted in this EULA for the Licensee to create his/her own compiled programs and distribute
-the Licensee’s programs and the Redistributables (if any), is subject to all of the following conditions:
-
-
All copies of the programs the Licensee creates must bear a valid copyright notice, either their own or the Actipro copyright
- notice that appears on the SOFTWARE PRODUCT.
-
The Licensee may not remove or alter any Actipro copyright, trademark or other proprietary rights notice contained in any portion
- of Actipro libraries, source code, Redistributables or other files that bear such a notice.
-
Actipro provides no warranty at all to any person, and the Licensee will remain solely responsible to anyone receiving the
- Licensee’s programs for support, service, upgrades, or technical or other assistance, and such recipients will have no right
- to contact Actipro for such services or assistance.
-
The Licensee will indemnify and hold Actipro, its related companies and its suppliers, harmless from and against any claims or
- liabilities arising out of the use, reproduction or distribution of the Licensee’s programs.
-
The Licensee’s programs containing the SOFTWARE PRODUCT must be written using a licensed, registered copy of the SOFTWARE PRODUCT.
-
The Licensee’s programs must add primary and substantial functionality, and may not be merely a set or subset of any of the libraries,
- Source Code, Redistributables or other files of the SOFTWARE PRODUCT.
-
The Licensee may not use Actipro's or any of its suppliers' names, logos, or trademarks to market the Licensee’s programs,
- unless expressly given such permission by Actipro.
-
-
-
-
-Support Services. Actipro may provide the Licensee with support services related to the SOFTWARE PRODUCT ("Support Services").
-Use of Support Services is governed by Actipro policies and programs described in the user manual, in on-line documentation and/or other
-Actipro provided materials. Any supplemental software code provided to the Licensee as part of the Support Services shall be considered
-part of the SOFTWARE PRODUCT and subject to the terms and conditions of this EULA. With respect to technical information the Licensee
-provides to Actipro as part of the Support Services, Actipro may use such information for its business purposes, including for product
-support and development.
-
-
-
-Software Transfer. The Licensee may NOT permanently or temporarily transfer ANY of the Licensee’s rights under this EULA to any
-individual or entity. Regardless of any modifications which the Licensee makes and regardless of how the Licensee might compile, link,
-and/or package the Licensee’s programs, under no circumstances may the libraries, redistributables, and/or other files of the
-SOFTWARE PRODUCT (including any portions thereof) be used for developing programs by anyone other than the Licensee. Only the Licensee
-as the licensed end user has the right to use the libraries, redistributables, or other files of the SOFTWARE PRODUCT (or any portions thereof)
-for developing programs created with the SOFTWARE PRODUCT. In particular, the Licensee may not share copies of the Source Code or
-Redistributables with other co-developers.
-
-
-
-Termination. Without prejudice to any other rights or remedies, Actipro will terminate this EULA upon the Licensee’s failure to
-comply with all the terms and conditions of this EULA. In such event, the Licensee must destroy all copies of the SOFTWARE PRODUCT and
-all of its component parts including any related documentation, and must remove ANY and ALL use of such technology immediately from any
-applications using technology contained in the SOFTWARE PRODUCT developed by the Licensee, whether in native, altered or compiled state.
-
-
-
-UPGRADES. If the SOFTWARE PRODUCT is labeled as an upgrade, the Licensee must be properly licensed to use the SOFTWARE PRODUCT
-identified by Actipro as being eligible for the upgrade in order to use the SOFTWARE PRODUCT. A SOFTWARE PRODUCT labeled as an upgrade
-replaces and/or supplements the SOFTWARE PRODUCT that formed the basis for the Licensee’s eligibility for the upgrade, and together
-constitute a single SOFTWARE PRODUCT. The Licensee may use the resulting upgraded SOFTWARE PRODUCT only in accordance with all the
-terms of this EULA.
-
-
-
-COPYRIGHT. All title and copyrights in and to the SOFTWARE PRODUCT (including but not limited to any images, demos, source code,
-intermediate files, packages, photographs, animations, video, audio, music, text, and "applets" incorporated into the SOFTWARE PRODUCT),
-the accompanying printed materials, and any copies of the SOFTWARE PRODUCT are owned by Actipro or its subsidiaries.
-The SOFTWARE PRODUCT is protected by copyright laws and international treaty provisions. Therefore, the Licensee must treat the
-SOFTWARE PRODUCT like any other copyrighted material except that the Licensee may install the SOFTWARE PRODUCT for use by the Licensee.
-The Licensee may not copy any printed materials accompanying the SOFTWARE PRODUCT.
-
-
-
-GENERAL PROVISIONS. This EULA may only be modified in writing signed by the Licensee and an authorized officer of Actipro.
-If any provision of this EULA is found void or unenforceable, the remainder will remain valid and enforceable according to its terms.
-
-
-
-MISCELLANEOUS. If the Licensee acquired this product in the United States, this EULA is governed by the laws of the State of Ohio.
-
-
-
-If this SOFTWARE PRODUCT was acquired outside the United States, then the Licensee, agrees and ascends to the adherence to all
-applicable international treaties regarding copyright and intellectual property rights which shall also apply.
-In addition, the Licensee agrees that any local law(s) to the benefit and protection of Actipro ownership of, and interest in,
-its intellectual property and right of recovery for damages thereto will also apply.
-
-
-
-Should you have any questions concerning this EULA, or if you desire to contact Actipro for any reason, please contact us via our
-support web pages at http://www.actiprosoftware.com.
-
-
-
-NO WARRANTIES. ACTIPRO EXPRESSLY DISCLAIMS ANY WARRANTY FOR THE SOFTWARE PRODUCT. THE PRODUCT AND ANY RELATED DOCUMENTATION IS PROVIDED
-"AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE, OR NONINFRINGEMENT. THE ENTIRE RISK ARISING OUT OF USE OR PERFORMANCE OF THE PRODUCT REMAINS WITH THE LICENSEE.
-
-
-
-LIMITATION OF LIABILITY. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL ACTIPRO OR ITS SUPPLIERS BE LIABLE
-FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF
-BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
-INABILITY TO USE THE SOFTWARE PRODUCT OR THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES, EVEN IF ACTIPRO HAS BEEN ADVISED OF
-THE POSSIBILITY OF SUCH DAMAGES.
-
-
-
-Copyright (c) 2002-2007 Actipro Software LLC. All rights reserved.
-
This tool allows you to open a coverage.xml file produced by
- NCover and navigate the source code. The
- source code is highlighted to clearly show which statements were visited
- and not visited. You can filter, sort and report on the coverage results.
-
NCoverExplorer has been tested with both NCover 1.3.3 and up to the latest NCover 1.5.7. It will NOT
- work with NCover 1.4.6. Note that NCover 1.5.x only works with .NET 2.0 and requires at least NCoverExplorer 1.3.5
- and/or a TestDriven.Net build > 2.0.1786 due to a limitation in NCover or else you will get duplicate nodes in your
- coverage results.
-
Jamie Cansdale now offers a "Test with... Coverage" feature
- in the latest version of his excellent TestDriven.Net
- tool. This will automatically launch NCoverExplorer to display the results
- of running unit test(s) under code coverage with NCover. Note that as of build 1341
- TestDriven.Net now works using both the latest version of NCover (1.5.x) and the earlier NCover 1.3.3 version.
-
My solution I used at work was a combination of NAnt and NAntRunner
- (the VS.Net add-in) to perform something similar. I have NAnt tasks to:
-
-
- Perform the build.
-
-
- Execute NCover while running unit tests (either all unit tests or those for
- a specific fixture using the /fixture feature of NUnit).
-
-
- Launch NCoverExplorer displaying the output coverage.xml file.
-
-
-
-
As of NCoverExplorer 1.3.5 you now have another option. There is now an included GUI for
- running NCover directly from within NCoverExplorer and displaying the results.
-
VSTS features of unit testing and code coverage will only be included with the premium bundles
- of the Visual Studio product range - and as such will most likely be priced above what many
- developers and businesses are prepared to pay. For "everyone else" in the market it would seem likely
- that they will continue to utilise open source alternatives.
-
-
Even if you are one of the fortunate developers who can afford VSTS, it still must
- be measured feature-wise against the open source alternatives which in a lot of cases have now been established
- for many years. Developers and managers will weigh up for themselves how important those features are
- as well as other factors such as Microsoft support etc. The nice thing for many of us is that we have a choice...
-
-
We have had a number of people e-mail us and say they prefer TestDriven.Net and NCoverExplorer
- over the VSTS alternative and want to switch off the VSTS ability - that's rather gratifying from our perspective!
-
A number of reasons. At first glance having your code colour coded within the VS.Net IDE may sound
- great. However think about what we are trying to achieve - improving our test code to increase our coverage.
- That means in many cases you want to be editing the unit tests themselves, not the pretty coloured code under test.
- This then requires either a photographic memory or a penchant for continually resizing your IDE/tab groups, as well as an ability
- to not find the colours distracting while editing and refactoring code... not my first choice.
-
-
You may instead find it more convenient to have a separate application window which can be positioned
- on a second screen (you all have at least two don't you?) or ALT-Tab switched between. As of release 1.3.1
- NCoverExplorer allows direct code navigation from method coverage in NCoverExplorer to it's corresponding line
- in the source code file within the VS.Net IDE.
-
-
From a technical perspective an add-in is a non-trivial task - particularly if trying to support all
- the variants of the VS.Net IDE. To do it natively requires VSIP skills which is a trip to the dark side.
- I won't say "never" however and if I find some spare time (or you want to volunteer to help me!) then it might
- happen one day...
-
Depending on your coverage strategy, the code being tested and the extent of your usage of reflection,
- mock objects and/or dependency injection you may determine it unfeasible to try
- to reach 100% coverage everywhere. Some teams readily accept the diminishing returns
- that can apply and instead set a specific blanket coverage goal such as “85%”.
-
-
Assuming you have such a situation and there was no threshold capability,
- you would be stuck forever looking at a "danger red" node in the tree every time you open NCoverExplorer.
- With this feature enabled (by setting a threshold less than 100% in the View->Options dialog) you see
- a more calming mellow “blue” instead...
-
-
As of release 1.3.1 you can now also specify the tolerance as a number of unvisited lines.
- If either of the two threshold conditions are met the node will be coloured appropriately. Note that
- a visit count of zero will always show as uncovered regardless of your tolerance.
-
-
Of course just because you exceed the percentage doesn't mean that the 5% of code unvisited
- isn't the most critical!
-
Please leave a comment on my blog or in the
- NCoverExplorer forums and I will see what I can do.
- NCoverExplorer is by no means my "day job" so no promises can be made but if the idea is indeed a good one which
- will benefit many others I'm sure I can find time...
-
- CTRL+A - Collapse all nodes recursively.
- CTRL+E - Edit in VS.Net at the current caret position.
- CTRL+F - Display the Find Class dialog.
- CTRL+L - Expand all nodes recursively.
- CTRL+N - Run NCover (via configuration dialog).
- CTRL+O - Open coverage xml file.
- CTRL+P - Print current source code class file.
- CTRL+Q - Expand all covered child nodes.
- CTRL+S - Save coverage xml file as displayed (without excluded nodes).
- F2 - Display the options dialog.
- F4 - Display the statistics summary dialog.
- F5 - Reload the current source code file.
- F6 - Display the reports dialog.
- DEL - Exclude node and children from coverage tree and recalculate coverage.
- INS - Include node and children into coverage tree and recalculate coverage.
-
- ALT+1 - Filter (hide) all 100% coverage nodes.
- ALT+2 - Filter (hide) all unvisited (0%) nodes.
- ALT+3 - Filter (hide) all nodes exceeding satisfactory coverage threshold.
- ALT+0 - Remove all filters.
-
- CTRL+1 - Display sequence point coverage report (covered%).
- CTRL+2 - Display sequence point coverage report (covered%) (unvisited seqpnt#).
- CTRL+3 - Display sequence point coverage report (unvisited seqpnt#).
- CTRL+4 - Display function coverage report (visits).
- CTRL+5 - Display function coverage coverage report (covered%).
- CTRL+6 - Display function coverage coverage report (covered%) (unvisited function#).
- CTRL+7 - Display function coverage coverage report (unvisited function#).
-
- CTRL+SHIFT+1 - Sort by name (default).
- CTRL+SHIFT+2 - Sort by name down to class level, with methods sorted by line number.
- CTRL+SHIFT+3 - Sort by coverage percentage ascending.
- CTRL+SHIFT+4 - Sort by coverage percentage ascending.
- CTRL+SHIFT+5 - Sort by #unvisited sequence points ascending.
- CTRL+SHIFT+6 - Sort by #unvisited sequence points ascending.
- CTRL+SHIFT+7 - Sort by max function visit count ascending.
- CTRL+SHIFT+8 - Sort by max function visit count ascending.
- CTRL+SHIFT+9 - Sort by max function coverage percentage ascending.
- CTRL+SHIFT+0 - Sort by max function coverage percentage descending.
-
- ALT+RIGHT - Next unvisited line in the current class.
- ALT+LEFT - Previous unvisited line in the current class.
- ALT+UP - Next unvisited class in the current namespace.
- ALT+DOWN - Previous unvisited class in the current namespace.
-
NCover 1.4.6 has a bug whereby the filenames that it writes into the xml file contain
- undesirable characters. Please use either NCover 1.3.3 or NCover 1.5.x. For more details refer to this blog entry
- here
-
One user reported a bizarre issue where on their machines a simple int.Parse("0") would not work.
- The exact cause is unknown (they had uninstalled some components from their XP installation), however
- switching region settings to something else and back again resolved the issue.
-
The module names included in the module thresholds should not include any path information,
- and are currently case sensitive (must exactly match the module names you see on the NCoverExplorer report).
- The case sensitivity constraint is fixed in NCoverExplorer 1.3.5.
-
-
-
--------------------------------- FAQ last updated Jul 21st 2007.
The latest version of this document is located here.
- For the latest NCoverExplorer news and updates, visit my blog.
-
-
-
v1.4.0 - Sep 16th 2007
-
The following new features were introduced:
-
-
- Major rewrite of the underlying object design for future maintainability. Should improve treeview
- performance for .NET 2.0 users (and load performance for all users) as well as make it easier to
- add new features.
-
-
- Changes to the project setting file format and location, both as used by the NCoverExplorer gui
- and the NCoverExplorer.Console.exe application. If you use the /c argument supplying a configuration
- file to NCoverExplorer then you must modify your project file format. See ConsoleExample.config
- for details (replace the outer tag to be called ConsoleSetting).
-
-
- Replaced ICSharpCode text editor with Actipro which offers far superior features, more attractive
- appearance and provides a more flexible licensing model for the future of NCoverExplorer.
-
-
- A new attribute added into the coverage report xml of "totalSeqPoints" which includes the
- total of any excluded sequence points at that level. In response to a feature request in
- this NCover forum thread to allow
- people to report how much code was excluded from coverage.
-
-
- Add a copy command to the right-click menu for the source code area.
-
-
- Add a print preview command to the File menu.
-
-
- Add support for profiling a specific process module to the Run NCover dialog.
-
-
- Add a /fc (failCombinedMinimum) option to NCoverExplorer.Console.exe for emulating the
- original behaviour of failing based on total coverage to supplement the /f option which
- fails if an individual module is below the coverage threshold.
-
-
-
The following minor changes were made:
-
-
- Rewrite the options dialog to use a VS.Net style property pages approach.
-
-
- Exclusions tab in Options dialog - delete key is now a shortcut to removing an exclusion.
-
-
- Reorder the file menu slightly so Run NCover is separated.
-
-
- Source code window now has a splitter bar.
-
-
- Command line generated for NCover 1.5.7+ in NCover Runner dialog includes the //reg
- option if choosing to register coverlib.dll.
-
-
- Statistics pane auto-sizes the last column to fill the width of the listview.
-
-
- Coverage exclusions now support '?' and more complex wildcard expressions such
- as Test.*.Something*.
-
-
-
The following bug fixes were made:
-
-
- Line number foreground colour not displayed correctly in options dialog tab.
-
-
- Directory not created if not existing when writing output report.
-
-
- Corrected typo in full name of parameter when using /quiet option with NCoverExplorer.Console.
-
-
- Reduce GDI usage by editor control.
- Rnsure Actipro renderer is correctly utilised.
- Turn off text margins in NCover run dialog for editor.
- Ensure C++ code has whole line highlighted even though no sequence point values.
- (Build 1.4.0.6)
-
-
-
-
-
v1.3.6 - Apr 5th 2007
-
Bundled with TestDriven.Net from build 2.5.2078.
-
The following new features were introduced:
-
-
- Added a Find dialog (ctrl+F) to quickly navigate to a class. Wildcards are supported.
-
-
- Added a /q or /quiet option to NCoverExplorer.Console.exe to minimise the output.
-
-
-
The following minor changes were made:
-
-
- Failing if less than a threshold now applies to any assembly not meeting the threshold
- rather than comparing against the total coverage across all assemblies.
-
-
- Add some examples to the NCoverExplorer.Console.exe output for the /help or /? (or no arguments).
-
-
- Pressing ESC on the NCover Runner dialog will now close it.
-
-
- Implement a workaround for poor treeview performance under .NET 2.0.
-
-
- Rather than displaying validation errors automatically "fix" paths with matching trailing
- slashes in the Change Source Path dialog.
-
-
- Writing of coverage files should now match the schema for the relevant NCover version.
- Later NCover versions like 1.5.7 have enhanced the schema, so the results of a merge or
- save from NCoverExplorer should offer a comparative schema in the result.
-
-
- Add a message indicating the return code to the output.
-
-
-
The following bug fixes were made:
-
-
- NCover 1.5.5/6 produce duplicate sequence points. To workaround this fix Jamie Cansdale implemented
- a change for me to the way the methods are identified uniquely. The longer term fix is NCover version 1.5.7
- - this should keep things usable until that is released.
-
-
- Another issue up to at least NCover 1.5.7 is that non-instrumented code does not have the sequence
- points optimised. When merging multiple coverage files NCoverExplorer was incorrectly merging the noops with
- valid instrumented sequence points, resulting in lower coverage information.
-
-
- If CoverageReport.xsl stylesheet already exists in destination output folder for an xml report
- and is marked as read-only then the replace would fail.
-
-
- Drag/drop of coverage.xml files would add to the wrong end of the MRU menu once the maximum
- number of items is reached.
-
-
- If multiple classes in the same file then selecting a class node was not navigating to that
- class in the source code tab. It will now jump to the first unvisited sequence point, or if
- there are none of those the first sequence point in the class.
-
-
- Wildcards for coverage exclusions were only working if placed at the ends, not in the middle
- e.g. *.Tests or Testing.* would work, but xxx.*.yyy would not.
-
-
- Prevent some of the nasty GDI errors in CommandBars code from disrupting the GUI. Longer
- term will utilise another framework.
-
-
- Replacing paths by typing them in had MaxLength set to 50 so impossible to edit long paths
- in the Change Source Path dialog.
-
-
- Merging property nodes under a parent in the tree has a dependency on the ordering of the coverage output
- to ensure they appear properly.
-
-
- When restoring form position from persisted values, ensure it appears on a visible screen,
- catering for the user changing their display settings between sessions.
-
-
- Ensure stylesheet cannot be copied over the top of itself.
-
-
- Supplying a file pattern with no matches to NCoverExplorer.Console.exe was throwing an "Index was
- outside the bounds of the array" exception.
-
-
- Multiple coverage exclusion attributes not supplied correctly to NCover (build 26).
-
-
- Check to make sure node is assigned to a TreeView before getting handle to set text (build 32).
-
-
- Sort sequence point nodes when loading and handle merge case of multiple non-instrumented
- sequence points becoming a single sequence point. (build 36).
-
-
-
-
-
v1.3.5 - Oct 23rd 2006
-
Bundled with TestDriven.Net from build 2.0.1921.
-
The following new features were introduced:
-
-
- Added ability to run NCover from within NCoverExplorer (all versions). User Ctrl+N or
- entries on File menu/toolbar to bring up configuration dialog. After successful
- execution, the resultant coverage file is displayed in NCoverExplorer.
-
-
- Added ability to generate MSBuild, NAnt and command-line scripts for running NCover
- from within NCoverExplorer. See the NCover dialog above.
-
-
- Added new function coverage viewing options and module/class coverage report.
- Indicates the percentage of functions covered rather than the sequence points within each.
- Supported by a new "satisfactory function threshold" and function % sorting options.
-
-
- Background colours can now be customised for coverage nodes in the tree.
-
-
- Reports will now have the current filtering applied, not just the sorting settings.
-
-
- Reports using NCoverExplorer.Console can now have filtering and sorting applied. Use the
- /sort: and /filter: command line arguments, or specify in a .config file (see example.config),
- or use the sort/filter arguments to the NAnt/MSBuild tasks.
-
-
- Sorting and filtering options applied are now persisted and reapplied to the next coverage
- xml file loaded, both in this and future sessions.
-
-
- Added ability to filter out all nodes exceeding coverage threshold.
-
-
- Revamp to the NAnt/MSBuild tasks. Renamed assemblies and namespaces. Included new attribute of
- "AssembliesList" as an alternative to the "Assemblies" group element to allow direct
- specification of a list as you would on the command line. The "Version" attribute is now optional
- - the task determines it from the NCover assembly instead if not specified. Tasks will automatically
- register NCover coverlib.dll using the HKCU entry in the registry - no need for regsvr32 any more!
- NCoverExplorer task now writes it's config file to temp folder for passing to the executable.
-
-
- Added documentation for the NAnt and MSBuild tasks. This is included both in the NCoverExplorer.Extras.zip
- file, as well as being available online for the custom MSBuild Task Help
- and NAnt Task Help.
- Links also available off the Help menu for NCoverExplorer.
-
-
- Added a schema file ConsoleConfig.xsd to the distribution for people wanting to know the exact syntax
- options for creating .config files to pass to NCoverExplorer.Console using the /config switch.
-
-
- Added regular expression support to the coverage exclusions dialog for people wanting more complex queries.
-
-
-
The following minor changes were made:
-
-
- Configuration file change - the ModuleThresholds section in .config files passed to NCoverExplorer.Console now
- uses propercase attribute names to be consistent with the rest of the configuration file.
- i.e. "ModuleName" instead of "moduleName", and "SatisfactoryCoverage" instead of "satisfactoryCoverage". You must update
- your NAnt/MSBuild tasks for NCoverExplorer if you use these. If you instead use the <exec> task with a .config
- file then you should update the case of the entries in this file. This only affects people who have setup coverage exclusions
- at the module level for reporting purposes.
-
-
- If source code is out of date compared to the coverage results, the user is prompted with
- the change source path dialog.
-
-
- If the user chooses a new source code location, the tab is now automatically opened for
- that location rather than requiring the user to click on the tree node again.
-
-
- Added Help->NCoverExplorer Forum menu option to link to the NCover website. Also included
- forum link information on the exception dialog.
-
-
- Added a toolbar button for turning off filtering.
-
-
- Keyboard shortcut change - Changed the keyboard shortcuts for next/previous unvisited class (ALT+UP/DOWN) and
- next/previous unvisited line in class (ALT+LEFT/RIGHT).
-
-
- Remember which tab was last opened in the NCoverExplorer options dialog during an NCoverExplorer session.
-
-
- Replaced references to "transparent.gif" with "shim.gif" in the NCoverExplorerSummary.xsl. The "shim.gif"
- file is a transparent 1x1 gif already distributed with CC.Net.
-
-
- Coverage exclusions for assemblies are now case insensitive.
-
-
- There are no longer two default coverage exclusions added of "*.Tests" and "*.My*" for first time users.
- Intended for demo purposes only but stayed in until now. New users can manually add them if they desire them.
-
-
-
The following bug fixes were made:
-
-
- Overloaded constructors with class level variable declarations were being merged into a single
- constructor in the coverage results as they had the same "start line" of the variable. Now uses
- end line as part of the identifying key for each method.
-
-
- Memory leak from opening and closing tabs displaying source code.
-
-
- .Net 2.0 performance is pretty dire due to crap Microsoft changes to the TreeView control.
- Change to default to .Net 1.1 in NCoverExplorer.exe.config and wrap updates to the tree
- in BeginUpdate/EndUpdate.
-
-
- Parsing Java code would blow up if an accessor had the same name as a nested class (illegal in C#).
-
-
- Bugfix in NCover task where multiple assemblies were specified for NCover 1.5.4, which requires
- separate <assembly> nodes.
-
-
- Bugfix in trying to restore selected node text after refreshing file could raise
- null reference exception.
-
-
- Bugfix so that module names specified in module thresholds when using NCoverExplorer.Console
- are no longer case sensitive for matching.
-
-
- Added support for NCover 1.5.5 - the //q bug is fixed in NCover. Also changed parsing code so that modules
- with a blank assembly name (through using TestDriven.Net) are ignored from the coverage.
-
-
- Bugfix for merge functionality for NCover.Console when wildcards were used with relative paths.
-
-
- Bugfix for naming of xml/html arguments for NCover.Console with relative file paths.
-
-
- Bugfix for drag/drop broken while making the memory usage optimisations during the 1.3.5 beta release.
-
-
- Print button was enabled when no source code displayed resulting in exception.
-
-
-
-
-
v1.3.4 - Jul 10th 2006
-
Bundled with TestDriven.Net from build 2.0.1702.
-
The following new features were introduced:
-
-
- Added toolbar buttons which support moving to the next and previous unvisited code
- within a class or namespace. Shortcut keys of N and P for next/previous unvisited line in the
- current class (or mouse forward/back buttons). Use Ctrl+N and Ctrl+P to navigate to the
- next/previous partially or unvisited class within the namespace (or Ctrl+forward/back mouse buttons).
-
-
- NCoverExplorer.Console.exe now supports saving the merged results of the coverage xml file(s) with
- a /s[ave] option. The NCoverExplorer NAnt and MSBuild tasks have also been enhanced to support this
- with an optional "mergeFileName" attribute.
-
-
- NCoverExplorer.Console.exe now supports wildcards for coverage xml filename(s).
-
-
- NCoverExplorer.Console.exe now supports module level coverage thresholds, rather than just a project
- coverage threshold. This feature allows finer tolerance for both output on the reports and to fail
- a build. Specifying the module thresholds is done either through a .config file (see ConsoleExample.config)
- or through parameters in the NAnt/MSBuild tasks.
-
-
- Added a new summary report showing class coverage per namespace per module.
-
-
- Enhanced the NCoverExplorerSummary.xsl to display summaries of each module.
-
-
- Clicking on a class with non-existent source code displays a dialog allowing the user to specify an alternate
- folder. For use when the source code location indicated within the coverage.xml file(s) loaded differs from
- that on the local machine now (e.g. a different drive letter or folder path).
-
-
-
The following minor changes were made:
-
-
- NCoverExplorer release is compiled against .Net 1.1 rather than .Net 1.0 due to a dependency on the
- FolderBrowserDialog not available in .Net 1.0.
-
-
- Coverage file stylesheet modified to show coverage column and NCoverExplorer version information with
- numerous other cosmetic enhancements.
-
-
- Enrich error environment information to include .Net framework version and operating system.
-
-
- Classes without a namespace are now shown under a namespace node of "-" like in Reflector.
-
-
-
The following bug fixes were made:
-
-
- Warnings about mismatches when merging xml files are no longer issued. NCover seems to inconsistently
- produce xml file coverage of methods which caused some users problems when merging.
-
-
- Nested classes without a namespace specified would cause the coverage.xml file to fail to load.
-
-
- Parsing overloaded properties (overloads of this[]) would not show the separate overloads in the tree
- and have incorrect coverage stats.
-
-
- Fix memory leaks for when source code tabs are closed.
-
-
- Minimum coverage threshold for NCoverExplorer.Console would sometimes be incorrect due to rounding.
-
-
- Changed NCoverExplorerSummary.xsl to format to 1dp rather than rounding to 0.
-
-
- Sorting by filename for a method then clicking on class node threw exception.
-
-
- VB.Net source code keywords not highlighted with the correct ICSharpCode template.
-
-
-
-
-
v1.3.3 - Apr 4th 2006
-
Bundled with TestDriven.Net from build 2.0.1578.
-
The following new features were introduced:
-
-
- Added NCoverExplorer.Console.exe for utilising NCoverExplorer features with automated
- coverage builds and NAnt tasks. By default will load up all the specified coverage file(s), apply
- any coverage exclusion(s) specified in the NCoverExplorer configuration and display total
- coverage statistics in the console output. If all items processed successfully returns an exit code of 0,
- if an exception occurs returns an exit code of 2.
-
-
- Added /m:xx (or /minCoverage:xx) argument to NCoverExplorer.Console.exe. When used in conjunction with
- /f (or /failMinimum) an exit code of 3 is returned if the min coverage is not reached. Can act
- as a trigger for failing an automated build such as with CruiseControl.Net.
-
-
- Added module & namespace summary xml report generation to NCoverExplorer (both the GUI and Console versions).
- In the GUI, this is available via the "View->Reports" menu. The three reports that are offered currently are:
- - Module Summary (Coverage totals for the project and per module);
- - Namespace Summary (Coverage totals for the project and per namespace);
- - Module Namespace Summary (Coverage totals for the project, per module and per namespace);
-
-
- Reports can be generated in xml or html format. Native html may be useful for directly attaching to e-mails.
- If xml format is chosen a "CoverageReport.xsl" stylesheet is copied from the NCoverExplorer installation
- folder to the report directory and linked to the xml file similar to coverage.xml/coverage.xsl by NCover.
-
-
- Reports can contain an "excluded nodes" footer section. This lists at the topmost level all of the items
- excluded from coverage at the time the report was run.
-
-
- Added "View->Filter" main menu and context menus, offering the ability to filter out nodes. Filtered
- nodes are simply moved under a new "Filtered" tree node and do not alter the coverage statistics
- (unlike excluded nodes which are effectively removed from the tree). Filters offered are either to
- hide all 100% covered nodes, or hide all unvisited (0%) nodes.
-
-
- Added "Include in Results" context menu option for when clicking on either the "Excluded" bin or one
- of it's immediate child nodes. Offers a way to "undo" an exclusion without reloading the file.
-
-
- Added "View->Summary Statistics" menu option (shortcut F3) to show dialog of totals of files, classes, members,
- NCLOC (non-commented lines of code) and sequence points. Statistics do not include excluded nodes
- (but will include filtered nodes).
-
-
- Created NAnt and MSBuild tasks for execution of NCoverExplorer.Console as an alternative to the <exec> task.
- These tasks offer a more developer friendly alternative such as <fileset> for coverage files and creating a
- .config file on the fly based on specified parameters such as <exclusions> within the .build/.proj file.
-
-
- Replaced menus with a lightly tweaked variant of Lutz Roeder's excellent CommandBar code to give a more modern
- look and assign icons on the menus.
-
-
- Added a toolbar. If not wanted the toolbar can be hidden using the "View->Show Toolbar" menu option.
-
-
-
The following minor changes were made:
-
-
- Options dialog shortcut changed to F2.
-
-
- Excluding a node will now select the node after by default rather than the one previous.
-
-
-
The following bug fixes were made:
-
-
- Fix bug where delete key shortcut was active on the root coverage file node, causing an exception to be thrown.
-
-
- Path was being truncated from the module name when saved.
-
-
- Fix bug where changing theme without coverage file loaded caused error.
-
-
-
-
-
v1.3.2 - Mar 14th 2006
-
Bundled with TestDriven.Net from build 2.0.1545.
-
The following new features were introduced:
-
-
- Added support for merging multiple coverage files. This can be triggered through a variety of ways:
- - Selecting multiple test classes/fixtures/projects in TestDriven.Net;
- - Passing multiple files in the command line arguments;
- - Selecting multiple files in the Open dialog;
- - Using a new "File->Merge..." menu option;
- - Drag/dropping onto the NCoverExplorer application.
-
-
- Added tabs for each source code file you open to explore coverage on. If you click on a partial class
- then tabs will be opened for each of the source code files making up the class.
-
-
- Added the ability to exclude assemblies, namespaces or classes from the coverage results by a wildcard capable
- case-sensitive match on the name. By default NCoverExplorer includes two exclusions:
- - Exclude all assemblies with the name ending in ".Tests".
- - Exclude all namespaces with the name containing ".My" (for VB.Net exclusions).
-
-
- Added support for the NCover 1.5.4 "excluded" attribute which can be found in the coverage.xml files when
- the appropriate NCover command-line attributes are used. Note that TestDriven.Net still does not as yet
- support this attribute so you need to use the NCover.Console command line for this feature - for more information see
- here. NCoverExplorer
- will not include nodes marked as 'excluded' by NCover in it's totals but will still display them in the tree.
-
-
- Added an "Excluded" child bin node containing all nodes that have been excluded by the options dialog, by NCover
- attributes or by the "Exclude From Results" context menu option (see next point).
-
-
- Replaced the "Remove from Results" context menu feature with "Exclude from Results" (shortcut of the DEL key).
- Achieves a similar result of removing nodes from coverage calculations, however the nodes are "moved" to the
- Excluded bin rather than being deleted from the tree.
-
-
- Added a custom "theme" capability along with further colour and font customisation options for the coverage tree,
- statistics and source code panes. A number of predefined "themes" are supplied and users can add their own.
- Users can switch between themes either in the Options dialog or via the "View->Themes" menu.
-
-
- Added a new "View->Coverage" menu which has sub-options related to "Sequence Point Coverage" and
- "Function Coverage", assigned shortcut keys ctrl+(1-4):
- - Choosing one of the "Sequence Point" variants will display the tree nodes with differing naming
- combinations of coverage percentage and # unvisited sequence points.
- - Choosing "Function Coverage" will alter the coverage tree display so that only methods/classes that were
- invoked are highlighted. Method nodes show the number of visits to that method. Class, namespace and module nodes
- show the maximum visit count by any of their children.
-
-
- Added a "View->Sort By" menu option and context menu on the tree, with sub-options for "Name" (default),
- "Class name/line number", "Coverage %" (ascending/descending), "Uncovered Sequence Points" (ascending/descending)
- and "Visit Counts" (ascending/descending).
- Assigned shortcut keys of ctrl+shift+(1-8). Note that reloading the coverage file will remove the current sort
- and default back to by "Name".
-
-
- Added "Save" and "Save As" options to the File menu. These give you the option of overwriting/creating a
- new coverage.xml file with the current values loaded in NCoverExplorer. Any coverage exclusions/removed
- nodes will not appear in the saved coverage file. Note that the methods are written in the same order as
- the sort order specified above.
-
-
- Added an "Explore Coverage Folder" menu option to the file menu.
-
-
- Added an "Expand All" context menu option on the tree (shortcut ctrl+L).
-
-
- Enhanced the statistics pane. When a class node is selected you will now see additional columns of
- coverage %, unvisited sequence points and sequence points. When clicking on a method node you will
- now see the filename.
-
-
- Implemented "smart expansion" in the tree. If when you expand a node there is only one child node
- then that node will also be expanded and so on. Increases speed of tree navigation particularly
- if using a style of "Nested" namespaces with deep hierarchies.
-
-
- Display class file name in tab page header bar when a method node is clicked on. Tooltip shows the path.
-
-
-
The following minor changes were made:
-
-
- Optimised when reloads of the coverage file so it is now only required if you change a coverage exclusion
- or the tree grouping/nesting styles in the options dialog. Makes for a snappier UI.
-
-
- Added a "Close" menu option to remove any loaded coverage file(s) from display.
-
-
- Moved all the "Recent Files" into a submenu to tidy up the File menu.
-
-
- Pressing Tab/shift-tab while focus is in the TextEditor pane of source code will now
- move focus out of the TextEditor.
-
-
- If a source code file contains multiple classes (not nested), then only the highlighting relevant
- to that particular class will be displayed in the editor window as each class tree node is clicked.
-
-
- Excluding the My namespace is now done through the Exclusions feature.
-
-
- Options dialog can be displayed using the F4 shortcut key.
-
-
- Removed last remnants of "non VS.Net standard colors" from the C# ICSharpCode TextEditor template.
-
-
- Make the GUI naming consistent to correctly reference "sequence points" rather than "lines" and "unvisited"
- rather than "uncovered".
-
-
- Removed "Edit in VS.Net" from the View menu.
-
-
- Changed NCoverExplorer main form icon to one that includes 32x32 sizes so Alt-Tab switching looks
- better than upscaled 16x16 icon.
-
-
- User is now prompted to remove a non-existent coverage file from the "Recent" files list rather than
- automatically being removed.
-
-
-
The following bug fixes were made:
-
-
- Serializing the configuration settings was not flushing the stream - resulting sometimes in a blank settings file
- preventing people from loading NCoverExplorer. Will now revert to default settings if an error occurs.
-
-
- Displaying a source code file that has been modified to have less lines of code than at the time of the coverage run
- will now display a user friendly message box.
-
-
- Compensation made for NCover not reporting column information when profiling C++ code. NCoverExplorer will now
- highlight the entire line rather than throwing an error.
-
-
- In some circumstances properties were not highlighted consistently due to a bug in the property node expansion.
-
-
- Coverage greater than 99.5% will no longer be rounded up to 100% in the display. It is instead shown as ">99.5%".
-
-
- Extremely high visit counts will no longer overflow the visit count.
-
-
- Statistics pane for a class will now always consistently show the property nodes grouped, rather than only
- after the class node has been expanded in the tree.
-
-
- Recent file menu would display incorrectly for files numbered from 10 onwards truncating first character.
-
-
- Release notes & FAQ were always directed to website rather than local versions when NCoverExplorer was started
- from TestDriven.Net.
-
-
-
-
-
v1.3.1 - Feb 15th 2006
-
Bundled with TestDriven.Net from build 2.0.1435.
-
The following new features were introduced:
-
-
- Namespaces are now "flattened" by default in the tree. This looks like the ClassView
- browser in VS.Net 2005 (or Lutz Roeder's Reflector). You can retain the nested look by changing it in the View->Options dialog.
-
-
- If you use the original "nested" namespace style (like the VS.Net 2003 class browser), then inner namespaces will now be
- listed at the top of each branch with the classes listed underneath which is less confusing to navigate.
-
-
- Option to exclude the "My" namespace for VB.Net projects (for use with with BCL 2.0 & NCover 1.5.x).
-
-
- Right-click menu option on coverage tree (shortcut ctrl+R) to "Remove From Results" that selected node
- and all it's children. Will force the coverage values to be recalculated. Intended for use where
- you have undesired assemblies, namespaces, classes or methods included in the report that are skewing your
- coverage results and you want them removed.
-
-
- Option to specify a satisfactory coverage threshold as a number of lines instead/as well as a percentage.
- If either of the conditions are met the node is coloured differently (provided the coverage is not zero).
-
-
- Colours can now be customised for both the source code highlighting and the nodes in the tree.
-
-
- Collapse all nodes context menu option on the coverage tree control (shortcut ctrl-A). Equivalent to reloading
- the coverage file (but would preserve any changes you have made such as removing nodes).
-
-
- By default the NCoverExplorer now attempts to restore your currently selected node/caret position after
- reloading a coverage.xml file (either F5 or by execution of another "Test With Coverage" command in TestDriven.Net).
- You can turn off this behaviour in the View->Options dialog.
-
-
- Statistics pane is now sortable by method name (default), visit count and line number.
-
-
- Statistics pane now summarises all the methods and their visit counts when a class node is clicked.
- Can be used as a basic form of method invocation counting for a fairly rudimentary level of profiling.
- The colouring used is the same as that of the tree to visually assist in identifying methods invoked.
-
-
-
The following minor changes were made:
-
-
- Restructured the Options dialog to have a tabbed interface.
-
-
- Renamed the "Show Visit Pane" menu option to "Show Statistics".
-
-
- The statistics pane now includes the method name. Widths of the columns are remembered each time you close NCoverExplorer.
-
-
- Statistics pane now has icons and colouring to match those of the associated nodes in the coverage tree.
-
-
- Inner nested classes now nested internally in the tree under the parent class, sorted to the top.
-
-
- Added FAQ, Release Notes and Blog website to the Help menu.
-
-
-
The following bug fixes were made:
-
-
- Source code files now loading with "Encoding.Default" rather than previous default of UTF-8.
-
-
- Coverage highlighting not working correctly on multiple line statements.
-
-
- Now handles partial classes and yield statements correctly.
-
-
-
-
-
v1.3 - Feb 6th 2006
-
Bundled with TestDriven.Net from build 2.0.1373d.
-
The following new features were introduced:
-
-
- Launching from VS.Net using TestDriven.Net will now re-use the NCoverExplorer instance
- opened from a previous "Test with... Coverage" click. Each VS.Net instance has it's own
- instance of NCoverExplorer.
-
-
- Added "Edit in VS.Net" functionality (keyboard shortcut ctrl+ E) for classes and methods.
- Will navigate to source code in your IDE at same point where your cursor resides in NCoverExplorer.
- Replaces and enhances previous "Open File" right-click option which has been removed.
-
-
- Added "Expand Covered" functionality (keyboard shortcut ctrl + Q) - recurses through the child
- nodes of the current node and expands all those with partial or complete coverage. Useful when
- using in conjunction with TestDriven.Net for isolated unit testing.
-
-
- Added "coverage file" node at the top of the tree showing total coverage across all modules/namespaces.
-
-
- Group by module option (default) to assist with navigating coverage for large solutions.
-
-
- Configuration information for NCoverExplorer now written to Local Settings rather than registry.
-
-
- Increase default number of "recent files" to 10, with ability to alter in the Options dialog.
-
-
- Reload of the current coverage file now has a shortcut key of F5.
-
-
- Display the path to the currently loaded coverage file in the title bar.
-
-
-
The following minor changes were made:
-
-
- Performance enhancements to improve loading times further for large files.
-
-
- Static constructors now renamed from "cctor" to ".cctor" so as to be sorted at the top.
-
-
- Running NCoverExplorer for first time ever will use a better starting form position.
-
-
- Removed configuration option for "nesting properties" - default remains the same of "true".
-
-
- Source code refactoring into separate assemblies to facilitate unit testing.
-
-
-
-
-
v1.2 - Feb 1st 2006
-
First public release, bundled with TestDriven.Net from build 2.0.1341d.
-
The following new features were introduced:
-
-
- Block style highlighting option for both visited and unvisited code.
-
-
- Satisfactory coverage threshold.
-
-
- Nesting of properties as nodes are expanded.
-
-
- Further speed improvements for initial file parsing.
-
-
-
-
-
v1.1 - Jan 1st 2006
-
Speed improvements.
-
-
-
v1.0 - Dec 17th 2005
-
First version created.
-
-
diff --git a/lib/NCover/MSVCP80.dll b/lib/NCover/MSVCP80.dll
deleted file mode 100644
index f0b52ebf..00000000
Binary files a/lib/NCover/MSVCP80.dll and /dev/null differ
diff --git a/lib/NCover/MSVCR80.dll b/lib/NCover/MSVCR80.dll
deleted file mode 100644
index 53c005ef..00000000
Binary files a/lib/NCover/MSVCR80.dll and /dev/null differ
diff --git a/lib/NCover/Microsoft.VC80.CRT.manifest b/lib/NCover/Microsoft.VC80.CRT.manifest
deleted file mode 100644
index 6a8a0e23..00000000
--- a/lib/NCover/Microsoft.VC80.CRT.manifest
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
- n9On8FItNsK/DmT8UQxu6jYDtWQ=
- 0KJ/VTwP4OUHx98HlIW2AdW1kuY=
- YJuB+9Os2oxW4mY+2oC/r8lICZE=
-
\ No newline at end of file
diff --git a/lib/NCover/NCover.Console.exe b/lib/NCover/NCover.Console.exe
deleted file mode 100644
index 80330112..00000000
Binary files a/lib/NCover/NCover.Console.exe and /dev/null differ
diff --git a/lib/NCover/NCover.Console.exe.config b/lib/NCover/NCover.Console.exe.config
deleted file mode 100644
index eb0a31af..00000000
--- a/lib/NCover/NCover.Console.exe.config
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/lib/NCover/NCover.Framework.dll b/lib/NCover/NCover.Framework.dll
deleted file mode 100644
index a9539e68..00000000
Binary files a/lib/NCover/NCover.Framework.dll and /dev/null differ
diff --git a/lib/NCover/NCoverExplorer.MSBuildTasks.dll b/lib/NCover/NCoverExplorer.MSBuildTasks.dll
deleted file mode 100644
index fa6e2bd4..00000000
Binary files a/lib/NCover/NCoverExplorer.MSBuildTasks.dll and /dev/null differ
diff --git a/lib/NCover/NCoverExplorer.MSBuildTasks.xml b/lib/NCover/NCoverExplorer.MSBuildTasks.xml
deleted file mode 100644
index dfa8c4fe..00000000
--- a/lib/NCover/NCoverExplorer.MSBuildTasks.xml
+++ /dev/null
@@ -1,1092 +0,0 @@
-
-
-
- NCoverExplorer.MSBuildTasks
-
-
-
-
- Logging levels to use within NCover task.
-
-
-
- No logging.
-
-
- Writes standard log output (Default).
-
-
- Writes verbose log output.
-
-
-
- New element option introduced in NCover 1.5.7 for use with //x2 argument.
-
-
-
-
- Legacy xml format that is the default.
-
-
-
-
- New xml format introduced in NCover 1.5.7 that nests method nodes with class nodes.
-
-
-
-
- Sort order for displaying the coverage results in the tree.
-
-
-
- Sort by name (default). (0)
-
-
- Sort by name( down to class level) then by line within the class. (1)
-
-
- Sort by coverage percentage ascending. (2)
-
-
- Sort by coverage percentage descending. (3)
-
-
- Sort by unvisited lines ascending. (4)
-
-
- Sort by unvisited lines descending. (5)
-
-
- Sort by visit count ascending. (6)
-
-
- Sort by visit count descending. (7)
-
-
- Sort by function coverage ascending. (8)
-
-
- Sort by function coverage descending. (9)
-
-
-
- Filter styles that can be applied to the results. Filtered nodes are not excluded from the coverage
- statistics.
-
-
-
- No filter applied. (0)
-
-
- Hide unvisited nodes. (1)
-
-
- Hide 100% fully covered nodes. (2)
-
-
- Hide nodes exceeding coverage threshold. (3)
-
-
-
- Potential report types.
-
-
-
- None. (0)
-
-
- Modules summary only. (1)
-
-
- Modules summary followed with a namespaces by module summary. (3)
-
-
- Modules summary followed with a classes by namespace summary. (4)
-
-
- Modules summary followed with a classes by namespace summary showing function coverage. (5)
-
-
-
- Common utility functions for working with NCover.
-
-
-
-
- Registry key for registering NCover manually - this will all become unnecessary in future versions of NCover (post 1.5.5) hopefully.
-
-
-
-
- Builds the temp settings XML file for NCover.
-
- The version.
- The ncover path.
- The settings file.
- The command line exe.
- The command line args.
- The working directory.
- The assembly list.
- The assembly files.
- The coverage file.
- The log level.
- The log file.
- The exclude attributes.
- If set to true profile IIS.
- The profile service.
- The XML format to write out (new feature in 1.5.7).
- Name of the profiled process.
-
- Command line switch necessary for passing as an argument.
-
-
-
-
- Creates the command line arguments.
-
- The version.
- The ncover path.
- The command line exe.
- The command line args.
- The working directory.
- The assembly list.
- The coverage file.
- The log level.
- The log file.
- The exclude attributes.
- if set to true [profile IIS].
- The profile service.
- if set to true include formatting.
- Whether to register CoverLib.dll.
- The command line format token.
-
-
-
-
- Registers the NCover coverlib.dll by writing directly into the registry under HKCU.
- Keeps a reference count so only register if only NCover task currently running.
-
-
-
-
- Unregisters the NCover coverlib.dll
- Keeps a reference count so only unregister if last NCover task currently running.
-
-
-
-
- Find path to NCover console and retrieve the version info.
-
-
-
-
- Reads the file contents and returns as a string.
-
-
-
-
- Build the Xml .ncoversettings file to pass to the NCover.Console executable using NCover 1.3.3 syntax.
-
-
-
-
- Write assembly names as a semi-colon delimited unique assembly name list.
- Assembly names do not have extensions (how NCover requires them) to match how the
- CLR identifies them when being profiled.
-
-
-
-
- Build the Xml .ncoversettings file to pass to the NCover.Console executable using NCover 1.5 syntax.
-
-
-
-
- Writes assembly names as separate Assembly nodes in the settings file. Seems to be a
- difference in how NCover 1.5.4 onwards handles from previous versions in the xml.
-
-
-
-
- Build a command line using NCover 1.3.3 syntax.
-
-
-
-
- Build a command line using NCover 1.5.x syntax.
-
-
-
-
- Creates the necessary HKCU entries for the NCover coverlib.dll.
-
- The ncover path.
-
-
-
- Handles a control-C style event so we can cleanup our refcount.
-
- Type of control exit.
- Whether to cancel the event.
-
-
-
- Utility class to scan for an executable in all available paths.
- Based on CodeProject article at: http://www.codeproject.com/csharp/winwhich.asp
-
-
-
-
- Initializes a new instance of the class.
-
-
-
-
- Return the version information for the executable located at this path. If executable
- not found at this location (e.g. not a fully qualified path) does a path search to see
- if it can be found anywhere else.
-
- Path to executable to find.
- Whether to throw exception if not found.
- Version number in format Major.Minor.Build
-
-
-
- Searches for the specified executable name in all available paths.
-
- Name of the executable.
-
-
-
-
- Form the regular expression string for the matching file.
-
- The name of the executable
- string that is the regex pattern.
-
-
-
- MSBuild task for automating NCoverExplorer.Console.
- Using this task you can merge coverage files from NCover, produce xml coverage reports for use
- with CruiseControl.Net, produce html report files directly, fail automated builds if coverage
- thresholds are not met and apply a range of detail to the reports produced such as sorting,
- filtering and coverage exclusions.
-
-
- This example shows producing an xml coverage report at Module/Namespace/Class detail level for
- inclusion on a CC.Net build server. You would add a merge file task in the publishers section
- of your CC.Net project file to merge in this "CoverageSummary.xml" file so that it can be
- transformed by the NCoverExplorer xsl stylesheets you have copied into the CC.Net folder. Here
- we have set a satisfactory coverage threshold at 80%.
-
-
-
-
-
-
- ]]>
-
-
-
- This example shows producing an html function coverage report, excluding the test assemblies. The
- assemblies excluded are being displayed at the bottom of the report. Note also that this time
- the ReportType is specified by its enum name rather than numeric value - they are interchangable.
- We have also "inlined" the "CoverageFiles" from the ItemGroup above to show this can be done.
-
-
-
-
- Assembly
- *.Tests
-
-
-
-
-
- ]]>
-
-
-
- This example shows producing an html module class summary coverage report with exclusions as above.
- This time we have added applying specific sorting and filtering criteria. This report will show all
- classes that do not have 100% coverage, sorted within their namespaces by descending coverage %. We
- have also "inlined" the exclusions
-
-
- ]]>
-
-
-
- This example shows the merging capability to produce a consolidated merge file from multiple
- coverage test runs. The results are being stored in a single "MyApp.CoverageMerged.xml" file.
- Note that you could additionally apply coverage exclusions at this point. Merging files can
- be useful if your testing process requires multiple coverage runs and you want a single archive
- which consolidates the results.
-
-
-
-
-
-
- ]]>
-
-
-
- This example shows failing a build if the overall coverage % does not meet our threshold, without
- producing a coverage report.
-
-
- ]]>
-
-
-
- This example shows failing a build if either the overall coverage % does not meet our threshold, or
- if one of the individual module thresholds is not met. Note that the ModuleThresholds
- could have been "inlined" (just showing the MSBuild flexibility to place in a separate group).
-
-
-
-
-
-
-
- ]]>
-
-
-
- This example shows using virtually the whole range of attributes. Shown below is failing a build
- if not reaching the overall or module level coverage thresholds. The results of merging multiple
- NCover files together are stored as a separate file. We are producing xml and html Namespace per
- module summary reports (with the exclusions show in the footer). Note that the module thresholds
- will also be used in the reports. The reports are sorted by name with no filter applied.
- We are excluding test assemblies and anything in a presentation layer namespace.
-
-
-
-
-
-
-
-
- Class
- MyApp.SomeNamespace.SomeClass
-
-
- Namespace
- MyApp\.(\w*\.)?
- true
-
-
-
-
-
- ]]>
-
-
-
-
-
- Initializes a new instance of the class.
-
-
-
-
- Validate the parameters supplied to this task.
-
- true if parameters are valid, false otherwise.
-
-
-
- Executes the task.
-
- if the task ran successfully; otherwise .
-
-
-
- Returns a string value containing the command line arguments to pass directly to the executable file.
-
-
- A string value containing the command line arguments to pass directly to the executable file.
-
-
-
-
- Logs the starting point of the run to all registered loggers.
-
- A descriptive message to provide loggers, usually the command line and switches.
-
-
-
- Returns the fully qualified path to the executable file.
-
-
- The fully qualified path to the executable file.
-
-
-
-
- Determine the path to NCoverExplorer. Either the user can specify it in the arguments to the task,
- or we look in the registry, program files and finally just assume it is in the path.
-
-
-
-
- Return a temporary filename for the config file for executing NCoverExplorer.Console.
-
- Configuration filename.
-
-
-
- Legacy NCoverExplorer.Console is considered prior to 1.4.0 (as 1.4.0 was when the settings
- file format was changed).
-
- NCoverExplorer.Console.exe path.
- true if version is prior to 1.4.0
-
-
-
- Builds a temporary NCoverExplorer configuration file which we can pass in the command line.
- We require this as the command line itself does not directly support all the argument combinations.
-
- Name of the settings file.
-
-
-
- Builds a temporary NCoverExplorer configuration file which we can pass in the command line.
- We require this as the command line itself does not directly support all the argument combinations.
-
- Name of the settings file.
-
-
-
- The coverage exclusions have been inlined as type=pattern semi-colon delimited pairs.
- Break apart and write to the temp config file.
-
- Current xml output stream.
-
-
-
- The coverage exclusions have been inlined as type=pattern semi-colon delimited pairs.
- Break apart and write to the temp config file.
-
- Current xml output stream.
-
-
-
- Iterate through the module thresholds and write their values into the configuration file.
-
- Current xml output stream.
-
-
-
- Build command line for passing to legacy NCoverExplorer.Console versions.
-
-
-
-
- Removes generated settings file after process has run.
-
-
-
-
- Gets or sets the output directory for the reports.
-
- The output dir.
-
-
-
- Whether to fail the task if the minimumCoverage threshold is not reached on any module.
- NCoverExplorer console application will return exit code 3.
-
-
-
-
- Whether to fail the task if the minimumCoverage threshold is not reached on total coverage.
- NCoverExplorer console application will return exit code 3.
-
-
-
-
- The minimum coverage percentage to be used with the FailMinimum and FailCombinedMinimum options.
-
-
-
-
- Gets or sets the name of the temporary XML config file being generated for coverage.
-
- The name of the XML config.
-
-
-
- The satisfactory coverage percentage for display in the reports.
-
-
-
-
- The .config filename for containing any custom exclusions and parameters.
-
-
-
-
- The type of report to produce (use numeric value or string name).
- 0 / None, 1 / ModuleSummary, 3 / ModuleNamespaceSummary,
- 4 / ModuleClassSummary, 5 / ModuleClassFunctionSummary
-
-
-
-
- The sorting if any to apply (use numeric value or string name).
- 0 / Name, 1 / ClassLine,
- 2 / CoveragePercentageAscending, 3 / CoveragePercentageDescending,
- 4 / UnvisitedSequencePointsAscending, 5 / UnvisitedSequencePointsDescending,
- 6 / VisitCountAscending, 7 / VisitCountDescending,
- 8 / FunctionCoverageAscending, 9 / FunctionCoverageDescending
-
-
-
-
- The filtering if any to apply (use numeric value or string name).
- 0 / None, 1 / HideUnvisited, 2 / HideFullyCovered, 3 / HideThresholdCovered
-
- The string or textual enum value.
-
-
-
- The filename for generating an xml report.
-
-
-
-
- The filename for generating an html report.
-
-
-
-
- The filename for the merge of the coverage xml files.
-
-
-
-
- Determines whether to include the coverage exclusions in the report. The default is
- .
-
-
-
-
- Used to select the coverage xml files to merge into the report.
-
-
-
-
- Coverage exclusions to apply, in one of two formats:
- They can be semi-colon delimited "Type=Pattern" pairs, e.g. "Assembly=*.Tests;Class=My.*".
- Alternatively they can be defined in a property group as a <CoverageExclusions> section.
- See the examples for both formats. If you want to use regular expressions then you must
- use the <PropertyGroup> approach.
-
-
- This example shows a range of coverage exclusions using the <PropertyGroup> approach.
- Note the optional use of wildcard characters in the pattern. You could set the exclusions
- up within the gui and then paste the xml directly from the NCoverExplorer.config file located
- in C:\Documents and Settings\user\Application Data\Gnoso\NCoverExplorer\
-
-
-
-
- Assembly
- *.Tests
-
-
- Namespace
- MyNamespace.*
-
-
- Class
- MyNamespace.MyClass
-
-
- Method
- MyNamespace.MyClass.MyMethod
-
-
- Namespace
- MyApp\.(\w*\.)?
- true
-
-
-
-
-
- ]]>
-
-
-
- This example shows inlining of three of the same exclusions above. Note with this approach
- it is not possible to use regular expressions.
-
-
- ]]>
-
-
-
-
-
- Module thresholds to apply, in format "AssemblyName=Percentage", e.g. "MyApp.Core=75"
-
-
-
-
- Gets the name of the executable file to run.
-
-
- The name of the executable file to run.
-
-
-
- Gets the with which to log errors.
-
-
- The with which to log errors.
-
-
-
- MSBuild task for automating NCover.Console.exe, with NCover 1.5.x support. Note that this task
- will self register CoverLib.dll by default using the registry (does not require local admin).
-
-
- This example shows the standard profiling using NCover for standard nunit tests with minimal arguments.
- Defaults are with logging to coverage.log, profiling all assemblies, output filename of coverage.xml and this
- example specifies a path to where to find ncover.console.exe.
-
-
- ]]>
-
-
-
- If you are using TypeMock, you may experience issues with the registration of coverlib.dll conflicting
- due to overwriting the registered profiler. You should add the "registerProfiler" attribute below and set it to false.
-
-
- ]]>
-
-
-
- This example for NCover 1.5.8 shows profiling a process which is launched by another process.
-
-
- ]]>
-
-
-
- This example shows using an assembly list as ; delimited names rather than using the ability
- of the NCover task to dynamically build from a list of files (shown in following example).
-
-
- ]]>
-
-
-
- This example shows the standard profiling using NCover 1.5.x for a Windows application, specifying a coverage
- exclusion, verbose logging to a named file, specifically named log and output xml files. It also shows
- coverage exclusion attributes, overriding the NCover location to run from and a way of listing assemblies
- to be included in the profiled NCover results.
-
-
-
-
-
-
- ]]>
-
-
-
-
-
- Initializes a new instance of the class.
-
-
-
-
- Executes the task.
-
- if the task ran successfully; otherwise .
-
-
-
- Returns a string value containing the command line arguments to pass directly to the executable file.
-
-
- A string value containing the command line arguments to pass directly to the executable file.
-
-
-
-
- Returns the fully qualified path to the executable file.
-
-
- The fully qualified path to the executable file.
-
-
-
-
- Logs the starting point of the run to all registered loggers.
-
- A descriptive message to provide loggers, usually the command line and switches.
-
-
-
- Check that we have a valid path to NCover.
-
-
-
-
- Removes generated settings file after process has run.
-
-
-
-
- Convert the MSBuild specific ITaskItem[] to a string array for use by NCoverUtilities.
-
-
-
-
-
-
- The command line executable to be launched by NCover (such as nunit-console.exe).
-
-
-
-
- The arguments to pass to the command line executable to be launched by NCover (such as nunit-console.exe).
-
-
-
-
- The filename for the output coverage.xml file (default).
-
-
-
-
- What level of NCover logging to provide. Values are "Normal" (default) and "Verbose".
- Due to a bug in NCover 1.5.4 "Quiet" will result in NCover stopping abnormally - hence has been
- defaulted to be "Normal" until the bug is fixed.
-
-
-
-
- Gets or sets the logfile name to write to if logLevel is set to anything other than "Quiet". The default
- is "coverage.log".
-
-
-
-
- Gets or sets the working directory for the command line executable.
-
-
-
-
- If coverage exclusion attributes have been applied (NCover 1.5.4 onwards) specify the full namespace
- to the attribute including the "Attribute" suffix - e.g. "CoverageExcludeAttribute" if defined in no
- namespace. Separate multiple attributes with semi-colons.
-
-
-
-
- Determines whether to profile under IIS. Default value is .
-
-
-
-
- The service name if profiling a windows service.
-
-
-
-
- Alternative to specifying assembly names - you can instead list them as you would on the
- command line as a semi-colon delimited list without any suffixes or paths.
-
-
-
-
- Used to specify the assemblies to be profiled. Alternative to the AssemblyList property,
- where instead you wat the list to be dynamically built using an itemgroup, for instance
- to match all assemblies against a wildcard. The NCover task will take care of stripping
- off the suffixes etc.
-
-
-
-
- Determines whether to register NCover CoverLib.dll on each run. The default is true. You
- would set this to false if using TypeMock due to a conflict in registered profilers.
- If set to true, the NCover task uses a reference counting approach to minimise the chance
- of issues when simultaneous builds.
-
-
-
-
- Gets or sets a value indicating the xml output format to write (new in NCover 1.5.7).
- Default value is "Xml1", alternat option is "Xml2" which nests method nodes within class
- nodes. Note however that "Xml2" is for future use and is not yet supported by NCoverExplorer
- as of version 1.3.6.
-
-
-
-
- Gets or sets the profiled process module name. Use this argument when the executable being
- launched is not the actual process you want to profile coverage for.
-
-
-
-
- Gets the name of the executable file to run.
-
-
- The name of the executable file to run.
-
-
-
- Gets the with which to log errors.
-
-
- The with which to log errors.
-
-
-
- Create a .nunit project file for all the test assemblies matching the specified pattern.
- This should be created in the bin folder where your test assemblies are located so that
- the assemblies are within the AppDomain path.
- The .nunit file can then be used by NUnit or NCover based tasks.
-
-
-
- Create a .nunit project file in output bin folder for a specified test assembly.
-
-
-
-
- $(MSBuildProjectDirectory)\Build
-
-
-
-
-
-
-
- ]]>
-
-
-
-
- Create a .nunit project file in output bin folder with an associated App.Config file for
- all test assemblies matching a pattern.
-
-
-
-
-
-
-
- ]]>
-
-
-
-
-
- Default constructor.
-
-
-
-
- Build the contents of the .nunit file using the test assemblies matching this pattern.
-
-
-
-
- Create a .nunit project file listing the test assemblies.
-
- Full filename of the .nunit file.
- Fileset containing the test assemblies.
- Optional path to App.Config file to include in project.
- Optional path to the nunit app base, when included full paths to each assembly (relative to the appbase) are included
-
-
-
- The nunit project file to create.
-
-
-
-
- Optional path to an App.Config file to be specified in the .nunit project file.
-
-
-
-
- Optional path to the nunit app base, when included full paths to each assembly
- (relative to the appbase) are included.
-
-
-
-
- Used to select the test assemblies to be included in the .nunit project.
-
-
-
-
- A strongly-typed resource class, for looking up localized strings, etc.
-
-
-
-
- Returns the cached ResourceManager instance used by this class.
-
-
-
-
- Overrides the current thread's CurrentUICulture property for all
- resource lookups using this strongly typed resource class.
-
-
-
-
- Looks up a localized string similar to Contents of config file:\r\n{0}.
-
-
-
-
- Looks up a localized string similar to Contents of config file:\r\n{0}.
-
-
-
-
- Looks up a localized string similar to Deleting config file: {0}.
-
-
-
-
- Looks up a localized string similar to This line cannot be parsed: '{0}'. Coverage exclusions should be in format: Type=Pattern (e.g. 'Assembly=*.Tests').
-
-
-
-
- Looks up a localized string similar to Could not find the registry key for NCoverExplorer indicating the program location (set by installing with TestDriven.Net). Please specify the full path to NCoverExplorer.Console.exe using the ToolPath attribute..
-
-
-
-
- Looks up a localized string similar to Could not find NCover.Console.exe in C:\Program Files\NCover\. Specify an alternate path using the ToolPath attribute on your NCover target..
-
-
-
-
- Looks up a localized string similar to Detected NCover.Console v{0} in {1}.
-
-
-
-
diff --git a/lib/NCover/NCoverFAQ.html b/lib/NCover/NCoverFAQ.html
deleted file mode 100644
index f63b8f13..00000000
--- a/lib/NCover/NCoverFAQ.html
+++ /dev/null
@@ -1,429 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
A code coverage analyzer monitors your code at runtime and
- records information about which lines of code were executed. NCover shows each
- sequence point in your application along with the number of times that point
- was executed. Sequence points are generated by the compiler and stored in the
- debug information (.pdb) files. A sequence point basically corresponds to a
- single program statement (often a line of code) in your high-level language.
-
2. Why would I want to do code coverage analysis?
-
Unit test suites are often used as a quality tool during the
- development process to keep the codebase stable as it changes and expands.
- Tools such as NUnit are often used to run and
- report on the test suites. However, when implementing unit testing in your
- build process, you have no way of knowing how much of your code the unit tests
- are actually testing. This is where code coverage comes in. You can run NUnit
- within NCover and use the code coverage report to determine which code was not
- tested by that particular test suite.
-
3. What versions of the CLR does NCover support?
-
- NCover 1.5.x requires the .NET framework version 2.0.50727 to be installed; however,
- the application being profiled can be written against any shipping version of the
- framework. NCover
- has been tested profiling coverage of .NET 2.0, .NET 1.1 and .NET 1.0 applications.
-
4. Which version of NCover should I install?
-
- If you have the .NET 2.0 framework installed on your machine then you should use
- the latest NCover version available. NCover as of version 1.5 can profile .NET 2.0, 1.1 and 1.0 applications.
-
- For development teams who do not have the .NET framework 2.0 installed but do have
- the .NET framework version 1.1.4322, you can
- try NCover 1.3.3. Note however that this version is no longer supported as
- it has a number of known issues and limitations.
-
5. What is the command line syntax for NCover?
-
Here is the usage info from the NCover command line (for NCover versions from 1.5.6
- only):
-
NCover.Console [<command line> [<command args>]]
- [//svc <service name>]
- [//iis]
- [//a <assembly list>]
- [//w <working directory>]
- [//ea <exclusion list>]
- [//reg]
- [//x <xml output file>]
- [//s [<settings file>]] [//r [<settings file>]]
- [//v] [//q]
- [//l <log file>]
-
-//svc For profiling windows services
-//iis For profiling web applications
-
-//a List of assemblies to profile separated by semi-colons i.e. "MyAssembly1;MyAssembly2". Do not include paths or suffixes.
-//w Working directory for profiled application
-//ea List of attributes marking classes or methods to exclude from coverage
-
-//reg Register profiler temporarily for user. (helps with xcopy deployment)
-//x Specify coverage output file. (default: coverage.xml).
-//pm Specify name of process to profile (i.e. myapp.exe)
-
-//s Save settings to a file (defaults: NCover.Settings)
-//r Use settings file, overriding other settings (default: NCover.Settings)
-
-//l Specify profiler log file (default: coverage.log).
-//q No logging (quiet)
-//v Enable verbose logging (show instrumented code)
-
-
-
<command line> - This argument specifies the command-line of the .NET application
- you want to analyze.
- Any command line arguments not starting with // will be passed
- through to that application. NCover will profile the running application until it has exited. See below for examples.
//svc - This option is an alternative to the <command line>
- for profiling windows services, which cannot be run directly as executables. NCover
- will start the service (stopping it first if already running) and profile coverage
- until the windows service is stopped.
-
//iis - This option is an alternative to the <command line> for profiling
- web applications. NCover will start the IISAdmin and W3C
- services (stopping first if currently running) and profile coverage until the IISAdmin
- service is stopped.
-
-
//a - This command-line argument specifies the assemblies that you want to analyze.
- NCover can only analyze assemblies that have .pdb files included with them. If
- you do not specify the //a argument, NCover will attempt to analyze every loaded
- assembly that has debug information available. Note that the assembly name arguments are
- the module name within the assembly, not the physical file name. e.g. "MyAssembly"
- rather than "MyAssembly.dll".
//w - If the application being profiled requires the
- working directory to be set to something other than the current directory you are
- executing the command line from then you can override it with this argument.
-
//ea - You can choose to exclude classes and methods
- from coverage statistics by defining .NET attribute(s) and applying it to the affected
- code. When using this argument you must specify the full type namespace of these
- attribute(s) separated by semi-colons. See below for an example.
-
-
//reg - NCover requires a COM registration of the CoverLib.dll assembly containing
- the profiler, which is performed automatically by the default .msi installation.
- If you require an xcopy style deployment of NCover like many other .NET tools, then
- you can use this argument which will temporarily register the profiler while performing
- coverage. This feature was added in NCover 1.5.6.
-
//x - The output of NCover is an xml file (example below). Use this argument to
- specify an alternate filename to "coverage.xml" in the current directory.
-
-
//pm - This setting tells NCover to ignore processes that don't have the specified process module name.
- This is the name of the executable (i.e. myapp.exe). This setting is useful in cases, where your NCover
- command spawns a series of child processes. Using this setting will help NCover determine which process to profile.
-
-
//s - You may find it more convenient to use a settings file rather than specifying
- a long list of command line arguments for running NCover. If you get the NCover
- command line working as you would like it and then use the //s argument it will
- save the required arguments as an xml file that can then be used by the //r argument
- below.
-
//r - For use when you have used //s to construct an NCover settings file containing
- your command line arguments. e.g. "ncover.console.exe //r NCover.Settings"
-
-
//l - The coverage log file can provide an insight if the desired coverage output
- is not obtained. Useful information you may find to assist you includes which assemblies
- were loaded by NCover, their file paths and which of those it found the .pdb build
- symbols for. Use this argument to specify an alternative log file name or location
- to coverage.log in the current directory.
-
//q - Suppresses writing the coverage.log file.
-
//v - This command-line argument makes the profiler emit all the original IL and
- modified IL instructions to the coverage log. This is useful for debugging
- purposes. Beware that this can make your coverage log file very large!
-
-
-
6. Does NCover required a special compilation step for my code?
-
No. Some code coverage tools change your source code and force
- you to recompile it into a special build. NCover is designed to work
- on shipping code. NCover uses the .NET Framework profiling API to monitor
- your code. It does require build symbols, but can be run on release code
- without any modifications.
-
7. How does NCover work?
-
NCover uses the .NET Framework profiler API to monitor an
- application's execution. When a method is loaded by the CLR, NCover retrieves
- the IL and replaces it with instrumented IL code. NCover does not change
- your original IL code, it simply inserts new code to update a visit
- counter at each sequence point. Upon
- request, (usually after the .NET process has shut down) the profiler outputs statistics
- to the coverage file.
-
-
- 8. What is the output of NCover?
-
NCover generally writes out three files after analysis
- completes.
-
-
- Coverage.log - This file is a log of the events and messages from the profiler
- during the analysis process. Most of the time, error messages are recorded in
- this log. If you enable verbose logging, the coverage log will contain
- disassembly of the original and instrumented IL code. Verbose logging is not recommended for
- normal use.
- Coverage.xml - This file is the analysis output of NCover. You can see an
- example of the output below.
-
- Coverage.xsl - This file is a simple XML transformation that makes the XML
- output easily readable.
-
Suggested usages of the coverage.xml output are to display it in the
- NCoverExplorer gui with the source
- code highlighted, to generate html reports, or to include it in your continuous build server reports such as CruiseControl.Net.
- For more information on these options see below in the FAQ.
-
-
- 9. How do I use coverage exclusions?
-
- First you should define an attribute to markup your excluded code with. You will
- likely want to put this in a common assembly to make it reusable, or indeed within
- a "CommonAssemblyInfo.cs" that you include in all your application assemblies.
- Note that if you are using the TestDriven.Net
- VS.Net add-in to "Test with Coverage" it will automatically
- pass through "//ea CoverageExcludeAttribute"
- which you should define without a namespace like above. For further information refer to this
-
- blog entry.
-
- 10. Examples
-
- Coverage while running a simple executable until it exits:
-
-
NCover.Console MyApplication.exe
-
- Coverage while running all the unit tests in an assembly using NUnit, profiling
- all loaded assemblies with .pdb build symbols:
- Coverage of a windows service. Stop the service to generate the coverage output:
-
-
NCover.Console //svc MyServiceName
-
- Coverage of an ASP.Net application. Stop the IIS service to generate the coverage
- output:
-
-
NCover.Console //iis
-
- 11. Where can I get help or support?
-
- Your best approach is to browse the
- NCover forums as well as the
- blog by the author Peter Waldschmidt. If you cannot find a similar issue
- mentioned feel free to post your query and perhaps someone can help.
-
- 12. How do I "xcopy deploy" NCover like my other build tools?
-
- Many developers prefer to have their build tools such as NUnit, NAnt etc stored
- in source control in a Tools folder along with the source code. This ensures that
- a new developer can obtain and build the application without having to install additional
- tools on their own machines.
-
- NCover can also be deployed in this fashion. However the one gotcha with NCover
- versus other tools is that the profiler within CoverLib.dll must be COM registered
- on the local machine before you execute it. Prior to NCover 1.5.6 this was usually
- achieved as part of your build script, which would call regsvr32 with the path to
- the CoverLib.dll in your Tools folder. Alternatively the <ncover> NAnt and
- MSBuild tasks described below will do this for you. As of NCover 1.5.6 you can also
- use the //reg option in the command line arguments which will temporarily register
- the profiler. Note that the //reg option will not work for IIS or Windows Service
- profiling unless you are running NCover under the same Windows login account as
- the IIS worker process, or your Windows Service.
-
- 13. How do I see my source code highlighted with the coverage results?
-
- NCoverExplorer is a gui and console-based
- .NET application developed by Grant Drake. NCoverExplorer
- parses the coverage.xml files output from NCover and displays the results integrated
- with your source code. It also includes a number of additional features to merge,
- filter, sort and generate html reports. The console version is
- designed to be used as part of an automated build process. The support forums for
- NCoverExplorer are located with the NCover ones at http://ncover.org/.
-
- 14. How do I run NCover from within the Visual Studio.Net IDE?
-
- The TestDriven.Net add-in by
- Jamie Cansdale offers a right-click capability within the IDE to execute
- your unit tests with code coverage. The results of the NCover code coverage are
- displayed with the bundled NCoverExplorer gui for analysis and reporting.
-
- 15. How do I run NCover from a NAnt or MSBuild task?
-
- You can use an <exec> task with NAnt
- or an <Exec> task with MSBuild. Alternatively you may want to use the custom
- <ncover> task for NAnt or <NCover> task for MSBuild developed by Grant
- Drake for a more developer friendly syntax. The source code, compiled assemblies
- and documentation are located in the NCoverExplorer.Extras.zip available from http://ncoverexplorer.org/.
-
- 16. How do I include NCover output in my CruiseControl.Net build reports?
-
- CruiseControl.Net is a continuous integration
- build server which offers web-based reporting of the outputs of a build such as
- unit test results and code coverage reporting. The default CruiseControl.Net installation
- includes a basic stylesheet which works in combination with the standard coverage.xml
- formatted output. So all you need to do is include the execution of NCover as part
- of your build, then add a CruiseControl.Net merge file publisher task to integrate
- the coverage.xml results into the build output.
-
- An improvement on the above to display more attractive and powerful reports as well
- as minimize the build log size is to use NCoverExplorer. The NCoverExplorer.Console.exe
- is designed to produce a more concise xml report summary that is combined with an
- alternate xsl stylesheet for CruiseControl.Net. You can find more information and
- screenshots in this
- blog entry - all the necessary tasks, examples and documentation are located
- within NCoverExplorer.Extras.zip available from
- http://ncoverexplorer.org/.
-
- 17. How do I merge multiple NCover coverage.xml results?
-
- You can can use NCoverExplorer to merge the results of multiple coverage runs. For
- more information refer to this
- blog entry.
-
- 18. Troubleshooting: Why is my coverage.xml file empty?
-
-
If using the command-line, did you COM register CoverLib.dll (or use the //reg option
- from NCover 1.5.6)?
-
Did you generate build symbol files (.pdbs) for the profiled application?
-
If using the //a option, did you correctly list just the assembly names without
- paths or .dll suffixes?
-
-
- 19. Troubleshooting: I have coverage.xml output but my XYZ assembly is not included in it?
-
-
NCover will only profile loaded assemblies - did your code execution path while
- under coverage force that assembly to be loaded (e.g. by loading a type or calling
- a method in that assembly)?
-
Did you generate build symbol files (.pdb files) for the missing assembly?
-
If using the //a option, did you correctly list the assembly names including the
- one that is missing?
-
Can you see information about the assembly being loaded within the coverage.log?
- Is the correct assembly being loaded (check the path) - if you have a version in
- the GAC it may possibly prevent the .pdb file from being loaded.
If using the NCoverExplorer gui, have you got a coverage exclusion defined which
- is hiding it from the display?
-
-
- 20. Troubleshooting: After running NCover my coverage.log says "Failed to load symbols for module XYZ"?
-
-
This message means that no .pdb build symbol file was found for that assembly so
- it cannot be profiled for code coverage. If that assembly is part of the .NET framework
- for instance like System.Data.dll, then this is an expected message and should not
- cause concern.
If however the assembly belongs to your application, did you generate the
- build symbol files (.pdb files) for it?
-
-
- 21. Troubleshooting: I get a "Profiled process terminated. Profiler connection not
- established" message?
-
-
If using the command-line, did you COM register CoverLib.dll (or use the //reg option
- from NCover 1.5.6)?
Are you running Windows XP 64-bit? You may want to take a look at
- this thread
-
- 22. Troubleshooting: My coverage exclusions are not working?
-
-
Have you put the full namespace type name to the exclusion including the Attribute suffix in the //ea argument? See the "How
- do I use coverage exclusions?" question above.
-
-
-
diff --git a/lib/System.Data.SqlServerCe.dll b/lib/System.Data.SqlServerCe.dll
deleted file mode 100644
index 33da7e95..00000000
Binary files a/lib/System.Data.SqlServerCe.dll and /dev/null differ
diff --git a/lib/log4net.dll b/lib/log4net.dll
deleted file mode 100644
index a70cd2b8..00000000
Binary files a/lib/log4net.dll and /dev/null differ
diff --git a/local.properties-example b/local.properties-example
deleted file mode 100644
index 473e1f60..00000000
--- a/local.properties-example
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
\ No newline at end of file
diff --git a/nuget/Package.nuspec b/nuget/Package.nuspec
deleted file mode 100644
index a12d8a07..00000000
--- a/nuget/Package.nuspec
+++ /dev/null
@@ -1,22 +0,0 @@
-
-
-
- DotNetProjects.Migrator
- $version$
- DotNetProjects
- DotNetProjects
- https://www.mozilla.org/MPL/1.1/
- https://github.com/dotnetprojects/Migrator.NET
- false
- Framework Assembly for DotNetProjects.Migrator
- Copyright 2015
-
-
-
-
-
-
-
-
-
-
diff --git a/nuget/nuget.exe b/nuget/nuget.exe
deleted file mode 100644
index 324daa84..00000000
Binary files a/nuget/nuget.exe and /dev/null differ
diff --git a/nuget/pack.ps1 b/nuget/pack.ps1
deleted file mode 100644
index 418a4a4f..00000000
--- a/nuget/pack.ps1
+++ /dev/null
@@ -1,15 +0,0 @@
-$root = (split-path -parent $MyInvocation.MyCommand.Definition) + '\..'
-
-Write-Host "root: $root"
-
-$version = [System.Reflection.Assembly]::LoadFile("$root\src\Migrator\bin\Migrator\Release\DotNetProjects.Migrator.dll").GetName().Version
-$versionStr = "{0}.{1}.{2}" -f ($version.Major, $version.Minor, $version.Build)
-
-Write-Host "Setting .nuspec version tag to $versionStr"
-
-$content = (Get-Content $root\NuGet\Package.nuspec)
-$content = $content -replace '\$version\$',$versionStr
-
-$content | Out-File $root\nuget\Package.compiled.nuspec
-
-& $root\NuGet\NuGet.exe pack $root\nuget\Package.compiled.nuspec
\ No newline at end of file
diff --git a/src/Migrator.Console/Boot.cs b/src/Migrator.Console/Boot.cs
deleted file mode 100644
index ea223b11..00000000
--- a/src/Migrator.Console/Boot.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-using System;
-
-namespace Migrator.MigratorConsole
-{
- ///
- /// Console application boostrap class.
- ///
- public class Boot
- {
- [STAThread]
- public static int Main(string[] argv)
- {
- var con = new MigratorConsole(argv);
- return con.Run();
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Console/Migrator.Console-vs2008.csproj b/src/Migrator.Console/Migrator.Console-vs2008.csproj
deleted file mode 100644
index 28fd6649..00000000
--- a/src/Migrator.Console/Migrator.Console-vs2008.csproj
+++ /dev/null
@@ -1,105 +0,0 @@
-
-
- Debug
- AnyCPU
- 9.0.30729
- 2.0
- {FBE3A83A-D0F8-4D72-AF8D-9EF772569A31}
- Exe
- Properties
- Migrator.Console
- Migrator.Console
-
-
- 2.0
-
-
- true
- http://localhost/Migrator.Console/
- true
- Web
- true
- Foreground
- 7
- Days
- false
- false
- true
- 0
- 1.0.0.%2a
- true
- false
- true
- MigratorDotNet.snk
-
-
- true
- full
- false
- bin\Migrator.Console\Debug\
- DEBUG;TRACE
- prompt
- 4
-
-
- pdbonly
- true
- bin\Migrator.Console\Release\
- TRACE
- prompt
- 4
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {1FEE70A4-AAD7-4C60-BE60-3F7DC03A8C4D}
- Migrator-vs2008
-
-
- {5270F048-E580-486C-B14C-E5B9F6E539D4}
- Migrator.Framework-vs2008
-
-
-
-
- False
- .NET Framework Client Profile
- false
-
-
- False
- .NET Framework 2.0 %28x86%29
- true
-
-
- False
- .NET Framework 3.0 %28x86%29
- false
-
-
- False
- .NET Framework 3.5
- false
-
-
- False
- .NET Framework 3.5 SP1
- false
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/Migrator.Console/Migrator.Console-vs2010.csproj b/src/Migrator.Console/Migrator.Console-vs2010.csproj
deleted file mode 100644
index 1e787332..00000000
--- a/src/Migrator.Console/Migrator.Console-vs2010.csproj
+++ /dev/null
@@ -1,115 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 9.0.30729
- 2.0
- {FBE3A83A-D0F8-4D72-AF8D-9EF772569A31}
- Exe
- Properties
- Migrator.Console
- Migrator.Console
-
-
- 3.5
-
-
- true
- true
- MigratorDotNet.snk
- v4.0
- http://localhost/Migrator.Console/
- true
- Web
- true
- Foreground
- 7
- Days
- false
- false
- true
- 0
- 1.0.0.%2a
- false
- true
-
-
-
- true
- full
- false
- bin\Migrator.Console\Debug\
- DEBUG;TRACE
- prompt
- 4
- AllRules.ruleset
-
-
- pdbonly
- true
- bin\Migrator.Console\Release\
- TRACE
- prompt
- 4
- AllRules.ruleset
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {d58c68e4-d789-40f7-9078-c9f587d4363c}
- DotNetProjects.Migrator.Providers
-
-
- {1FEE70A4-AAD7-4C60-BE60-3F7DC03A8C4D}
- DotNetProjects.Migrator
-
-
- {5270F048-E580-486C-B14C-E5B9F6E539D4}
- DotNetProjects.Migrator.Framework
-
-
-
-
- False
- .NET Framework 3.5 SP1 Client Profile
- false
-
-
- False
- .NET Framework 2.0 %28x86%29
- true
-
-
- False
- .NET Framework 3.0 %28x86%29
- false
-
-
- False
- .NET Framework 3.5
- false
-
-
- False
- .NET Framework 3.5 SP1
- false
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/Migrator.Console/MigratorConsole.cs b/src/Migrator.Console/MigratorConsole.cs
deleted file mode 100644
index 50af4973..00000000
--- a/src/Migrator.Console/MigratorConsole.cs
+++ /dev/null
@@ -1,214 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using Migrator.Framework;
-using Migrator.Providers;
-using Migrator.Tools;
-
-namespace Migrator.MigratorConsole
-{
- ///
- /// Commande line utility to run the migrations
- ///
- ///
- public class MigratorConsole
- {
- readonly string[] args;
- string _connectionString;
- bool _dryrun;
- string _dumpTo;
- bool _list;
- long _migrateTo = -1;
- string _migrationsAssembly;
- ProviderTypes _provider;
- bool _trace;
- string _defaultSchema;
-
- ///
- /// Builds a new console
- ///
- /// Command line arguments
- public MigratorConsole(string[] argv)
- {
- args = argv;
- ParseArguments(argv);
- }
-
- ///
- /// Run the migrator's console
- ///
- /// -1 if error, else 0
- public int Run()
- {
- try
- {
- if (_list)
- List();
- else if (_dumpTo != null)
- Dump();
- else
- Migrate();
- }
- catch (ArgumentException aex)
- {
- Console.WriteLine("Invalid argument '{0}' : {1}", aex.ParamName, aex.Message);
- Console.WriteLine();
- PrintUsage();
- return -1;
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex);
- return -1;
- }
- return 0;
- }
-
- ///
- /// Runs the migrations.
- ///
- public void Migrate()
- {
- CheckArguments();
-
- Migrator mig = GetMigrator();
- if (mig.DryRun)
- mig.Logger.Log("********** Dry run! Not actually applying changes. **********");
-
- if (_migrateTo == -1)
- mig.MigrateToLastVersion();
- else
- mig.MigrateTo(_migrateTo);
- }
-
- ///
- /// List migrations.
- ///
- public void List()
- {
- CheckArguments();
-
- Migrator mig = GetMigrator();
- List appliedMigrations = mig.AppliedMigrations;
-
- Console.WriteLine("Available migrations:");
- foreach (Type t in mig.MigrationsTypes)
- {
- long v = MigrationLoader.GetMigrationVersion(t);
- Console.WriteLine("{0} {1} {2}",
- appliedMigrations.Contains(v) ? "=>" : " ",
- v.ToString().PadLeft(3),
- StringUtils.ToHumanName(t.Name)
- );
- }
- }
-
- public void Dump()
- {
- CheckArguments();
-
- var dumper = new SchemaDumper(_provider, _connectionString, _defaultSchema);
-
- dumper.DumpTo(_dumpTo);
- }
-
- ///
- /// Show usage information and help.
- ///
- public void PrintUsage()
- {
- int tab = 17;
- Version ver = Assembly.GetExecutingAssembly().GetName().Version;
-
- Console.WriteLine("Database migrator - v{0}.{1}.{2}", ver.Major, ver.Minor, ver.Revision);
- Console.WriteLine();
- Console.WriteLine("usage:\nMigrator.Console.exe provider connectionString migrationsAssembly [options]");
- Console.WriteLine();
- Console.WriteLine("\t{0} {1}", "provider".PadRight(tab), "The database provider (SqlServer, MySql, Postgre)");
- Console.WriteLine("\t{0} {1}", "connectionString".PadRight(tab), "Connection string to the database");
- Console.WriteLine("\t{0} {1}", "migrationAssembly".PadRight(tab), "Path to the assembly containing the migrations");
- Console.WriteLine("Options:");
- Console.WriteLine("\t-{0}{1}", "version NO".PadRight(tab), "To specific version to migrate the database to");
- Console.WriteLine("\t-{0}{1}", "defaultSchema ".PadRight(tab), "To specify the default schema");
- Console.WriteLine("\t-{0}{1}", "list".PadRight(tab), "List migrations");
- Console.WriteLine("\t-{0}{1}", "trace".PadRight(tab), "Show debug informations");
- Console.WriteLine("\t-{0}{1}", "dump FILE".PadRight(tab), "Dump the database schema as migration code");
- Console.WriteLine("\t-{0}{1}", "dryrun".PadRight(tab), "Simulation mode (don't actually apply/remove any migrations)");
- Console.WriteLine();
- }
-
- #region Private helper methods
-
- void CheckArguments()
- {
- if (_connectionString == null)
- throw new ArgumentException("Connection string missing", "connectionString");
- if (_migrationsAssembly == null)
- throw new ArgumentException("Migrations assembly missing", "migrationsAssembly");
- }
-
- Migrator GetMigrator()
- {
- Assembly asm = Assembly.LoadFrom(_migrationsAssembly);
-
- var migrator = new Migrator(_provider, _connectionString, _defaultSchema, asm, _trace);
- migrator.args = args;
- migrator.DryRun = _dryrun;
- return migrator;
- }
-
- void ParseArguments(string[] argv)
- {
- for (int i = 0; i < argv.Length; i++)
- {
- if (argv[i].Equals("-list"))
- {
- _list = true;
- }
- else if (argv[i].Equals("-trace"))
- {
- _trace = true;
- }
- else if (argv[i].Equals("-dryrun"))
- {
- _dryrun = true;
- }
- else if (argv[i].Equals("-version"))
- {
- _migrateTo = long.Parse(argv[i + 1]);
- i++;
- }
- else if (argv[i].EndsWith("-defaultSchema"))
- {
- _defaultSchema = argv[i + 1];
- }
- else if (argv[i].Equals("-dump"))
- {
- _dumpTo = argv[i + 1];
- i++;
- }
- else
- {
- if (i == 0) _provider = (ProviderTypes)Enum.Parse(typeof(ProviderTypes), argv[i]);
- if (i == 1) _connectionString = argv[i];
- if (i == 2) _migrationsAssembly = argv[i];
- }
- }
- }
-
- #endregion
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Console/MigratorDotNet.snk b/src/Migrator.Console/MigratorDotNet.snk
deleted file mode 100644
index 5032d709..00000000
Binary files a/src/Migrator.Console/MigratorDotNet.snk and /dev/null differ
diff --git a/src/Migrator.Console/app.config b/src/Migrator.Console/app.config
deleted file mode 100644
index ae779258..00000000
--- a/src/Migrator.Console/app.config
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
diff --git a/src/Migrator.Framework/AssemblyInfo.cs b/src/Migrator.Framework/AssemblyInfo.cs
deleted file mode 100644
index e06d25a4..00000000
--- a/src/Migrator.Framework/AssemblyInfo.cs
+++ /dev/null
@@ -1,4 +0,0 @@
-using System.Reflection;
-
-[assembly: AssemblyTitle("DotNetProjects.Migrator.Framework")]
-[assembly: AssemblyDescription("DotNetProjects.Migrator Framework")]
\ No newline at end of file
diff --git a/src/Migrator.Framework/Column.cs b/src/Migrator.Framework/Column.cs
deleted file mode 100644
index 9b80f959..00000000
--- a/src/Migrator.Framework/Column.cs
+++ /dev/null
@@ -1,100 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-using System.Data;
-
-namespace Migrator.Framework
-{
- ///
- /// Represents a table column.
- ///
- public class Column : IColumn, IDbField
- {
- public Column(string name)
- {
- Name = name;
- }
-
- public Column(string name, DbType type)
- {
- Name = name;
- Type = type;
- }
-
- public Column(string name, DbType type, int size)
- {
- Name = name;
- Type = type;
- Size = size;
- }
-
- public Column(string name, DbType type, object defaultValue)
- {
- Name = name;
- Type = type;
- DefaultValue = defaultValue;
- }
-
- public Column(string name, DbType type, ColumnProperty property)
- {
- Name = name;
- Type = type;
- ColumnProperty = property;
- }
-
- public Column(string name, DbType type, int size, ColumnProperty property)
- {
- Name = name;
- Type = type;
- Size = size;
- ColumnProperty = property;
- }
-
- public Column(string name, DbType type, int size, ColumnProperty property, object defaultValue)
- {
- Name = name;
- Type = type;
- Size = size;
- ColumnProperty = property;
- DefaultValue = defaultValue;
- }
-
- public Column(string name, DbType type, ColumnProperty property, object defaultValue)
- {
- Name = name;
- Type = type;
- ColumnProperty = property;
- DefaultValue = defaultValue;
- }
-
- public string Name { get; set; }
-
- public DbType Type { get; set; }
-
- public int Size { get; set; }
-
- public ColumnProperty ColumnProperty { get; set; }
-
- public object DefaultValue { get; set; }
-
- public bool IsIdentity
- {
- get { return (ColumnProperty & ColumnProperty.Identity) == ColumnProperty.Identity; }
- }
-
- public bool IsPrimaryKey
- {
- get { return (ColumnProperty & ColumnProperty.PrimaryKey) == ColumnProperty.PrimaryKey; }
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/ColumnProperty.cs b/src/Migrator.Framework/ColumnProperty.cs
deleted file mode 100644
index 79d515a5..00000000
--- a/src/Migrator.Framework/ColumnProperty.cs
+++ /dev/null
@@ -1,74 +0,0 @@
-using System;
-
-namespace Migrator.Framework
-{
- ///
- /// Represents a table column properties.
- ///
- [Flags]
- public enum ColumnProperty
- {
- None = 0,
- ///
- /// Null is allowable
- ///
- Null = 1,
- ///
- /// Null is not allowable
- ///
- NotNull = 2,
- ///
- /// Identity column, autoinc
- ///
- Identity = 4,
- ///
- /// Unique Column
- ///
- Unique = 8,
- ///
- /// Indexed Column
- ///
- Indexed = 16,
- ///
- /// Unsigned Column
- ///
- Unsigned = 32,
-
- CaseSensitive = 64,
- ///
- /// Foreign Key
- ///
- ForeignKey = Unsigned | Null,
- ///
- /// Primary Key
- ///
- PrimaryKey = 128 | Unsigned | NotNull,
- ///
- /// Primary key. Make the column a PrimaryKey and unsigned
- ///
- PrimaryKeyWithIdentity = PrimaryKey | Identity
- }
-
- public static class ColumnPropertyExtensions
- {
- public static bool IsSet(this ColumnProperty fruits, ColumnProperty flags)
- {
- return (fruits & flags) == flags;
- }
-
- public static bool IsNotSet(this ColumnProperty fruits, ColumnProperty flags)
- {
- return (fruits & (~flags)) == 0;
- }
-
- public static ColumnProperty Set(this ColumnProperty fruits, ColumnProperty flags)
- {
- return fruits | flags;
- }
-
- public static ColumnProperty Clear(this ColumnProperty fruits, ColumnProperty flags)
- {
- return fruits & (~flags);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/DataRecordExtensions.cs b/src/Migrator.Framework/DataRecordExtensions.cs
deleted file mode 100644
index 063dfe75..00000000
--- a/src/Migrator.Framework/DataRecordExtensions.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-using System;
-using System.Data;
-
-namespace Migrator.Framework
-{
- public static class DataRecordExtensions
- {
- public static T TryParse(this IDataRecord record, string name)
- {
- return TryParse(record, name, () => default(T));
- }
-
- public static T TryParse(this IDataRecord record, string name, Func defaultValue)
- {
- object value = record[name];
-
- Type type = typeof (T);
-
- if (value == null || Convert.IsDBNull(value)) return defaultValue();
-
- if (type == typeof (DateTime?) || type == typeof (DateTime))
- {
- return (T) (object) (Convert.ToDateTime(value));
- }
-
- if (type == typeof (Guid) || type == typeof (Guid?))
- {
- if (value is byte[]) return (T) (object) new Guid((byte[]) value);
- return (T) ((object) new Guid(value.ToString()));
- }
-
- if (type == typeof (string))
- {
- return (T) ((object) value.ToString());
- }
-
- if (type == typeof (Int32?) || type == typeof (Int32))
- {
- return (T) (object) Convert.ToInt32(value);
- }
-
- if (type == typeof (Int64?) || type == typeof (Int64))
- {
- return (T) (object) Convert.ToInt64(value);
- }
-
- if (type == typeof (bool) || type == typeof (bool?))
- {
- if (value is Int32 || value is Int64 || value is Int16 || value is UInt16 || value is UInt32 || value is UInt64)
- {
- long intValue = Convert.ToInt64(value);
- return (T) (object) (intValue != 0);
- }
-
- if (value is string)
- {
- bool result;
- if (bool.TryParse((string) value, out result))
- {
- return (T) (object) result;
- }
- }
-
- return (T) value;
- }
-
- try
- {
- return (T) value;
- }
- catch (InvalidCastException ex)
- {
- throw new MigrationException(string.Format("Invalid cast exception of value: {0} of type: {1} to type: {2} (field name: {3})", value, value.GetType(), typeof (T), name), ex);
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/DotNetProjects.Migrator.Framework.csproj b/src/Migrator.Framework/DotNetProjects.Migrator.Framework.csproj
deleted file mode 100644
index 530d1b96..00000000
--- a/src/Migrator.Framework/DotNetProjects.Migrator.Framework.csproj
+++ /dev/null
@@ -1,133 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 9.0.30729
- 2.0
- {5270F048-E580-486C-B14C-E5B9F6E539D4}
- Library
- Migrator.Framework
- DotNetProjects.Migrator.Framework
-
-
- 3.5
-
-
- true
- MigratorDotNet.snk
- v4.0
- publish\
- true
- Disk
- false
- Foreground
- 7
- Days
- false
- false
- true
- 0
- 1.0.0.%2a
- false
- false
- true
-
-
-
- true
- full
- false
- bin\Debug\
- DEBUG;TRACE
- prompt
- 4
- AllRules.ruleset
-
-
- pdbonly
- true
- bin\Release\
- TRACE
- prompt
- 4
- AllRules.ruleset
-
-
-
-
-
-
-
- GlobalAssemblyInfo.cs
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- False
- .NET Framework 3.5 SP1 Client Profile
- false
-
-
- False
- .NET Framework 3.5 SP1
- true
-
-
- False
- Windows Installer 3.1
- true
-
-
-
-
-
\ No newline at end of file
diff --git a/src/Migrator.Framework/ForeignKeyConstraint.cs b/src/Migrator.Framework/ForeignKeyConstraint.cs
deleted file mode 100644
index a4d5cd92..00000000
--- a/src/Migrator.Framework/ForeignKeyConstraint.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace Migrator.Framework
-{
- public class ForeignKeyConstraint : IDbField
- {
- public ForeignKeyConstraint()
- { }
-
- public ForeignKeyConstraint(string name, string table, string[] columns, string pkTable, string[] pkColumns)
- {
- this.Name = name;
- this.Table = table;
- this.Columns = columns;
- this.PkTable = pkTable;
- this.PkColumns = pkColumns;
- }
-
- public string Name { get; set; }
- public string Table { get; set; }
- public string[] Columns { get; set; }
- public string PkTable { get; set; }
- public string[] PkColumns { get; set; }
- }
-}
diff --git a/src/Migrator.Framework/ForeignKeyConstraintType.cs b/src/Migrator.Framework/ForeignKeyConstraintType.cs
deleted file mode 100644
index 802ff2a1..00000000
--- a/src/Migrator.Framework/ForeignKeyConstraintType.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-namespace Migrator.Framework
-{
- public enum ForeignKeyConstraintType
- {
- Cascade,
- SetNull,
- NoAction,
- Restrict,
- SetDefault
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/IDbField.cs b/src/Migrator.Framework/IDbField.cs
deleted file mode 100644
index 672c336c..00000000
--- a/src/Migrator.Framework/IDbField.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace Migrator.Framework
-{
- public interface IDbField
- {
- string Name { get; set; }
- }
-}
diff --git a/src/Migrator.Framework/ILogger.cs b/src/Migrator.Framework/ILogger.cs
deleted file mode 100644
index 06e0baad..00000000
--- a/src/Migrator.Framework/ILogger.cs
+++ /dev/null
@@ -1,97 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-namespace Migrator.Framework
-{
- public interface ILogger
- {
- ///
- /// Log that we have started a migration
- ///
- /// Start list of versions
- /// Final Version
- void Started(List currentVersion, long finalVersion);
-
- ///
- /// Log that we are migrating up
- ///
- /// Version we are migrating to
- /// Migration name
- void MigrateUp(long version, string migrationName);
-
- ///
- /// Log that we are migrating down
- ///
- /// Version we are migrating to
- /// Migration name
- void MigrateDown(long version, string migrationName);
-
- ///
- /// Inform that a migration corresponding to the number of
- /// version is untraceable (not found?) and will be ignored.
- ///
- /// Version we couldnt find
- void Skipping(long version);
-
- ///
- /// Log that we are rolling back to version
- ///
- ///
- /// version
- ///
- void RollingBack(long originalVersion);
-
- ///
- /// Log a Sql statement that changes the schema or content of the database as part of a migration
- ///
- ///
- /// SELECT statements should not be logged using this method as they do not alter the data or schema of the
- /// database.
- ///
- /// The Sql statement to log
- void ApplyingDBChange(string sql);
-
- ///
- /// Log that we had an exception on a migration
- ///
- /// The version of the migration that caused the exception.
- /// The name of the migration that caused the exception.
- /// The exception itself
- void Exception(long version, string migrationName, Exception ex);
-
- ///
- /// Log that we had an exception on a migration
- ///
- /// An informative message to show to the user.
- /// The exception itself
- void Exception(string message, Exception ex);
-
- ///
- /// Log that we have finished a migration
- ///
- /// List of versions with which we started
- /// Final Version
- void Finished(List currentVersion, long finalVersion);
-
- ///
- /// Log a message
- ///
- /// The format string ("{0}, blabla {1}").
- /// Parameters to apply to the format string.
- void Log(string format, params object[] args);
-
- ///
- /// Log a Warning
- ///
- /// The format string ("{0}, blabla {1}").
- /// Parameters to apply to the format string.
- void Warn(string format, params object[] args);
-
- ///
- /// Log a Trace Message
- ///
- /// The format string ("{0}, blabla {1}").
- /// Parameters to apply to the format string.
- void Trace(string format, params object[] args);
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/IMigration.cs b/src/Migrator.Framework/IMigration.cs
deleted file mode 100644
index f81653f9..00000000
--- a/src/Migrator.Framework/IMigration.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-namespace Migrator.Framework
-{
- public interface IMigration
- {
- string Name { get; }
-
- ///
- /// Represents the database.
- /// .
- ///
- /// Migration.Framework.ITransformationProvider
- ITransformationProvider Database { get; set; }
-
- ///
- /// Defines tranformations to port the database to the current version.
- ///
- void Up();
-
- ///
- /// This is run after the Up transaction has been committed
- ///
- void AfterUp();
-
- ///
- /// Defines transformations to revert things done in Up.
- ///
- void Down();
-
- ///
- /// This is run after the Down transaction has been committed
- ///
- void AfterDown();
-
- ///
- /// This gets called once on the first migration object.
- ///
- void InitializeOnce(string[] args);
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/ITransformationProvider.cs b/src/Migrator.Framework/ITransformationProvider.cs
deleted file mode 100644
index cb79ecf6..00000000
--- a/src/Migrator.Framework/ITransformationProvider.cs
+++ /dev/null
@@ -1,632 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.Common;
-
-namespace Migrator.Framework
-{
- ///
- /// The main interface to use in Migrations to make changes on a database schema.
- ///
- public interface ITransformationProvider : IDisposable
- {
- ///
- /// Get this provider or a NoOp provider if you are not running in the context of 'provider'.
- ///
- ITransformationProvider this[string provider] { get; }
-
- string SchemaInfoTable { get; set; }
-
- ///
- /// The list of Migrations currently applied to the database.
- ///
- List AppliedMigrations { get; }
-
- ///
- /// Connection string to the database
- ///
- String ConnectionString { get; }
-
- ///
- /// Logger used to log details of operations performed during migration
- ///
- ILogger Logger { get; set; }
-
- ///
- /// Add a column to an existing table
- ///
- /// The name of the table that will get the new column
- /// The name of the new column
- /// The data type for the new columnd
- /// The precision or size of the column
- /// Properties that can be ORed together
- /// The default value of the column if no value is given in a query
- void AddColumn(string table, string column, DbType type, int size, ColumnProperty property, object defaultValue);
-
- ///
- /// Add a column to an existing table
- ///
- /// The name of the table that will get the new column
- /// The name of the new column
- /// The data type for the new columnd
- void AddColumn(string table, string column, DbType type);
-
- ///
- /// Add a column to an existing table
- ///
- /// The name of the table that will get the new column
- /// The name of the new column
- /// The data type for the new columnd
- /// The precision or size of the column
- void AddColumn(string table, string column, DbType type, int size);
-
- ///
- /// Add a column to an existing table
- ///
- /// The name of the table that will get the new column
- /// The name of the new column
- /// The data type for the new columnd
- /// The precision or size of the column
- /// Properties that can be ORed together
- void AddColumn(string table, string column, DbType type, int size, ColumnProperty property);
-
- ///
- /// Add a column to an existing table
- ///
- /// The name of the table that will get the new column
- /// The name of the new column
- /// The data type for the new columnd
- /// Properties that can be ORed together
- void AddColumn(string table, string column, DbType type, ColumnProperty property);
-
- ///
- /// Add a column to an existing table with the default column size.
- ///
- /// The name of the table that will get the new column
- /// The name of the new column
- /// The data type for the new columnd
- /// The default value of the column if no value is given in a query
- void AddColumn(string table, string column, DbType type, object defaultValue);
-
- ///
- /// Add a column to an existing table
- ///
- /// The name of the table that will get the new column
- /// An instance of a Column with the specified properties
- void AddColumn(string table, Column column);
-
- ///
- /// Add a foreign key constraint
- ///
- /// The name of the foreign key. e.g. FK_TABLE_REF
- /// The table that the foreign key will be created in (eg. Table.FK_id)
- /// The columns that are the foreign keys (eg. FK_id)
- /// The table that holds the primary keys (eg. Table.PK_id)
- /// The columns that are the primary keys (eg. PK_id)
- void AddForeignKey(string name, string foreignTable, string[] foreignColumns, string primaryTable, string[] primaryColumns);
-
- ///
- /// Add a foreign key constraint
- ///
- /// The name of the foreign key. e.g. FK_TABLE_REF
- /// The table that the foreign key will be created in (eg. Table.FK_id)
- /// The columns that are the foreign keys (eg. FK_id)
- /// The table that holds the primary keys (eg. Table.PK_id)
- /// The columns that are the primary keys (eg. PK_id)
- /// Constraint parameters
- void AddForeignKey(string name, string foreignTable, string[] foreignColumns, string primaryTable, string[] primaryColumns, ForeignKeyConstraintType constraint);
-
- ///
- /// Add a foreign key constraint
- ///
- ///
- /// The name of the foreign key. e.g. FK_TABLE_REF
- /// The table that the foreign key will be created in (eg. Table.FK_id)
- /// The column that is the foreign key (eg. FK_id)
- /// The table that holds the primary keys (eg. Table.PK_id)
- /// The column that is the primary key (eg. PK_id)
- void AddForeignKey(string name, string foreignTable, string foreignColumn, string primaryTable, string primaryColumn);
-
- ///
- /// Add a foreign key constraint
- ///
- /// The name of the foreign key. e.g. FK_TABLE_REF
- /// The table that the foreign key will be created in (eg. Table.FK_id)
- /// The column that is the foreign key (eg. FK_id)
- /// The table that holds the primary key (eg. Table.PK_id)
- /// The column that is the primary key (eg. PK_id)
- /// Constraint parameters
- void AddForeignKey(string name, string foreignTable, string foreignColumn, string primaryTable, string primaryColumn, ForeignKeyConstraintType constraint);
-
- ///
- /// Add a foreign key constraint when you don't care about the name of the constraint.
- /// Warning: This will prevent you from dropping the constraint since you won't know the name.
- ///
- /// The table that the foreign key will be created in (eg. Table.FK_id)
- /// The column that is the foreign key (eg. FK_id)
- /// The table that holds the primary key (eg. Table.PK_id)
- /// The column that is the primary key (eg. PK_id)
- void GenerateForeignKey(string foreignTable, string foreignColumn, string primaryTable, string primaryColumn);
-
- ///
- /// Add a foreign key constraint when you don't care about the name of the constraint.
- /// Warning: This will prevent you from dropping the constraint since you won't know the name.
- ///
- /// The table that the foreign key will be created in (eg. Table.FK_id)
- /// The columns that are the foreign keys (eg. FK_id)
- /// The table that holds the primary key (eg. Table.PK_id)
- /// The column that is the primary key (eg. PK_id)
- void GenerateForeignKey(string foreignTable, string[] foreignColumns, string primaryTable, string[] primaryColumns);
-
- ///
- /// Add a foreign key constraint when you don't care about the name of the constraint.
- /// Warning: This will prevent you from dropping the constraint since you won't know the name.
- ///
- /// The table that the foreign key will be created in (eg. Table.FK_id)
- /// The columns that are the foreign keys (eg. FK_id)
- /// The table that holds the primary key (eg. Table.PK_id)
- /// The columns that are the primary keys (eg. PK_id)
- /// Constraint parameters
- void GenerateForeignKey(string foreignTable, string[] foreignColumns, string primaryTable, string[] primaryColumns, ForeignKeyConstraintType constraint);
-
- ///
- /// Add a foreign key constraint when you don't care about the name of the constraint.
- /// Warning: This will prevent you from dropping the constraint since you won't know the name.
- ///
- /// The table that the foreign key will be created in (eg. Table.FK_id)
- /// The columns that are the foreign keys (eg. FK_id)
- /// The table that holds the primary key (eg. Table.PK_id)
- /// The column that is the primary key (eg. PK_id)
- /// Constraint parameters
- void GenerateForeignKey(string foreignTable, string foreignColumn, string primaryTable, string primaryColumn,
- ForeignKeyConstraintType constraint);
-
- ///
- /// Add a foreign key constraint when you don't care about the name of the constraint.
- /// Warning: This will prevent you from dropping the constraint since you won't know the name.
- ///
- /// The current expectations are that there is a column named the same as the foreignTable present in
- /// the table. This is subject to change because I think it's not a good convention.
- ///
- /// The table that the foreign key will be created in (eg. Table.FK_id)
- /// The table that holds the primary key (eg. Table.PK_id)
- void GenerateForeignKey(string foreignTable, string primaryTable);
-
- ///
- /// Add a foreign key constraint when you don't care about the name of the constraint.
- /// Warning: This will prevent you from dropping the constraint since you won't know the name.
- ///
- /// The current expectations are that there is a column named the same as the foreignTable present in
- /// the table. This is subject to change because I think it's not a good convention.
- ///
- /// The table that the foreign key will be created in (eg. Table.FK_id)
- /// The table that holds the primary key (eg. Table.PK_id)
- ///
- void GenerateForeignKey(string foreignTable, string primaryTable, ForeignKeyConstraintType constraint);
-
- ///
- /// Add a primary key to a table
- ///
- /// The name of the primary key to add.
- /// The name of the table that will get the primary key.
- /// The name of the column or columns that are in the primary key.
- void AddPrimaryKey(string name, string table, params string[] columns);
-
- ///
- /// Add a constraint to a table
- ///
- /// The name of the constraint to add.
- /// The name of the table that will get the constraint
- /// The name of the column or columns that will get the constraint.
- void AddUniqueConstraint(string name, string table, params string[] columns);
-
- ///
- /// Add a constraint to a table
- ///
- /// The name of the constraint to add.
- /// The name of the table that will get the constraint
- /// The check constraint definition.
- void AddCheckConstraint(string name, string table, string checkSql);
-
- void AddView(string name, string tableName, params IViewField[] fields);
-
- ///
- /// Add a table
- ///
- /// The name of the table to add.
- /// The columns that are part of the table.
- void AddTable(string name, params IDbField[] columns);
-
- ///
- /// Add a table
- ///
- /// The name of the table to add.
- /// The name of the database engine to use. (MySQL)
- /// The columns that are part of the table.
- void AddTable(string name, string engine, params IDbField[] columns);
-
- ///
- /// Start a transction
- ///
- void BeginTransaction();
-
- ///
- /// Change the definition of an existing column.
- ///
- /// The name of the table that will get the new column
- /// An instance of a Column with the specified properties and the name of an existing column
- void ChangeColumn(string table, Column column);
-
- void RemoveColumnDefaultValue(string table, string column);
-
- ///
- /// Check to see if a column exists
- ///
- ///
- ///
- ///
- bool ColumnExists(string table, string column);
-
- ///
- /// Commit the running transction
- ///
- void Commit();
-
- ///
- /// Check to see if a constraint exists
- ///
- /// The name of the constraint
- /// The table that the constraint lives on.
- ///
- bool ConstraintExists(string table, string name);
-
- ///
- /// Check to see if a primary key constraint exists on the table
- ///
- /// The name of the primary key
- /// The table that the constraint lives on.
- ///
- bool PrimaryKeyExists(string table, string name);
-
- ///
- /// Execute an arbitrary SQL query
- ///
- /// The SQL to execute.
- /// timeout
- /// Array of parameters of type object
- ///
- int ExecuteNonQuery(string sql, int timeout, object[] args);
-
- ///
- /// Execute an arbitrary SQL query
- ///
- /// The SQL to execute.
- /// timeout
- ///
- int ExecuteNonQuery(string sql,int timeout);
-
- int ExecuteNonQuery(string sql);
- ///
- /// Execute an arbitrary SQL query
- ///
- /// The SQL to execute.
- ///
- IDataReader ExecuteQuery(string sql);
-
- ///
- /// Execute an arbitrary SQL query
- ///
- /// The SQL to execute.
- /// A single value that is returned.
- object ExecuteScalar(string sql);
-
- List ExecuteStringQuery(string sql, params object[] args);
-
- Index[] GetIndexes(string table);
-
- ///
- /// Get the information about the columns in a table
- ///
- /// The table name that you want the columns for.
- ///
- Column[] GetColumns(string table);
-
- ///
- /// Get information about a single column in a table
- ///
- /// The table name that you want the columns for.
- /// The column name for which you want information.
- ///
- Column GetColumnByName(string table, string column);
-
- ///
- /// Get the names of all of the tables
- ///
- /// The names of all the tables.
- string[] GetTables();
-
- ForeignKeyConstraint[] GetForeignKeyConstraints(string table);
-
- ///
- /// Insert data into a table
- ///
- /// The table that will get the new data
- /// The names of the columns
- /// The values in the same order as the columns
- ///
- int Insert(string table, string[] columns, object[] values);
-
- ///
- /// Delete data from a table
- ///
- /// The table that will have the data deleted
- /// The names of the columns used in a where clause
- /// The values in the same order as the columns
- ///
- int Delete(string table, string[] columns, string[] values);
-
- ///
- /// Delete data from a table
- ///
- /// The table that will have the data deleted
- /// The name of the column used in a where clause
- /// The value for the where clause
- ///
- int Delete(string table, string whereColumn, string whereValue);
-
- ///
- /// Truncate data from a table
- ///
- /// The table that will have the data deleted
- ///
- int TruncateTable(string table);
-
- ///
- /// Marks a Migration version number as having been applied
- ///
- /// The version number of the migration that was applied
- void MigrationApplied(long version, string scope);
-
- ///
- /// Marks a Migration version number as having been rolled back from the database
- ///
- /// The version number of the migration that was removed
- void MigrationUnApplied(long version, string scope);
-
- ///
- /// Remove an existing column from a table
- ///
- /// The name of the table to remove the column from
- /// The column to remove
- void RemoveColumn(string table, string column);
-
- ///
- /// Remove an existing foreign key constraint
- ///
- /// The table that contains the foreign key.
- /// The name of the foreign key to remove
- void RemoveForeignKey(string table, string name);
-
- ///
- /// Remove an existing constraint
- ///
- /// The table that contains the foreign key.
- /// The name of the constraint to remove
- void RemoveConstraint(string table, string name);
-
- void RemoveAllConstraints(string table);
-
- ///
- /// Remove an existing primary key
- ///
- /// The table that contains the primary key.
- void RemovePrimaryKey(string table);
-
- ///
- /// Remove an existing table
- ///
- /// The name of the table
- void RemoveTable(string tableName);
-
- ///
- /// Rename an existing table
- ///
- /// The old name of the table
- /// The new name of the table
- void RenameTable(string oldName, string newName);
-
- ///
- /// Rename an existing table
- ///
- /// The name of the table
- /// The old name of the column
- /// The new name of the column
- void RenameColumn(string tableName, string oldColumnName, string newColumnName);
-
- ///
- /// Rollback the currently running transaction.
- ///
- void Rollback();
-
- ///
- /// Get values from a table
- ///
- /// The columns to select
- /// The table to select from
- /// The where clause to limit the selection
- ///
- IDataReader Select(string what, string from, string where);
-
- ///
- /// Get values from a table
- ///
- /// The columns to select
- /// The table to select from
- ///
- IDataReader Select(string what, string from);
-
- ///
- /// Get a single value from a table
- ///
- /// The columns to select
- /// The table to select from
- ///
- ///
- object SelectScalar(string what, string from, string where);
-
- ///
- /// Get a single value from a table
- ///
- /// The columns to select
- /// The table to select from
- ///
- object SelectScalar(string what, string from);
-
- ///
- /// Check if a table already exists
- ///
- /// The name of the table that you want to check on.
- ///
- bool TableExists(string tableName);
-
- ///
- /// Update the values in a table
- ///
- /// The name of the table to update
- /// The names of the columns.
- /// The values for the columns in the same order as the names.
- ///
- int Update(string table, string[] columns, object[] values);
-
- ///
- /// Update the values in a table
- ///
- /// The name of the table to update
- /// The names of the columns.
- /// The values for the columns in the same order as the names.
- /// A where clause to limit the update
- ///
- int Update(string table, string[] columns, object[] values, string where);
-
- int Update(string table, string[] columns, object[] values, string[] whereColumns, object[] whereValues);
-
- ///
- /// Get a command instance
- ///
- ///
- IDbCommand GetCommand();
-
- ///
- /// Execute a schema builder
- ///
- ///
- void ExecuteSchemaBuilder(SchemaBuilder.SchemaBuilder schemaBuilder);
-
-
- void RemoveAllForeignKeys(string tableName, string columnName);
-
- bool IsThisProvider(string provider);
-
- ///
- /// Quote a multiple column names, if required
- ///
- ///
- ///
- string[] QuoteColumnNamesIfRequired(params string[] columnNames);
-
- ///
- /// Quaote column if required
- ///
- ///
- ///
- string QuoteColumnNameIfRequired(string name);
-
- ///
- /// Quote table name if required
- ///
- ///
- ///
- string QuoteTableNameIfRequired(string name);
-
- ///
- /// Encodes a guid value as a string, suitable for inclusion in sql statement
- ///
- ///
- ///
- string Encode(Guid guid);
-
- ///
- /// Change the target database
- ///
- /// Name of the new target database
- void SwitchDatabase(string databaseName);
-
-
- ///
- /// Get a list of databases available on the server
- ///
- List GetDatabases();
-
- ///
- /// Checks to see if a database with specific name exists on the server
- ///
- bool DatabaseExists(string name);
-
- ///
- /// Create a new database on the server
- ///
- /// Name of the new database
- void CreateDatabases(string databaseName);
-
- ///
- /// Delete a database from the server
- ///
- /// Name of the database to delete
- void DropDatabases(string databaseName);
-
- void AddIndex(string table, Index index);
-
- ///
- /// Add a multi-column index to a table
- ///
- /// The name of the index to add.
- /// The name of the table that will get the index.
- /// The name of the column or columns that are in the index.
- void AddIndex(string name, string table, params string[] columns);
-
- ///
- /// Check to see if an index exists
- ///
- /// The name of the index
- /// The table that the index lives on.
- ///
- bool IndexExists(string table, string name);
-
- ///
- /// Remove an existing index
- ///
- /// The table that contains the index.
- /// The name of the index to remove
- void RemoveIndex(string table, string name);
-
- ///
- /// Generate parameter name based on an index number
- ///
- /// The index number of the parameter
- string GenerateParameterName(int index);
-
- ///
- /// Remove all indexes of a table
- ///
- /// The table name
- void RemoveAllIndexes(string table);
-
- string Concatenate(params string[] strings);
-
- IDbConnection Connection { get; }
-
- IEnumerable GetTables(string schema);
-
- IEnumerable GetColumns(string schema, string table);
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/IViewField.cs b/src/Migrator.Framework/IViewField.cs
deleted file mode 100644
index 5a68a87a..00000000
--- a/src/Migrator.Framework/IViewField.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace Migrator.Framework
-{
- public interface IViewField
- {
- string TableName { get; set; }
- string ColumnName { get; set; }
-
- string KeyColumnName { get; set; }
- string ParentTableName { get; set; }
- string ParentKeyColumnName { get; set; }
- }
-}
diff --git a/src/Migrator.Framework/Index.cs b/src/Migrator.Framework/Index.cs
deleted file mode 100644
index 5eb27c13..00000000
--- a/src/Migrator.Framework/Index.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace Migrator.Framework
-{
- public class Index : IDbField
- {
- public string Name { get; set; }
- public bool Unique { get; set; }
- public bool Clustered { get; set; }
- public bool PrimaryKey { get; set; }
- public string[] KeyColumns { get; set; }
- public string[] IncludeColumns { get; set; }
- }
-}
diff --git a/src/Migrator.Framework/JoiningTableTransformationProviderExtensions.cs b/src/Migrator.Framework/JoiningTableTransformationProviderExtensions.cs
deleted file mode 100644
index 79eab098..00000000
--- a/src/Migrator.Framework/JoiningTableTransformationProviderExtensions.cs
+++ /dev/null
@@ -1,85 +0,0 @@
-using System.Collections.Generic;
-using System.Data;
-using System.Linq;
-using System.Text;
-using Migrator.Framework.Support;
-
-namespace Migrator.Framework
-{
- ///
- /// A set of extension methods for the transformation provider to make it easier to
- /// build many-to-many joining tables (takes care of adding the joining table and foreign
- /// key constraints as necessary.
- /// This functionality was useful when bootstrapping a number of projects a few years ago, but
- /// now that most changes are brown-field I'm thinking of removing these methods as it's easier to maintain
- /// code that creates the tables etc. directly within migration.
- ///
- public static class JoiningTableTransformationProviderExtensions
- {
- public static ITransformationProvider AddManyToManyJoiningTable(this ITransformationProvider database, string schema, string lhsTableName, string lhsKey, string rhsTableName, string rhsKey)
- {
- string joiningTable = GetNameOfJoiningTable(lhsTableName, rhsTableName);
-
- return AddManyToManyJoiningTable(database, schema, lhsTableName, lhsKey, rhsTableName, rhsKey, joiningTable);
- }
-
- static string GetNameOfJoiningTable(string lhsTableName, string rhsTableName)
- {
- return (Inflector.Singularize(lhsTableName) ?? lhsTableName) + (Inflector.Pluralize(rhsTableName) ?? rhsTableName);
- }
-
- public static ITransformationProvider AddManyToManyJoiningTable(this ITransformationProvider database, string schema, string lhsTableName, string lhsKey, string rhsTableName, string rhsKey, string joiningTableName)
- {
- string joiningTableWithSchema = TransformationProviderUtility.FormatTableName(schema, joiningTableName);
-
- string joinLhsKey = Inflector.Singularize(lhsTableName) + "Id";
- string joinRhsKey = Inflector.Singularize(rhsTableName) + "Id";
-
- database.AddTable(joiningTableWithSchema,
- new Column(joinLhsKey, DbType.Guid, ColumnProperty.NotNull),
- new Column(joinRhsKey, DbType.Guid, ColumnProperty.NotNull));
-
- string pkName = "PK_" + joiningTableName;
-
- pkName = ShortenKeyNameToBeSuitableForOracle(pkName);
-
- database.AddPrimaryKey(pkName, joiningTableWithSchema, joinLhsKey, joinRhsKey);
-
- string lhsTableNameWithSchema = TransformationProviderUtility.FormatTableName(schema, lhsTableName);
- string rhsTableNameWithSchema = TransformationProviderUtility.FormatTableName(schema, rhsTableName);
-
- string lhsFkName = TransformationProviderUtility.CreateForeignKeyName(lhsTableName, joiningTableName);
- database.AddForeignKey(lhsFkName, joiningTableWithSchema, joinLhsKey, lhsTableNameWithSchema, lhsKey, ForeignKeyConstraintType.NoAction);
-
- string rhsFkName = TransformationProviderUtility.CreateForeignKeyName(rhsTableName, joiningTableName);
- database.AddForeignKey(rhsFkName, joiningTableWithSchema, joinRhsKey, rhsTableNameWithSchema, rhsKey, ForeignKeyConstraintType.NoAction);
-
- return database;
- }
-
- static string ShortenKeyNameToBeSuitableForOracle(string pkName)
- {
- return TransformationProviderUtility.AdjustNameToSize(pkName, TransformationProviderUtility.MaxLengthForForeignKeyInOracle, false);
- }
-
- public static ITransformationProvider RemoveManyToManyJoiningTable(this ITransformationProvider database, string schema, string lhsTableName, string rhsTableName)
- {
- string joiningTable = GetNameOfJoiningTable(lhsTableName, rhsTableName);
- return RemoveManyToManyJoiningTable(database, schema, lhsTableName, rhsTableName, joiningTable);
- }
-
- public static ITransformationProvider RemoveManyToManyJoiningTable(this ITransformationProvider database, string schema, string lhsTableName, string rhsTableName, string joiningTableName)
- {
- string joiningTableNameWithSchema = TransformationProviderUtility.FormatTableName(schema, joiningTableName);
- string lhsFkName = TransformationProviderUtility.CreateForeignKeyName(lhsTableName, joiningTableName);
- string rhsFkName = TransformationProviderUtility.CreateForeignKeyName(rhsTableName, joiningTableName);
-
- database.RemoveForeignKey(joiningTableNameWithSchema, lhsFkName);
- database.RemoveForeignKey(joiningTableNameWithSchema, rhsFkName);
- database.RemoveTable(joiningTableNameWithSchema);
-
- return database;
- }
- }
-
-}
diff --git a/src/Migrator.Framework/Loggers/IAttachableLogger.cs b/src/Migrator.Framework/Loggers/IAttachableLogger.cs
deleted file mode 100644
index 45b82ed1..00000000
--- a/src/Migrator.Framework/Loggers/IAttachableLogger.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-namespace Migrator.Framework.Loggers
-{
- ///
- /// ILogger interface.
- /// Implicit in this interface is that the logger will delegate actual
- /// logging to the (s) that have been attached
- ///
- public interface IAttachableLogger : ILogger
- {
- ///
- /// Attach an
- ///
- ///
- void Attach(ILogWriter writer);
-
- ///
- /// Detach an
- ///
- ///
- void Detach(ILogWriter writer);
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/Loggers/ILogWriter.cs b/src/Migrator.Framework/Loggers/ILogWriter.cs
deleted file mode 100644
index 8042c155..00000000
--- a/src/Migrator.Framework/Loggers/ILogWriter.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-namespace Migrator.Framework.Loggers
-{
- ///
- /// Handles writing a message to the log medium (i.e. file, console)
- ///
- public interface ILogWriter
- {
- ///
- /// Write this message
- ///
- ///
- ///
- void Write(string message, params object[] args);
-
- ///
- /// Write this message, as a line
- ///
- ///
- ///
- void WriteLine(string message, params object[] args);
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/Loggers/Logger.cs b/src/Migrator.Framework/Loggers/Logger.cs
deleted file mode 100644
index ae093ddc..00000000
--- a/src/Migrator.Framework/Loggers/Logger.cs
+++ /dev/null
@@ -1,171 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-using System;
-using System.Collections.Generic;
-
-namespace Migrator.Framework.Loggers
-{
- ///
- /// Text logger for the migration mediator
- ///
- public class Logger : IAttachableLogger
- {
- readonly bool _trace;
- readonly List _writers = new List();
-
- public Logger(bool trace)
- {
- _trace = trace;
- }
-
- public Logger(bool trace, params ILogWriter[] writers)
- : this(trace)
- {
- _writers.AddRange(writers);
- }
-
- public void Attach(ILogWriter writer)
- {
- _writers.Add(writer);
- }
-
- public void Detach(ILogWriter writer)
- {
- _writers.Remove(writer);
- }
-
- public void Started(List currentVersions, long finalVersion)
- {
- WriteLine("Latest version applied : {0}. Target version : {1}", LatestVersion(currentVersions), finalVersion);
- }
-
- public void MigrateUp(long version, string migrationName)
- {
- WriteLine("Applying {0}: {1}", version.ToString(), migrationName);
- }
-
- public void MigrateDown(long version, string migrationName)
- {
- WriteLine("Removing {0}: {1}", version.ToString(), migrationName);
- }
-
- public void Skipping(long version)
- {
- WriteLine("{0} {1}", version.ToString(), "");
- }
-
- public void RollingBack(long originalVersion)
- {
- WriteLine("Rolling back to migration {0}", originalVersion);
- }
-
- public void ApplyingDBChange(string sql)
- {
- Log(sql);
- }
-
- public void Exception(long version, string migrationName, Exception ex)
- {
- WriteLine("============ Error Detail ============");
- WriteLine("Error in migration: {0}", version);
- LogExceptionDetails(ex);
- WriteLine("======================================");
- }
-
- public void Exception(string message, Exception ex)
- {
- WriteLine("============ Error Detail ============");
- WriteLine("Error: {0}", message);
- LogExceptionDetails(ex);
- WriteLine("======================================");
- }
-
- public void Finished(List originalVersions, long currentVersion)
- {
- WriteLine("Migrated to version {0}", currentVersion);
- }
-
- public void Log(string format, params object[] args)
- {
- WriteLine(format, args);
- }
-
- public void Warn(string format, params object[] args)
- {
- Write("Warning! : ");
- WriteLine(format, args);
- }
-
- public void Trace(string format, params object[] args)
- {
- if (_trace)
- {
- Log(format, args);
- }
- }
-
- public void Started(long currentVersion, long finalVersion)
- {
- WriteLine("Current version : {0}. Target version : {1}", currentVersion, finalVersion);
- }
-
- void LogExceptionDetails(Exception ex)
- {
- WriteLine("{0}", ex.Message);
- WriteLine("{0}", ex.StackTrace);
- Exception iex = ex.InnerException;
- while (iex != null)
- {
- WriteLine("Caused by: {0}", iex);
- WriteLine("{0}", ex.StackTrace);
- iex = iex.InnerException;
- }
- }
-
- public void Finished(long originalVersion, long currentVersion)
- {
- WriteLine("Migrated to version {0}", currentVersion);
- }
-
- void Write(string message, params object[] args)
- {
- foreach (ILogWriter writer in _writers)
- {
- writer.Write(message, args);
- }
- }
-
- void WriteLine(string message, params object[] args)
- {
- foreach (ILogWriter writer in _writers)
- {
- writer.WriteLine(message, args);
- }
- }
-
- public static ILogger ConsoleLogger()
- {
- return new Logger(false, new ConsoleWriter());
- }
-
- string LatestVersion(List versions)
- {
- if (versions.Count > 0)
- {
- return versions[versions.Count - 1].ToString();
- }
- return "No migrations applied yet!";
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/Loggers/SqlScriptFileLogger.cs b/src/Migrator.Framework/Loggers/SqlScriptFileLogger.cs
deleted file mode 100644
index fab28946..00000000
--- a/src/Migrator.Framework/Loggers/SqlScriptFileLogger.cs
+++ /dev/null
@@ -1,93 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-
-namespace Migrator.Framework.Loggers
-{
- public class SqlScriptFileLogger : ILogger, IDisposable
- {
- readonly ILogger _innerLogger;
- TextWriter _streamWriter;
-
- public SqlScriptFileLogger(ILogger logger, TextWriter streamWriter)
- {
- _innerLogger = logger;
- _streamWriter = streamWriter;
- }
-
- #region IDisposable Members
-
- public void Dispose()
- {
- if (_streamWriter != null)
- {
- _streamWriter.Dispose();
- _streamWriter = null;
- }
- }
-
- #endregion
-
- public void Log(string format, params object[] args)
- {
- _innerLogger.Log(format, args);
- }
-
- public void Warn(string format, params object[] args)
- {
- _innerLogger.Warn(format, args);
- }
-
- public void Trace(string format, params object[] args)
- {
- _innerLogger.Trace(format, args);
- }
-
- public void ApplyingDBChange(string sql)
- {
- _innerLogger.ApplyingDBChange(sql);
- _streamWriter.WriteLine(sql);
- }
-
- public void Started(List appliedVersions, long finalVersion)
- {
- _innerLogger.Started(appliedVersions, finalVersion);
- }
-
- public void MigrateUp(long version, string migrationName)
- {
- _innerLogger.MigrateUp(version, migrationName);
- }
-
- public void MigrateDown(long version, string migrationName)
- {
- _innerLogger.MigrateDown(version, migrationName);
- }
-
- public void Skipping(long version)
- {
- _innerLogger.Skipping(version);
- }
-
- public void RollingBack(long originalVersion)
- {
- _innerLogger.RollingBack(originalVersion);
- }
-
- public void Exception(long version, string migrationName, Exception ex)
- {
- _innerLogger.Exception(version, migrationName, ex);
- }
-
- public void Exception(string message, Exception ex)
- {
- _innerLogger.Exception(message, ex);
- }
-
- public void Finished(List appliedVersions, long currentVersion)
- {
- _innerLogger.Finished(appliedVersions, currentVersion);
- _streamWriter.Close();
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/Maximums.cs b/src/Migrator.Framework/Maximums.cs
deleted file mode 100644
index 17af8a6a..00000000
--- a/src/Migrator.Framework/Maximums.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace Migrator.Framework
-{
- public static class Maximums
- {
- public const int NTextLength = 1073741823;
- public const int BlobLength = 2147483647;
- }
-}
diff --git a/src/Migrator.Framework/Migration.cs b/src/Migrator.Framework/Migration.cs
deleted file mode 100644
index ca89eaa7..00000000
--- a/src/Migrator.Framework/Migration.cs
+++ /dev/null
@@ -1,113 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-namespace Migrator.Framework
-{
- ///
- /// A migration is a group of transformation applied to the database schema
- /// (or sometimes data) to port the database from one version to another.
- /// The Up() method must apply the modifications (eg.: create a table)
- /// and the Down() method must revert, or rollback the modifications
- /// (eg.: delete a table).
- ///
- /// Each migration must be decorated with the [Migration(0)] attribute.
- /// Each migration number (0) must be unique, or else a
- /// DuplicatedVersionException will be trown.
- ///
- ///
- /// All migrations are executed inside a transaction. If an exception is
- /// thrown, the transaction will be rolledback and transformations wont be
- /// applied.
- ///
- ///
- /// It is best to keep a limited number of transformation inside a migration
- /// so you can easely move from one version of to another with fine grain
- /// modifications.
- /// You should give meaningful name to the migration class and prepend the
- /// migration number to the filename so they keep ordered, eg.:
- /// 002_CreateTableTest.cs.
- ///
- ///
- /// Use the Database property to apply transformation and the
- /// Logger property to output informations in the console (or other).
- /// For more details on transformations see
- /// ITransformationProvider.
- ///
- ///
- ///
- /// The following migration creates a new Customer table.
- /// (File 003_AddCustomerTable.cs)
- ///
- /// [Migration(3)]
- /// public class AddCustomerTable : Migration
- /// {
- /// public override void Up()
- /// {
- /// Database.AddTable("Customer",
- /// new Column("Name", typeof(string), 50),
- /// new Column("Address", typeof(string), 100)
- /// );
- /// }
- /// public override void Down()
- /// {
- /// Database.RemoveTable("Customer");
- /// }
- /// }
- ///
- ///
- public abstract class Migration : IMigration
- {
- public string Name
- {
- get { return StringUtils.ToHumanName(GetType().Name); }
- }
-
- ///
- /// Defines tranformations to port the database to the current version.
- ///
- public abstract void Up();
-
- ///
- /// This is run after the Up transaction has been committed
- ///
- public virtual void AfterUp()
- {
- }
-
- ///
- /// Defines transformations to revert things done in Up.
- ///
- public abstract void Down();
-
- ///
- /// This is run after the Down transaction has been committed
- ///
- public virtual void AfterDown()
- {
- }
-
- ///
- /// Represents the database.
- /// .
- ///
- /// Migration.Framework.ITransformationProvider
- public ITransformationProvider Database { get; set; }
-
- ///
- /// This gets called once on the first migration object.
- ///
- public virtual void InitializeOnce(string[] args)
- {
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/MigrationAttribute.cs b/src/Migrator.Framework/MigrationAttribute.cs
deleted file mode 100644
index fc149678..00000000
--- a/src/Migrator.Framework/MigrationAttribute.cs
+++ /dev/null
@@ -1,59 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-using System;
-
-namespace Migrator.Framework
-{
- ///
- /// Describe a migration
- ///
- public class MigrationAttribute : Attribute
- {
- private long _version;
- private bool _ignore = false;
-
- public string Scope { get; set; }
-
- ///
- /// Describe the migration
- ///
- /// The unique version of the migration.
- public MigrationAttribute(long version)
- {
- Version = version;
- }
- public MigrationAttribute(int year, int month, int day, int hour, int minute,int second)
- {
- var combined = String.Format("{0:D4}{1:D2}{2:D2}{3:D2}{4:D2}{5:D2}", year, month, day, hour, minute,second);
- Version = long.Parse(combined);
- }
- ///
- /// The version reflected by the migration
- ///
- public long Version
- {
- get { return _version; }
- private set { _version = value; }
- }
-
- ///
- /// Set to true to ignore this migration.
- ///
- public bool Ignore
- {
- get { return _ignore; }
- set { _ignore = value; }
- }
- }
-}
diff --git a/src/Migrator.Framework/MigrationException.cs b/src/Migrator.Framework/MigrationException.cs
deleted file mode 100644
index 395ca98e..00000000
--- a/src/Migrator.Framework/MigrationException.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-using System;
-
-namespace Migrator.Framework
-{
- ///
- /// Base class for migration errors.
- ///
- public class MigrationException : Exception
- {
- public MigrationException(string message)
- : base(message)
- {
- }
-
- public MigrationException(string message, Exception cause)
- : base(message, cause)
- {
- }
-
- public MigrationException(string migration, int version, Exception innerException)
- : base(String.Format("Exception in migration {0} (#{1})", migration, version), innerException)
- {
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/MigratorDotNet.snk b/src/Migrator.Framework/MigratorDotNet.snk
deleted file mode 100644
index 5032d709..00000000
Binary files a/src/Migrator.Framework/MigratorDotNet.snk and /dev/null differ
diff --git a/src/Migrator.Framework/SchemaBuilder/AddColumnExpression.cs b/src/Migrator.Framework/SchemaBuilder/AddColumnExpression.cs
deleted file mode 100644
index 02d3f049..00000000
--- a/src/Migrator.Framework/SchemaBuilder/AddColumnExpression.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-namespace Migrator.Framework.SchemaBuilder
-{
- public class AddColumnExpression : ISchemaBuilderExpression
- {
- readonly IFluentColumn _column;
- readonly string _toTable;
-
- public AddColumnExpression(string toTable, IFluentColumn column)
- {
- _column = column;
- _toTable = toTable;
- }
-
- public void Create(ITransformationProvider provider)
- {
- provider.AddColumn(_toTable, _column.Name, _column.Type, _column.Size, _column.ColumnProperty, _column.DefaultValue);
-
- if (_column.ForeignKey != null)
- {
- provider.AddForeignKey(
- "FK_" + _toTable + "_" + _column.Name + "_" + _column.ForeignKey.PrimaryTable + "_" +
- _column.ForeignKey.PrimaryKey,
- _toTable, _column.Name, _column.ForeignKey.PrimaryTable, _column.ForeignKey.PrimaryKey, _column.Constraint);
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/SchemaBuilder/FluentColumn.cs b/src/Migrator.Framework/SchemaBuilder/FluentColumn.cs
deleted file mode 100644
index e0ea1c6c..00000000
--- a/src/Migrator.Framework/SchemaBuilder/FluentColumn.cs
+++ /dev/null
@@ -1,71 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-using System.Data;
-
-namespace Migrator.Framework.SchemaBuilder
-{
- public class FluentColumn : IFluentColumn
- {
- readonly Column _inner;
-
- public FluentColumn(string columnName)
- {
- _inner = new Column(columnName);
- }
-
- public ColumnProperty ColumnProperty
- {
- get { return _inner.ColumnProperty; }
- set { _inner.ColumnProperty = value; }
- }
-
- public string Name
- {
- get { return _inner.Name; }
- set { _inner.Name = value; }
- }
-
- public DbType Type
- {
- get { return _inner.Type; }
- set { _inner.Type = value; }
- }
-
- public int Size
- {
- get { return _inner.Size; }
- set { _inner.Size = value; }
- }
-
- public bool IsIdentity
- {
- get { return _inner.IsIdentity; }
- }
-
- public bool IsPrimaryKey
- {
- get { return _inner.IsPrimaryKey; }
- }
-
- public object DefaultValue
- {
- get { return _inner.DefaultValue; }
- set { _inner.DefaultValue = value; }
- }
-
- public ForeignKeyConstraintType Constraint { get; set; }
-
- public ForeignKey ForeignKey { get; set; }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/SchemaBuilder/ForeignKey.cs b/src/Migrator.Framework/SchemaBuilder/ForeignKey.cs
deleted file mode 100644
index 793f2ec6..00000000
--- a/src/Migrator.Framework/SchemaBuilder/ForeignKey.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-namespace Migrator.Framework.SchemaBuilder
-{
- public class ForeignKey
- {
- public ForeignKey(string primaryTable, string primaryKey)
- {
- PrimaryTable = primaryTable;
- PrimaryKey = primaryKey;
- }
-
- public string PrimaryTable { get; set; }
-
- public string PrimaryKey { get; set; }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/SchemaBuilder/IColumnOptions.cs b/src/Migrator.Framework/SchemaBuilder/IColumnOptions.cs
deleted file mode 100644
index 8fd8cb32..00000000
--- a/src/Migrator.Framework/SchemaBuilder/IColumnOptions.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using System.Data;
-
-namespace Migrator.Framework.SchemaBuilder
-{
- public interface IColumnOptions
- {
- SchemaBuilder OfType(DbType dbType);
-
- SchemaBuilder WithSize(int size);
-
- IForeignKeyOptions AsForeignKey();
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/SchemaBuilder/SchemaBuilder.cs b/src/Migrator.Framework/SchemaBuilder/SchemaBuilder.cs
deleted file mode 100644
index 5fd35ad1..00000000
--- a/src/Migrator.Framework/SchemaBuilder/SchemaBuilder.cs
+++ /dev/null
@@ -1,169 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-using System;
-using System.Collections.Generic;
-using System.Data;
-
-namespace Migrator.Framework.SchemaBuilder
-{
- public class SchemaBuilder : IColumnOptions, IForeignKeyOptions, IDeleteTableOptions
- {
- readonly IList _exprs;
- IFluentColumn _currentColumn;
- string _currentTable;
-
- public SchemaBuilder()
- {
- _exprs = new List();
- }
-
- public IEnumerable Expressions
- {
- get { return _exprs; }
- }
-
- public SchemaBuilder OfType(DbType columnType)
- {
- _currentColumn.Type = columnType;
-
- return this;
- }
-
- public SchemaBuilder WithSize(int size)
- {
- if (size == 0)
- throw new ArgumentNullException("size", "Size must be greater than zero");
-
- _currentColumn.Size = size;
-
- return this;
- }
-
- public IForeignKeyOptions AsForeignKey()
- {
- _currentColumn.ColumnProperty = ColumnProperty.ForeignKey;
-
- return this;
- }
-
- ///
- /// Adds a Table to be created to the Schema
- ///
- /// Table name to be created
- /// SchemaBuilder for chaining
- public SchemaBuilder AddTable(string name)
- {
- if (string.IsNullOrEmpty(name))
- throw new ArgumentNullException("name");
-
- _exprs.Add(new AddTableExpression(name));
- _currentTable = name;
-
- return this;
- }
-
- public IDeleteTableOptions DeleteTable(string name)
- {
- if (string.IsNullOrEmpty(name))
- throw new ArgumentNullException("name");
- _currentTable = "";
- _currentColumn = null;
-
- _exprs.Add(new DeleteTableExpression(name));
-
- return this;
- }
-
- ///
- /// Reference an existing table.
- ///
- /// Table to reference
- /// SchemaBuilder for chaining
- public SchemaBuilder WithTable(string name)
- {
- if (string.IsNullOrEmpty(name))
- throw new ArgumentNullException("name");
-
- _currentTable = name;
-
- return this;
- }
-
- public SchemaBuilder ReferencedTo(string primaryKeyTable, string primaryKeyColumn)
- {
- _currentColumn.Constraint = ForeignKeyConstraintType.NoAction;
- _currentColumn.ForeignKey = new ForeignKey(primaryKeyTable, primaryKeyColumn);
- return this;
- }
-
- ///
- /// Reference an existing table.
- ///
- /// Table to reference
- /// SchemaBuilder for chaining
- public SchemaBuilder RenameTable(string newName)
- {
- if (string.IsNullOrEmpty(newName))
- throw new ArgumentNullException("newName");
-
- _exprs.Add(new RenameTableExpression(_currentTable, newName));
- _currentTable = newName;
-
- return this;
- }
-
- ///
- /// Adds a Column to be created
- ///
- /// Column name to be added
- /// IColumnOptions to restrict chaining
- public IColumnOptions AddColumn(string name)
- {
- if (string.IsNullOrEmpty(name))
- throw new ArgumentNullException("name");
- if (string.IsNullOrEmpty(_currentTable))
- throw new ArgumentException("missing referenced table");
-
- IFluentColumn column = new FluentColumn(name);
- _currentColumn = column;
-
- _exprs.Add(new AddColumnExpression(_currentTable, column));
- return this;
- }
-
- public SchemaBuilder WithProperty(ColumnProperty columnProperty)
- {
- _currentColumn.ColumnProperty = columnProperty;
-
- return this;
- }
-
- public SchemaBuilder WithDefaultValue(object defaultValue)
- {
- if (defaultValue == null)
- throw new ArgumentNullException("defaultValue", "DefaultValue cannot be null or empty");
-
- _currentColumn.DefaultValue = defaultValue;
-
- return this;
- }
-
- public SchemaBuilder WithConstraint(ForeignKeyConstraintType action)
- {
- _currentColumn.Constraint = action;
-
- return this;
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/StringUtils.cs b/src/Migrator.Framework/StringUtils.cs
deleted file mode 100644
index 07a6dd84..00000000
--- a/src/Migrator.Framework/StringUtils.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-using System.Text;
-using System.Text.RegularExpressions;
-
-namespace Migrator.Framework
-{
- public class StringUtils
- {
- ///
- /// Convert a classname to something more readable.
- /// ex.: CreateATable => Create a table
- ///
- ///
- ///
- public static string ToHumanName(string className)
- {
- string name = Regex.Replace(className, "^[_0-9]*|[_0-9]*$", "");
-
- name = Regex.Replace(name, "([A-Z])", " $1").Substring(1);
-
- return name.Substring(0, 1).ToUpper() + name.Substring(1).ToLower();
- }
-
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- public static string ReplaceOnce(string template, string placeholder, string replacement)
- {
- int loc = template.IndexOf(placeholder);
- if (loc < 0)
- {
- return template;
- }
- else
- {
- return new StringBuilder(template.Substring(0, loc))
- .Append(replacement)
- .Append(template.Substring(loc + placeholder.Length))
- .ToString();
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/Support/Inflector.cs b/src/Migrator.Framework/Support/Inflector.cs
deleted file mode 100644
index 8766edca..00000000
--- a/src/Migrator.Framework/Support/Inflector.cs
+++ /dev/null
@@ -1,167 +0,0 @@
-using System.Collections;
-using System.Text.RegularExpressions;
-
-namespace Migrator.Framework.Support
-{
- public class Inflector
- {
- private static readonly ArrayList plurals = new ArrayList();
- private static readonly ArrayList singulars = new ArrayList();
- private static readonly ArrayList uncountables = new ArrayList();
-
- private Inflector()
- {
- }
-
- static Inflector()
- {
- AddPlural("$", "s");
- AddPlural("s$", "s");
- AddPlural("(ax|test)is$", "$1es");
- AddPlural("(octop|vir)us$", "$1i");
- AddPlural("(alias|status)$", "$1es");
- AddPlural("(bu)s$", "$1ses");
- AddPlural("(buffal|tomat)o$", "$1oes");
- AddPlural("([ti])um$", "$1a");
- AddPlural("sis$", "ses");
- AddPlural("(?:([^f])fe|([lr])f)$", "$1$2ves");
- AddPlural("(hive)$", "$1s");
- AddPlural("([^aeiouy]|qu)y$", "$1ies");
- AddPlural("(x|ch|ss|sh)$", "$1es");
- AddPlural("(matr|vert|ind)ix|ex$", "$1ices");
- AddPlural("([m|l])ouse$", "$1ice");
- AddPlural("^(ox)$", "$1en");
- AddPlural("(quiz)$", "$1zes");
- AddSingular("s$", "");
- AddSingular("(n)ews$", "$1ews");
- AddSingular("([ti])a$", "$1um");
- AddSingular("((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$", "$1$2sis");
- AddSingular("(^analy)ses$", "$1sis");
- AddSingular("([^f])ves$", "$1fe");
- AddSingular("(hive)s$", "$1");
- AddSingular("(tive)s$", "$1");
- AddSingular("([lr])ves$", "$1f");
- AddSingular("([^aeiouy]|qu)ies$", "$1y");
- AddSingular("(s)eries$", "$1eries");
- AddSingular("(m)ovies$", "$1ovie");
- AddSingular("(x|ch|ss|sh)es$", "$1");
- AddSingular("([m|l])ice$", "$1ouse");
- AddSingular("(bus)es$", "$1");
- AddSingular("(o)es$", "$1");
- AddSingular("(shoe)s$", "$1");
- AddSingular("(cris|ax|test)es$", "$1is");
- AddSingular("(octop|vir)i$", "$1us");
- AddSingular("(alias|status)es$", "$1");
- AddSingular("^(ox)en", "$1");
- AddSingular("(vert|ind)ices$", "$1ex");
- AddSingular("(matr)ices$", "$1ix");
- AddSingular("(quiz)zes$", "$1");
- AddIrregular("person", "people");
- AddIrregular("man", "men");
- AddIrregular("child", "children");
- AddIrregular("sex", "sexes");
- AddIrregular("move", "moves");
- AddUncountable("equipment");
- AddUncountable("information");
- AddUncountable("rice");
- AddUncountable("money");
- AddUncountable("species");
- AddUncountable("series");
- AddUncountable("fish");
- AddUncountable("sheep");
- }
-
- private class Rule
- {
- private readonly Regex regex;
- private readonly string replacement;
-
- public Rule(string pattern, string replacement)
- {
- regex = new Regex(pattern, RegexOptions.IgnoreCase);
- this.replacement = replacement;
- }
-
- public string Apply(string word)
- {
- if (!regex.IsMatch(word))
- {
- return null;
- }
-
- return regex.Replace(word, replacement);
- }
- }
-
- ///
- /// Return the plural of a word.
- ///
- /// The singular form
- /// The plural form of
- public static string Pluralize(string word)
- {
- return ApplyRules(plurals, word);
- }
-
- ///
- /// Return the singular of a word.
- ///
- /// The plural form
- /// The singular form of
- public static string Singularize(string word)
- {
- return ApplyRules(singulars, word);
- }
-
- ///
- /// Capitalizes a word.
- ///
- /// The word to be capitalized.
- /// capitalized.
- public static string Capitalize(string word)
- {
- return word.Substring(0, 1).ToUpper() + word.Substring(1).ToLower();
- }
-
- private static void AddIrregular(string singular, string plural)
- {
- AddPlural("(" + singular[0] + ")" + singular.Substring(1) + "$", "$1" + plural.Substring(1));
- AddSingular("(" + plural[0] + ")" + plural.Substring(1) + "$", "$1" + singular.Substring(1));
- }
-
- private static void AddUncountable(string word)
- {
- uncountables.Add(word.ToLower());
- }
-
- private static void AddPlural(string rule, string replacement)
- {
- plurals.Add(new Rule(rule, replacement));
- }
-
- private static void AddSingular(string rule, string replacement)
- {
- singulars.Add(new Rule(rule, replacement));
- }
-
- private static string ApplyRules(IList rules, string word)
- {
- string result = word;
-
- if (!uncountables.Contains(word.ToLower()))
- {
- for (int i = rules.Count - 1; i >= 0; i--)
- {
- Rule rule = (Rule)rules[i];
-
- if ((result = rule.Apply(word)) != null)
- {
- break;
- }
- }
- }
-
- return result;
- }
- }
-}
diff --git a/src/Migrator.Framework/Support/TransformationProviderUtility.cs b/src/Migrator.Framework/Support/TransformationProviderUtility.cs
deleted file mode 100644
index 10e0a907..00000000
--- a/src/Migrator.Framework/Support/TransformationProviderUtility.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-using System;
-using System.Linq;
-using System.Reflection;
-
-namespace Migrator.Framework.Support
-{
- public static class TransformationProviderUtility
- {
- public const int MaxLengthForForeignKeyInOracle = 30;
- //static readonly ILog log = LogManager.GetLogger(typeof (TransformationProviderUtility));
- static readonly string[] CommonWords = new[] {"Test"};
-
- public static string CreateForeignKeyName(string tableName, string foreignKeyTableName)
- {
- string fkName = string.Format("FK_{0}_{1}", tableName, foreignKeyTableName);
-
- return AdjustNameToSize(fkName, MaxLengthForForeignKeyInOracle, true);
- }
-
- public static string AdjustNameToSize(string name, int totalCharacters, bool removeCommmonWords)
- {
- string adjustedName = name;
-
- if (adjustedName.Length > totalCharacters)
- {
- if (removeCommmonWords)
- {
- adjustedName = RemoveCommonWords(adjustedName);
- }
- }
-
- if (adjustedName.Length > totalCharacters) adjustedName = adjustedName.Substring(0, totalCharacters);
-
- if (name != adjustedName)
- {
- //log.WarnFormat("Name has been truncated from: {0} to: {1}", name, adjustedName);
- }
-
- return adjustedName;
- }
-
- static string RemoveCommonWords(string adjustedName)
- {
- foreach (var word in CommonWords)
- {
- if (adjustedName.Contains(word))
- {
- adjustedName = adjustedName.Replace(word, string.Empty);
- }
- }
- return adjustedName;
- }
-
- public static string FormatTableName(string schema, string tableName)
- {
- return string.IsNullOrEmpty(schema) ? tableName : string.Format("{0}.{1}", schema, tableName);
- }
-
- public static string GetQualifiedResourcePath(Assembly assembly, string resourceName)
- {
- var resources = assembly.GetManifestResourceNames();
-
- //resource full name is in format `namespace.resourceName`
- var sqlScriptParts = resourceName.Split('.').Reverse().ToArray();
- Func isNameMatch = x => x.Split('.').Reverse().Take(sqlScriptParts.Length).SequenceEqual(sqlScriptParts, StringComparer.InvariantCultureIgnoreCase);
-
- string result = null;
- var foundResources = resources.Where(isNameMatch).ToArray();
-
- if (foundResources.Length == 0) throw new InvalidOperationException(string.Format("Could not find resource named {0} in assembly {1}", resourceName, assembly.FullName));
-
- if (foundResources.Length > 1) throw new InvalidOperationException(string.Format(@"Could not find unique resource named {0} in assembly {1}.Possible candidates are: {2}", resourceName, assembly.FullName, string.Join(Environment.NewLine + "\t", foundResources)));
-
- return foundResources[0];
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Framework/Unique.cs b/src/Migrator.Framework/Unique.cs
deleted file mode 100644
index 0930acc1..00000000
--- a/src/Migrator.Framework/Unique.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace Migrator.Framework
-{
- public class Unique : IDbField
- {
- public string Name { get; set; }
- public string[] KeyColumns { get; set; }
- }
-}
diff --git a/src/Migrator.Framework/ViewField.cs b/src/Migrator.Framework/ViewField.cs
deleted file mode 100644
index 9b848ac5..00000000
--- a/src/Migrator.Framework/ViewField.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-using System.Data;
-
-namespace Migrator.Framework
-{
- ///
- /// Represents a table column.
- ///
- public class ViewField : IViewField
- {
- public ViewField(string ColumnName)
- {
- this.ColumnName = ColumnName;
- }
-
- public ViewField(string ColumnName, string TableName, string KeyColumnName, string ParentTableName, string ParentKeyColumnName)
- {
- this.ColumnName = ColumnName;
- this.TableName = TableName;
- this.KeyColumnName = KeyColumnName;
- this.ParentTableName = ParentTableName;
- this.ParentKeyColumnName = ParentKeyColumnName;
- }
-
- public string TableName { get; set; }
- public string ColumnName { get; set; }
- public string KeyColumnName { get; set; }
- public string ParentTableName { get; set; }
- public string ParentKeyColumnName { get; set; }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.MSBuild/Logger/TaskLogger.cs b/src/Migrator.MSBuild/Logger/TaskLogger.cs
deleted file mode 100644
index d6f13081..00000000
--- a/src/Migrator.MSBuild/Logger/TaskLogger.cs
+++ /dev/null
@@ -1,129 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-using System;
-using System.Collections.Generic;
-using Microsoft.Build.Framework;
-using Microsoft.Build.Utilities;
-using ILogger = Migrator.Framework.ILogger;
-
-namespace Migrator.MSBuild.Logger
-{
- ///
- /// MSBuild task logger for the migration mediator
- ///
- public class TaskLogger : ILogger
- {
- readonly Task _task;
-
- public TaskLogger(Task task)
- {
- _task = task;
- }
-
- public void Started(List currentVersions, long finalVersion)
- {
- LogInfo("Latest version applied : {0}. Target version : {1}", LatestVersion(currentVersions), finalVersion);
- }
-
- public void MigrateUp(long version, string migrationName)
- {
- LogInfo("Applying {0}: {1}", version.ToString(), migrationName);
- }
-
- public void MigrateDown(long version, string migrationName)
- {
- LogInfo("Removing {0}: {1}", version.ToString(), migrationName);
- }
-
- public void Skipping(long version)
- {
- MigrateUp(version, "");
- }
-
- public void RollingBack(long originalVersion)
- {
- LogInfo("Rolling back to migration {0}", originalVersion);
- }
-
- public void ApplyingDBChange(string sql)
- {
- Log(sql);
- }
-
- public void Exception(long version, string migrationName, Exception ex)
- {
- LogInfo("============ Error Detail ============");
- LogInfo("Error in migration: {0}", version);
- _task.Log.LogErrorFromException(ex, true);
- LogInfo("======================================");
- }
-
- public void Exception(string message, Exception ex)
- {
- LogInfo("============ Error Detail ============");
- LogInfo("Error: {0}", message);
- _task.Log.LogErrorFromException(ex, true);
- LogInfo("======================================");
- }
-
- public void Finished(List originalVersion, long currentVersion)
- {
- LogInfo("Migrated to version {0}", currentVersion);
- }
-
- public void Log(string format, params object[] args)
- {
- LogInfo(format, args);
- }
-
- public void Warn(string format, params object[] args)
- {
- _task.Log.LogWarning("[Warning] {0}", String.Format(format, args));
- }
-
- public void Trace(string format, params object[] args)
- {
- _task.Log.LogMessage(MessageImportance.Low, format, args);
- }
-
- protected void LogInfo(string format, params object[] args)
- {
- _task.Log.LogMessage(format, args);
- }
-
- protected void LogError(string format, params object[] args)
- {
- _task.Log.LogError(format, args);
- }
-
- public void Started(long currentVersion, long finalVersion)
- {
- LogInfo("Current version : {0}", currentVersion);
- }
-
- public void Finished(long originalVersion, long currentVersion)
- {
- LogInfo("Migrated to version {0}", currentVersion);
- }
-
- string LatestVersion(List versions)
- {
- if (versions.Count > 0)
- {
- return versions[versions.Count - 1].ToString();
- }
- return "No migrations applied yet!";
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.MSBuild/MigrateTask.cs b/src/Migrator.MSBuild/MigrateTask.cs
deleted file mode 100644
index e45cab37..00000000
--- a/src/Migrator.MSBuild/MigrateTask.cs
+++ /dev/null
@@ -1,157 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-using System;
-using System.IO;
-using System.Reflection;
-using Microsoft.Build.Framework;
-using Microsoft.Build.Utilities;
-using Migrator.Compile;
-using Migrator.Framework.Loggers;
-using Migrator.MSBuild.Logger;
-using Migrator.Providers;
-
-namespace Migrator.MSBuild
-{
- ///
- /// Runs migrations on a database
- ///
- ///
- /// To script the changes applied to the database via the migrations into a file, set the
- /// flag and provide a file to write the changes to via the setting.
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- public class Migrate : Task
- {
- string _scriptFile;
- long _to = -1; // To last revision
-
- [Required]
- public ProviderTypes Provider { set; get; }
-
- public string DefaultSchema { get; set; }
-
- [Required]
- public string ConnectionString { set; get; }
-
- ///
- /// The paths to the assemblies that contain your migrations.
- /// This will generally just be a single item.
- ///
- public ITaskItem[] Migrations { set; get; }
-
- ///
- /// The paths to the directory that contains your migrations.
- /// This will generally just be a single item.
- ///
- public string Directory { set; get; }
-
- public string Language { set; get; }
-
- public long To
- {
- set { _to = value; }
- get { return _to; }
- }
-
- public bool Trace { set; get; }
-
- public bool DryRun { set; get; }
-
- ///
- /// Gets value indicating whether to script the changes made to the database
- /// to the file indicated by .
- ///
- /// true if the changes should be scripted to a file; otherwise, false.
- public bool ScriptChanges
- {
- get { return !String.IsNullOrEmpty(_scriptFile); }
- }
-
- ///
- /// Gets or sets the script file that will contain the Sql statements
- /// that are executed as part of the migrations.
- ///
- public string ScriptFile
- {
- get { return _scriptFile; }
- set { _scriptFile = value; }
- }
-
- public override bool Execute()
- {
- if (! String.IsNullOrEmpty(Directory))
- {
- var engine = new ScriptEngine(Language, null);
- Execute(engine.Compile(Directory));
- }
-
- if (null != Migrations)
- {
- foreach (ITaskItem assembly in Migrations)
- {
- Assembly asm = Assembly.LoadFrom(assembly.GetMetadata("FullPath"));
- Execute(asm);
- }
- }
-
- return true;
- }
-
- void Execute(Assembly asm)
- {
- var mig = new Migrator(Provider, ConnectionString, DefaultSchema, asm, Trace, new TaskLogger(this));
- mig.DryRun = DryRun;
- if (ScriptChanges)
- {
- using (var writer = new StreamWriter(ScriptFile))
- {
- mig.Logger = new SqlScriptFileLogger(mig.Logger, writer);
- RunMigration(mig);
- }
- }
- else
- {
- RunMigration(mig);
- }
- }
-
- void RunMigration(Migrator mig)
- {
- if (mig.DryRun)
- mig.Logger.Log("********** Dry run! Not actually applying changes. **********");
-
- if (_to == -1)
- mig.MigrateToLastVersion();
- else
- mig.MigrateTo(_to);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.MSBuild/Migrator.MSBuild-vs2008.csproj b/src/Migrator.MSBuild/Migrator.MSBuild-vs2008.csproj
deleted file mode 100644
index 7de5cb93..00000000
--- a/src/Migrator.MSBuild/Migrator.MSBuild-vs2008.csproj
+++ /dev/null
@@ -1,69 +0,0 @@
-
-
- Debug
- AnyCPU
- 9.0.30729
- 2.0
- {A145FFA9-5FE6-4636-93B8-0C110D132BF3}
- Library
- Migrator.MSBuild
- Migrator.MSBuild
-
-
- 2.0
-
-
- true
- MigratorDotNet.snk
-
-
- true
- full
- false
- bin\Debug\
- DEBUG;TRACE
- prompt
- 4
-
-
- pdbonly
- true
- bin\Release\
- TRACE
- prompt
- 4
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {1FEE70A4-AAD7-4C60-BE60-3F7DC03A8C4D}
- Migrator-vs2008
-
-
- {5270F048-E580-486C-B14C-E5B9F6E539D4}
- Migrator.Framework-vs2008
-
-
-
-
-
\ No newline at end of file
diff --git a/src/Migrator.MSBuild/Migrator.MSBuild-vs2010.csproj b/src/Migrator.MSBuild/Migrator.MSBuild-vs2010.csproj
deleted file mode 100644
index 2475b022..00000000
--- a/src/Migrator.MSBuild/Migrator.MSBuild-vs2010.csproj
+++ /dev/null
@@ -1,110 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 9.0.30729
- 2.0
- {A145FFA9-5FE6-4636-93B8-0C110D132BF3}
- Library
- Migrator.MSBuild
- Migrator.MSBuild
-
-
- 3.5
-
-
- true
- MigratorDotNet.snk
- v4.0
- publish\
- true
- Disk
- false
- Foreground
- 7
- Days
- false
- false
- true
- 0
- 1.0.0.%2a
- false
- false
- true
-
-
-
- true
- full
- false
- bin\Debug\
- DEBUG;TRACE
- prompt
- 4
- AllRules.ruleset
-
-
- pdbonly
- true
- bin\Release\
- TRACE
- prompt
- 4
- AllRules.ruleset
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {d58c68e4-d789-40f7-9078-c9f587d4363c}
- DotNetProjects.Migrator.Providers
-
-
- {1FEE70A4-AAD7-4C60-BE60-3F7DC03A8C4D}
- DotNetProjects.Migrator
-
-
- {5270F048-E580-486C-B14C-E5B9F6E539D4}
- DotNetProjects.Migrator.Framework
-
-
-
-
- False
- .NET Framework 3.5 SP1 Client Profile
- false
-
-
- False
- .NET Framework 3.5 SP1
- true
-
-
- False
- Windows Installer 3.1
- true
-
-
-
-
-
\ No newline at end of file
diff --git a/src/Migrator.MSBuild/Migrator.Targets b/src/Migrator.MSBuild/Migrator.Targets
deleted file mode 100644
index 46d9de28..00000000
--- a/src/Migrator.MSBuild/Migrator.Targets
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
- $(MSBuildExtensionsPath)\MigratorTasks
- $(MigratorTasksPath)\Migrator.MSBuild.dll
-
-
-
-
diff --git a/src/Migrator.MSBuild/MigratorDotNet.snk b/src/Migrator.MSBuild/MigratorDotNet.snk
deleted file mode 100644
index 5032d709..00000000
Binary files a/src/Migrator.MSBuild/MigratorDotNet.snk and /dev/null differ
diff --git a/src/Migrator.MSBuild/example-build.proj b/src/Migrator.MSBuild/example-build.proj
deleted file mode 100644
index 0c8afde6..00000000
--- a/src/Migrator.MSBuild/example-build.proj
+++ /dev/null
@@ -1,28 +0,0 @@
-
-
-
- Debug
- bin\$(Configuration)
- src\Migrations.csproj
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/Migrator.NAnt/Loggers/TaskLogger.cs b/src/Migrator.NAnt/Loggers/TaskLogger.cs
deleted file mode 100644
index 779051e3..00000000
--- a/src/Migrator.NAnt/Loggers/TaskLogger.cs
+++ /dev/null
@@ -1,141 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-using System;
-using System.Collections.Generic;
-using Migrator.Framework;
-using NAnt.Core;
-
-namespace Migrator.NAnt.Loggers
-{
- ///
- /// NAnt task logger for the migration mediator
- ///
- public class TaskLogger : ILogger
- {
- readonly Task _task;
-
- public TaskLogger(Task task)
- {
- _task = task;
- }
-
- public void Started(List currentVersions, long finalVersion)
- {
- LogInfo("Latest version applied : {0}. Target version : {1}", LatestVersion(currentVersions), finalVersion);
- }
-
- public void MigrateUp(long version, string migrationName)
- {
- LogInfo("Applying {0}: {1}", version.ToString(), migrationName);
- }
-
- public void MigrateDown(long version, string migrationName)
- {
- LogInfo("Removing {0}: {1}", version.ToString(), migrationName);
- }
-
- public void Skipping(long version)
- {
- MigrateUp(version, "");
- }
-
- public void RollingBack(long originalVersion)
- {
- LogInfo("Rolling back to migration {0}", originalVersion);
- }
-
- public void ApplyingDBChange(string sql)
- {
- Log(sql);
- }
-
- public void Exception(long version, string migrationName, Exception ex)
- {
- LogInfo("============ Error Detail ============");
- LogInfo("Error in migration: {0}", version);
- LogExceptionDetails(ex);
- LogInfo("======================================");
- }
-
- public void Exception(string message, Exception ex)
- {
- LogInfo("============ Error Detail ============");
- LogInfo("Error: {0}", message);
- LogExceptionDetails(ex);
- LogInfo("======================================");
- }
-
- public void Finished(List originalVersion, long currentVersion)
- {
- LogInfo("Migrated to version {0}", currentVersion);
- }
-
- public void Log(string format, params object[] args)
- {
- LogInfo(format, args);
- }
-
- public void Warn(string format, params object[] args)
- {
- LogInfo("[Warning] {0}", String.Format(format, args));
- }
-
- public void Trace(string format, params object[] args)
- {
- _task.Log(Level.Debug, format, args);
- }
-
- protected void LogInfo(string format, params object[] args)
- {
- _task.Log(Level.Info, format, args);
- }
-
- protected void LogError(string format, params object[] args)
- {
- _task.Log(Level.Error, format, args);
- }
-
- public void Started(long currentVersion, long finalVersion)
- {
- LogInfo("Current version : {0}", currentVersion);
- }
-
- void LogExceptionDetails(Exception ex)
- {
- LogInfo("{0}", ex.Message);
- LogInfo("{0}", ex.StackTrace);
- Exception iex = ex.InnerException;
- while (iex != null)
- {
- LogInfo("Caused by: {0}", iex);
- LogInfo("{0}", ex.StackTrace);
- iex = iex.InnerException;
- }
- }
-
- public void Finished(long originalVersion, long currentVersion)
- {
- LogInfo("Migrated to version {0}", currentVersion);
- }
-
- string LatestVersion(List versions)
- {
- if (versions.Count > 0)
- {
- return versions[versions.Count - 1].ToString();
- }
- return "No migrations applied yet!";
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.NAnt/MigrateTask.cs b/src/Migrator.NAnt/MigrateTask.cs
deleted file mode 100644
index 21d74d40..00000000
--- a/src/Migrator.NAnt/MigrateTask.cs
+++ /dev/null
@@ -1,147 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-using System;
-using System.IO;
-using System.Reflection;
-using Migrator.Compile;
-using Migrator.Framework.Loggers;
-using Migrator.NAnt.Loggers;
-using Migrator.Providers;
-
-using NAnt.Core;
-using NAnt.Core.Attributes;
-
-namespace Migrator.NAnt
-{
- ///
- /// Runs migrations on a database
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- [TaskName("migrate")]
- public class MigrateTask : Task
- {
- string _scriptFile;
- long _to = -1; // To last revision
-
- [TaskAttribute("defaultschema")]
- public string DefaultSchema { get; set; }
-
- [TaskAttribute("provider", Required = true)]
- public ProviderTypes Provider { set; get; }
-
- [TaskAttribute("connectionstring", Required = true)]
- public string ConnectionString { set; get; }
-
- [TaskAttribute("migrations")]
- public FileInfo MigrationsAssembly { set; get; }
-
- ///
- /// The paths to the directory that contains your migrations.
- /// This will generally just be a single item.
- ///
- [TaskAttribute("directory")]
- public string Directory { set; get; }
-
- [TaskAttribute("language")]
- public string Language { set; get; }
-
- [TaskAttribute("to")]
- public long To
- {
- set { _to = value; }
- get { return _to; }
- }
-
- [TaskAttribute("trace")]
- public bool Trace { set; get; }
-
- [TaskAttribute("dryrun")]
- public bool DryRun { set; get; }
-
- ///
- /// Gets value indicating whether to script the changes made to the database
- /// to the file indicated by .
- ///
- /// true if the changes should be scripted to a file; otherwise, false.
- public bool ScriptChanges
- {
- get { return !String.IsNullOrEmpty(_scriptFile); }
- }
-
- ///
- /// Gets or sets the script file that will contain the Sql statements
- /// that are executed as part of the migrations.
- ///
- [TaskAttribute("scriptFile")]
- public string ScriptFile
- {
- get { return _scriptFile; }
- set { _scriptFile = value; }
- }
-
- protected override void ExecuteTask()
- {
- if (! String.IsNullOrEmpty(Directory))
- {
- var engine = new ScriptEngine(Language, null);
- Execute(engine.Compile(Directory));
- }
-
- if (null != MigrationsAssembly)
- {
- Assembly asm = Assembly.LoadFrom(MigrationsAssembly.FullName);
- Execute(asm);
- }
- }
-
- void Execute(Assembly asm)
- {
- var mig = new Migrator(Provider, ConnectionString, DefaultSchema, asm, Trace, new TaskLogger(this));
- mig.DryRun = DryRun;
- if (ScriptChanges)
- {
- using (var writer = new StreamWriter(ScriptFile))
- {
- mig.Logger = new SqlScriptFileLogger(mig.Logger, writer);
- RunMigration(mig);
- }
- }
- else
- {
- RunMigration(mig);
- }
- }
-
- void RunMigration(Migrator mig)
- {
- if (mig.DryRun)
- mig.Logger.Log("********** Dry run! Not actually applying changes. **********");
-
- if (_to == -1)
- mig.MigrateToLastVersion();
- else
- mig.MigrateTo(_to);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.NAnt/Migrator.NAnt-vs2008.csproj b/src/Migrator.NAnt/Migrator.NAnt-vs2008.csproj
deleted file mode 100644
index 44f4d6f1..00000000
--- a/src/Migrator.NAnt/Migrator.NAnt-vs2008.csproj
+++ /dev/null
@@ -1,71 +0,0 @@
-
-
- Debug
- AnyCPU
- 9.0.30729
- 2.0
- {CDD39DB7-C9C0-4ECA-AD36-1B4D0BF59101}
- Library
- Properties
- Migrator.NAnt
- Migrator.NAnt
-
-
- 2.0
-
-
- false
- MigratorDotNet.snk
-
-
- true
- full
- false
- bin\Migrator.NAnt\Debug\
- DEBUG;TRACE
- prompt
- 4
-
-
- pdbonly
- true
- bin\Migrator.NAnt\Release\
- TRACE
- prompt
- 4
-
-
-
- False
- ..\..\lib\log4net.dll
-
-
-
-
-
- ..\..\lib\NAnt.Core.dll
- False
-
-
-
-
-
-
-
-
-
-
-
- {1FEE70A4-AAD7-4C60-BE60-3F7DC03A8C4D}
- Migrator-vs2008
-
-
- {5270F048-E580-486C-B14C-E5B9F6E539D4}
- Migrator.Framework-vs2008
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/Migrator.NAnt/Migrator.NAnt-vs2010.csproj b/src/Migrator.NAnt/Migrator.NAnt-vs2010.csproj
deleted file mode 100644
index 4fd0cdca..00000000
--- a/src/Migrator.NAnt/Migrator.NAnt-vs2010.csproj
+++ /dev/null
@@ -1,112 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 9.0.30729
- 2.0
- {CDD39DB7-C9C0-4ECA-AD36-1B4D0BF59101}
- Library
- Properties
- Migrator.NAnt
- Migrator.NAnt
-
-
- 3.5
-
-
- false
- MigratorDotNet.snk
- v4.0
- publish\
- true
- Disk
- false
- Foreground
- 7
- Days
- false
- false
- true
- 0
- 1.0.0.%2a
- false
- false
- true
-
-
-
- true
- full
- false
- bin\Migrator.NAnt\Debug\
- DEBUG;TRACE
- prompt
- 4
- AllRules.ruleset
-
-
- pdbonly
- true
- bin\Migrator.NAnt\Release\
- TRACE
- prompt
- 4
- AllRules.ruleset
-
-
-
- False
- ..\..\lib\log4net.dll
-
-
- False
- ..\..\lib\NAnt.Core.dll
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {d58c68e4-d789-40f7-9078-c9f587d4363c}
- DotNetProjects.Migrator.Providers
-
-
- {1FEE70A4-AAD7-4C60-BE60-3F7DC03A8C4D}
- DotNetProjects.Migrator
-
-
- {5270F048-E580-486C-B14C-E5B9F6E539D4}
- DotNetProjects.Migrator.Framework
-
-
-
-
-
-
-
- False
- .NET Framework 3.5 SP1 Client Profile
- false
-
-
- False
- .NET Framework 3.5 SP1
- true
-
-
- False
- Windows Installer 3.1
- true
-
-
-
-
\ No newline at end of file
diff --git a/src/Migrator.NAnt/MigratorDotNet.snk b/src/Migrator.NAnt/MigratorDotNet.snk
deleted file mode 100644
index 5032d709..00000000
Binary files a/src/Migrator.NAnt/MigratorDotNet.snk and /dev/null differ
diff --git a/src/Migrator.Providers/AssemblyInfo.cs b/src/Migrator.Providers/AssemblyInfo.cs
deleted file mode 100644
index 037167e2..00000000
--- a/src/Migrator.Providers/AssemblyInfo.cs
+++ /dev/null
@@ -1,4 +0,0 @@
-using System.Reflection;
-
-[assembly: AssemblyTitle("DotNetProjects.Migrator.Providers")]
-[assembly: AssemblyDescription("Standard Migration Provider")]
\ No newline at end of file
diff --git a/src/Migrator.Providers/ColumnPropertiesMapper.cs b/src/Migrator.Providers/ColumnPropertiesMapper.cs
deleted file mode 100644
index aabc05d5..00000000
--- a/src/Migrator.Providers/ColumnPropertiesMapper.cs
+++ /dev/null
@@ -1,226 +0,0 @@
-using System;
-using System.Collections.Generic;
-using Migrator.Framework;
-
-namespace Migrator.Providers
-{
- ///
- /// This is basically a just a helper base class
- /// per-database implementors may want to override ColumnSql
- ///
- public class ColumnPropertiesMapper
- {
- ///
- /// the type of the column
- ///
- protected string columnSql;
-
- ///
- /// Sql if this column has a default value
- ///
- protected object defaultVal;
-
- protected Dialect dialect;
-
- ///
- /// Sql if This column is Indexed
- ///
- protected bool indexed;
-
- /// The name of the column
- protected string name;
-
- /// The SQL type
- public string type { get; private set; }
-
- public ColumnPropertiesMapper(Dialect dialect, string type)
- {
- this.dialect = dialect;
- this.type = type;
- }
-
- ///
- /// The sql for this column, override in database-specific implementation classes
- ///
- public virtual string ColumnSql
- {
- get { return columnSql; }
- }
-
- public string Name
- {
- get { return name; }
- set { name = value; }
- }
-
- public object Default
- {
- get { return defaultVal; }
- set { defaultVal = value; }
- }
-
- public string QuotedName
- {
- get { return dialect.Quote(Name); }
- }
-
- public string IndexSql
- {
- get
- {
- if (dialect.SupportsIndex && indexed)
- return String.Format("INDEX({0})", dialect.Quote(name));
- return null;
- }
- }
-
- public virtual void MapColumnProperties(Column column)
- {
- Name = column.Name;
-
- indexed = PropertySelected(column.ColumnProperty, ColumnProperty.Indexed);
-
- var vals = new List();
-
- AddName(vals);
-
- AddType(vals);
-
- AddCaseSensitive(column, vals);
-
- AddIdentity(column, vals);
-
- AddUnsigned(column, vals);
-
- AddNotNull(column, vals);
-
- AddNull(column, vals);
-
- AddPrimaryKey(column, vals);
-
- AddIdentityAgain(column, vals);
-
- AddUnique(column, vals);
-
- AddForeignKey(column, vals);
-
- AddDefaultValue(column, vals);
-
- columnSql = String.Join(" ", vals.ToArray());
- }
-
- public virtual void MapColumnPropertiesWithoutDefault(Column column)
- {
- Name = column.Name;
-
- indexed = PropertySelected(column.ColumnProperty, ColumnProperty.Indexed);
-
- var vals = new List();
-
- AddName(vals);
-
- AddType(vals);
-
- AddCaseSensitive(column, vals);
-
- AddIdentity(column, vals);
-
- AddUnsigned(column, vals);
-
- AddNotNull(column, vals);
-
- AddNull(column, vals);
-
- AddPrimaryKey(column, vals);
-
- AddIdentityAgain(column, vals);
-
- AddUnique(column, vals);
-
- AddForeignKey(column, vals);
-
- columnSql = String.Join(" ", vals.ToArray());
- }
-
- protected virtual void AddCaseSensitive(Column column, List vals)
- {
- AddValueIfSelected(column, ColumnProperty.CaseSensitive, vals);
- }
-
- protected virtual void AddDefaultValue(Column column, List vals)
- {
- if (column.DefaultValue != null)
- vals.Add(dialect.Default(column.DefaultValue));
- }
-
- protected virtual void AddForeignKey(Column column, List vals)
- {
- AddValueIfSelected(column, ColumnProperty.ForeignKey, vals);
- }
-
- protected virtual void AddUnique(Column column, List vals)
- {
- AddValueIfSelected(column, ColumnProperty.Unique, vals);
- }
-
- protected virtual void AddIdentityAgain(Column column, List vals)
- {
- if (dialect.IdentityNeedsType)
- AddValueIfSelected(column, ColumnProperty.Identity, vals);
- }
-
- protected virtual void AddPrimaryKey(Column column, List vals)
- {
- AddValueIfSelected(column, ColumnProperty.PrimaryKey, vals);
- }
-
- protected virtual void AddNull(Column column, List vals)
- {
- if (!PropertySelected(column.ColumnProperty, ColumnProperty.PrimaryKey))
- {
- if (dialect.NeedsNullForNullableWhenAlteringTable) AddValueIfSelected(column, ColumnProperty.Null, vals);
- }
- }
-
- protected virtual void AddNotNull(Column column, List vals)
- {
- if (!PropertySelected(column.ColumnProperty, ColumnProperty.Null) && (!PropertySelected(column.ColumnProperty, ColumnProperty.PrimaryKey) || dialect.NeedsNotNullForIdentity))
- {
- AddValueIfSelected(column, ColumnProperty.NotNull, vals);
- }
- }
-
- protected virtual void AddUnsigned(Column column, List vals)
- {
- if (dialect.IsUnsignedCompatible(column.Type))
- AddValueIfSelected(column, ColumnProperty.Unsigned, vals);
- }
-
- protected virtual void AddIdentity(Column column, List vals)
- {
- if (!dialect.IdentityNeedsType)
- AddValueIfSelected(column, ColumnProperty.Identity, vals);
- }
-
- protected virtual void AddType(List vals)
- {
- vals.Add(type);
- }
-
- protected virtual void AddName(List vals)
- {
- vals.Add(dialect.ColumnNameNeedsQuote || dialect.IsReservedWord(Name) ? QuotedName : Name);
- }
-
- protected virtual void AddValueIfSelected(Column column, ColumnProperty property, ICollection vals)
- {
- if (PropertySelected(column.ColumnProperty, property))
- vals.Add(dialect.SqlForProperty(property));
- }
-
- public static bool PropertySelected(ColumnProperty source, ColumnProperty comparison)
- {
- return (source & comparison) == comparison;
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/DbProviderFactoriesHelper.cs b/src/Migrator.Providers/DbProviderFactoriesHelper.cs
deleted file mode 100644
index f7d60531..00000000
--- a/src/Migrator.Providers/DbProviderFactoriesHelper.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data.Common;
-using System.Linq;
-using System.Text;
-
-namespace Migrator.Providers
-{
- public static class DbProviderFactoriesHelper
- {
- public static DbProviderFactory GetFactory(string providerName, string assemblyName, string factoryProviderType)
- {
- try
- {
- return DbProviderFactories.GetFactory(providerName);
- }
- catch(Exception)
- { }
-
- return (DbProviderFactory)AppDomain.CurrentDomain.CreateInstanceAndUnwrap(assemblyName, factoryProviderType);
- }
- }
-}
diff --git a/src/Migrator.Providers/Dialect.cs b/src/Migrator.Providers/Dialect.cs
deleted file mode 100644
index c860dd0b..00000000
--- a/src/Migrator.Providers/Dialect.cs
+++ /dev/null
@@ -1,284 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Globalization;
-using Migrator.Framework;
-
-namespace Migrator.Providers
-{
- ///
- /// Defines the implementations specific details for a particular database.
- ///
- public abstract class Dialect
- {
- readonly Dictionary propertyMap = new Dictionary();
- readonly HashSet reservedWords = new HashSet();
- readonly TypeNames typeNames = new TypeNames();
- readonly List unsignedCompatibleTypes = new List();
-
- protected Dialect()
- {
- RegisterProperty(ColumnProperty.Null, "NULL");
- RegisterProperty(ColumnProperty.NotNull, "NOT NULL");
- RegisterProperty(ColumnProperty.Unique, "UNIQUE");
- RegisterProperty(ColumnProperty.PrimaryKey, "PRIMARY KEY");
- }
-
- public virtual bool ColumnNameNeedsQuote
- {
- get { return false; }
- }
-
- public virtual bool TableNameNeedsQuote
- {
- get { return false; }
- }
-
- public virtual bool ConstraintNameNeedsQuote
- {
- get { return false; }
- }
-
- public virtual bool IdentityNeedsType
- {
- get { return true; }
- }
-
- public virtual bool NeedsNotNullForIdentity
- {
- get { return true; }
- }
-
- public virtual bool SupportsIndex
- {
- get { return true; }
- }
-
- public virtual string QuoteTemplate
- {
- get { return "\"{0}\""; }
- }
-
- public virtual bool NeedsNullForNullableWhenAlteringTable
- {
- get { return false; }
- }
-
- protected void AddReservedWord(string reservedWord)
- {
- reservedWords.Add(reservedWord.ToUpperInvariant());
- }
-
- protected void AddReservedWords(params string[] words)
- {
- if (words == null) return;
- foreach (string word in words) reservedWords.Add(word);
- }
-
- public virtual bool IsReservedWord(string reservedWord)
- {
- if (string.IsNullOrEmpty(reservedWord)) throw new ArgumentNullException("reservedWord");
-
- if (reservedWords == null) return false;
-
- bool isReserved = reservedWords.Contains(reservedWord.ToUpperInvariant());
-
- if (isReserved)
- {
- Console.WriteLine("Reserved word: {0}", reservedWord);
- }
-
- return isReserved;
- }
-
- public abstract ITransformationProvider GetTransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope, string providerName);
- public abstract ITransformationProvider GetTransformationProvider(Dialect dialect, IDbConnection connection, string defaultSchema, string scope, string providerName);
-
- public ITransformationProvider NewProviderForDialect(string connectionString, string defaultSchema, string scope, string providerName)
- {
- return GetTransformationProvider(this, connectionString, defaultSchema, scope, providerName);
- }
-
- public ITransformationProvider NewProviderForDialect(IDbConnection connection, string defaultSchema, string scope, string providerName)
- {
- return GetTransformationProvider(this, connection, defaultSchema, scope, providerName);
- }
-
- ///
- /// Subclasses register a typename for the given type code and maximum
- /// column length. $l in the type name will be replaced by the column
- /// length (if appropriate)
- ///
- /// The typecode
- /// Maximum length of database type
- /// The database type name
- protected void RegisterColumnType(DbType code, int capacity, string name)
- {
- typeNames.Put(code, capacity, name);
- }
-
- ///
- /// Suclasses register a typename for the given type code. $l in the
- /// typename will be replaced by the column length (if appropriate).
- ///
- /// The typecode
- /// The database type name
- protected void RegisterColumnType(DbType code, string name)
- {
- typeNames.Put(code, name);
- }
-
- public virtual ColumnPropertiesMapper GetColumnMapper(Column column)
- {
- string type = column.Size > 0 ? GetTypeName(column.Type, column.Size) : GetTypeName(column.Type);
- if (! IdentityNeedsType && column.IsIdentity)
- type = String.Empty;
-
- return new ColumnPropertiesMapper(this, type);
- }
-
- public virtual DbType GetDbTypeFromString(string type)
- {
- return typeNames.GetDbType(type);
- }
-
- ///
- /// Get the name of the database type associated with the given
- ///
- /// The DbType
- /// The database type name used by ddl.
- public virtual string GetTypeName(DbType type)
- {
- string result = typeNames.Get(type);
- if (result == null)
- {
- throw new Exception(string.Format("No default type mapping for DbType {0}", type));
- }
-
- return result;
- }
-
- ///
- /// Get the name of the database type associated with the given
- ///
- /// The DbType
- /// The database type name used by ddl.
- ///
- public virtual string GetTypeName(DbType type, int length)
- {
- return GetTypeName(type, length, 0, 0);
- }
-
- ///
- /// Get the name of the database type associated with the given
- ///
- /// The DbType
- /// The database type name used by ddl.
- ///
- ///
- ///
- public virtual string GetTypeName(DbType type, int length, int precision, int scale)
- {
- string resultWithLength = typeNames.Get(type, length, precision, scale);
- if (resultWithLength != null)
- return resultWithLength;
-
- return GetTypeName(type);
- }
-
- ///
- /// Get the type from the specified database type name.
- /// Note: This does not work perfectly, but it will do for most cases.
- ///
- /// The name of the type.
- /// The .
- public virtual DbType GetDbType(string databaseTypeName)
- {
- return typeNames.GetDbType(databaseTypeName);
- }
-
- public void RegisterProperty(ColumnProperty property, string sql)
- {
- if (! propertyMap.ContainsKey(property))
- {
- propertyMap.Add(property, sql);
- }
- propertyMap[property] = sql;
- }
-
- public string SqlForProperty(ColumnProperty property)
- {
- if (propertyMap.ContainsKey(property))
- {
- return propertyMap[property];
- }
- return String.Empty;
- }
-
- public virtual string Quote(string value)
- {
- return String.Format(QuoteTemplate, value);
- }
-
- public virtual string Default(object defaultValue)
- {
- if (defaultValue is String && defaultValue.ToString() == String.Empty)
- {
- defaultValue = "''";
- }
- else if (defaultValue is Guid)
- {
- return String.Format("DEFAULT '{0}'", defaultValue.ToString());
- }
- else if (defaultValue is DateTime)
- {
- return String.Format("DEFAULT '{0}'", ((DateTime)defaultValue).ToString("yyyy-MM-dd HH:mm:ss"));
- }
- else if (defaultValue is String)
- {
- defaultValue = ((String)defaultValue).Replace("'", "''");
- defaultValue = "'" + defaultValue + "'";
- }
-
- return String.Format("DEFAULT {0}", defaultValue);
- }
-
- public ColumnPropertiesMapper GetAndMapColumnProperties(Column column)
- {
- ColumnPropertiesMapper mapper = GetColumnMapper(column);
- mapper.MapColumnProperties(column);
- if (column.DefaultValue != null && column.DefaultValue != DBNull.Value)
- mapper.Default = column.DefaultValue;
- return mapper;
- }
-
- public ColumnPropertiesMapper GetAndMapColumnPropertiesWithoutDefault(Column column)
- {
- ColumnPropertiesMapper mapper = GetColumnMapper(column);
- mapper.MapColumnPropertiesWithoutDefault(column);
- if (column.DefaultValue != null && column.DefaultValue != DBNull.Value)
- mapper.Default = column.DefaultValue;
- return mapper;
- }
-
- ///
- /// Subclasses register which DbTypes are unsigned-compatible (ie, available in signed and unsigned variants)
- ///
- ///
- protected void RegisterUnsignedCompatible(DbType type)
- {
- unsignedCompatibleTypes.Add(type);
- }
-
- ///
- /// Determine if a particular database type has an unsigned variant
- ///
- /// The DbType
- /// True if the database type has an unsigned variant, otherwise false
- public bool IsUnsignedCompatible(DbType type)
- {
- return unsignedCompatibleTypes.Contains(type);
- }
-
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/DotNetProjects.Migrator.Providers.csproj b/src/Migrator.Providers/DotNetProjects.Migrator.Providers.csproj
deleted file mode 100644
index a9a8aa64..00000000
--- a/src/Migrator.Providers/DotNetProjects.Migrator.Providers.csproj
+++ /dev/null
@@ -1,165 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 9.0.30729
- 2.0
- {D58C68E4-D789-40F7-9078-C9F587D4363C}
- Library
- Migrator.Providers
- DotNetProjects.Migrator.Providers
-
-
- 3.5
-
-
- false
- true
- MigratorDotNet.snk
- v4.0
- publish\
- true
- Disk
- false
- Foreground
- 7
- Days
- false
- false
- true
- 0
- 1.0.0.%2a
- false
- true
-
-
-
- true
- full
- false
- bin\Debug\
- TRACE;DEBUG
- prompt
- 4
- AllRules.ruleset
- default
-
-
- pdbonly
- true
- bin\Release\
- TRACE
- prompt
- 4
- AllRules.ruleset
-
-
-
- False
- ..\..\lib\NAnt.Core.dll
-
-
-
-
-
-
-
-
- GlobalAssemblyInfo.cs
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- False
- .NET Framework 3.5 SP1 Client Profile
- false
-
-
- False
- .NET Framework 2.0 %28x86%29
- true
-
-
- False
- .NET Framework 3.0 %28x86%29
- false
-
-
- False
- .NET Framework 3.5
- false
-
-
- False
- .NET Framework 3.5 SP1
- false
-
-
-
-
-
-
-
- {5270F048-E580-486C-B14C-E5B9F6E539D4}
- DotNetProjects.Migrator.Framework
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/Migrator.Providers/ForeignKeyConstraintMapper.cs b/src/Migrator.Providers/ForeignKeyConstraintMapper.cs
deleted file mode 100644
index 3df89f5f..00000000
--- a/src/Migrator.Providers/ForeignKeyConstraintMapper.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-using Migrator.Framework;
-
-namespace Migrator.Providers
-{
- public class ForeignKeyConstraintMapper
- {
- public string SqlForConstraint(ForeignKeyConstraintType constraint)
- {
- switch (constraint)
- {
- case ForeignKeyConstraintType.Cascade:
- return "CASCADE";
- case ForeignKeyConstraintType.Restrict:
- return "RESTRICT";
- case ForeignKeyConstraintType.SetDefault:
- return "SET DEFAULT";
- case ForeignKeyConstraintType.SetNull:
- return "SET NULL";
- default:
- return "NO ACTION";
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/DB2/DB2Dialect.cs b/src/Migrator.Providers/Impl/DB2/DB2Dialect.cs
deleted file mode 100644
index 48341675..00000000
--- a/src/Migrator.Providers/Impl/DB2/DB2Dialect.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-using System.Data;
-
-using Migrator.Framework;
-
-namespace Migrator.Providers.Impl.DB2
-{
- public class DB2Dialect : Dialect
- {
- public DB2Dialect()
- {
- this.RegisterColumnType(DbType.AnsiStringFixedLength, "CHAR(255)");
- this.RegisterColumnType(DbType.AnsiStringFixedLength, 255, "CHAR($l)");
- this.RegisterColumnType(DbType.AnsiStringFixedLength, 65535, "TEXT");
- this.RegisterColumnType(DbType.AnsiStringFixedLength, 16777215, "MEDIUMTEXT");
- this.RegisterColumnType(DbType.AnsiString, "VARCHAR(255)");
- this.RegisterColumnType(DbType.AnsiString, 255, "VARCHAR($l)");
- this.RegisterColumnType(DbType.AnsiString, 256, "VARCHAR(255)");
- this.RegisterColumnType(DbType.AnsiString, 65535, "TEXT");
- this.RegisterColumnType(DbType.AnsiString, 16777215, "MEDIUMTEXT");
- this.RegisterColumnType(DbType.Binary, "LONGBLOB");
- this.RegisterColumnType(DbType.Binary, 127, "TINYBLOB");
- this.RegisterColumnType(DbType.Binary, 65535, "BLOB");
- this.RegisterColumnType(DbType.Binary, 16777215, "MEDIUMBLOB");
- this.RegisterColumnType(DbType.Boolean, "TINYINT(1)");
- this.RegisterColumnType(DbType.Byte, "TINYINT UNSIGNED");
- this.RegisterColumnType(DbType.Currency, "MONEY");
- this.RegisterColumnType(DbType.Date, "DATE");
- this.RegisterColumnType(DbType.DateTime, "DATETIME");
- this.RegisterColumnType(DbType.DateTimeOffset, "DATETIME");
- this.RegisterColumnType(DbType.Decimal, "NUMERIC(19,5)");
- this.RegisterColumnType(DbType.Decimal, 19, "NUMERIC(19, $l)");
- this.RegisterColumnType(DbType.Double, "DOUBLE");
- this.RegisterColumnType(DbType.Guid, "VARCHAR(40)");
- this.RegisterColumnType(DbType.Int16, "SMALLINT");
- this.RegisterColumnType(DbType.Int32, "INTEGER");
- this.RegisterColumnType(DbType.Int64, "BIGINT");
- this.RegisterColumnType(DbType.Single, "FLOAT");
- this.RegisterColumnType(DbType.StringFixedLength, "CHAR(255)");
- this.RegisterColumnType(DbType.StringFixedLength, 255, "CHAR($l)");
- this.RegisterColumnType(DbType.StringFixedLength, 65535, "TEXT");
- this.RegisterColumnType(DbType.StringFixedLength, 16777215, "MEDIUMTEXT");
- this.RegisterColumnType(DbType.String, "VARCHAR(255)");
- this.RegisterColumnType(DbType.String, 255, "VARCHAR($l)");
- this.RegisterColumnType(DbType.String, 256, "VARCHAR(255)");
- this.RegisterColumnType(DbType.String, 65535, "TEXT");
- this.RegisterColumnType(DbType.String, 16777215, "MEDIUMTEXT");
- this.RegisterColumnType(DbType.String, 1073741823, "LONGTEXT");
- this.RegisterColumnType(DbType.Time, "TIME");
-
- this.RegisterProperty(ColumnProperty.Unsigned, "UNSIGNED");
- this.RegisterProperty(ColumnProperty.Identity, "AUTO_INCREMENT");
-
- this.RegisterUnsignedCompatible(DbType.Int16);
- this.RegisterUnsignedCompatible(DbType.Int32);
- this.RegisterUnsignedCompatible(DbType.Int64);
- this.RegisterUnsignedCompatible(DbType.Decimal);
- this.RegisterUnsignedCompatible(DbType.Double);
- this.RegisterUnsignedCompatible(DbType.Single);
-
- this.AddReservedWords("KEY");
- }
-
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, string connectionString,
- string defaultSchema, string scope, string providerName)
- {
- return new DB2TransformationProvider(dialect, connectionString, scope, providerName);
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, IDbConnection connection,
- string defaultSchema,
- string scope, string providerName)
- {
- return new DB2TransformationProvider(dialect, connection, scope, providerName);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/DB2/DB2TransformationProvider.cs b/src/Migrator.Providers/Impl/DB2/DB2TransformationProvider.cs
deleted file mode 100644
index 66781912..00000000
--- a/src/Migrator.Providers/Impl/DB2/DB2TransformationProvider.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.Common;
-
-namespace Migrator.Providers.Impl.DB2
-{
- ///
- /// DB2 transformation provider
- ///
- public class DB2TransformationProvider : TransformationProvider
- {
- public DB2TransformationProvider(Dialect dialect, string connectionString, string scope, string providerName)
- : base(dialect, connectionString, null, scope)
- {
- if (string.IsNullOrEmpty(providerName)) providerName = "IBM.Data.DB2";
- var fac = DbProviderFactories.GetFactory(providerName);
- _connection = fac.CreateConnection();
- _connection.ConnectionString = _connectionString;
- this._connection.Open();
- }
-
- public DB2TransformationProvider(Dialect dialect, IDbConnection connection, string scope, string providerName)
- : base(dialect, connection, null, scope)
- {
- }
-
- public override List GetDatabases()
- {
- throw new NotImplementedException();
- }
-
- public override bool ConstraintExists(string table, string name)
- {
- throw new NotImplementedException();
- }
-
- public override bool IndexExists(string table, string name)
- {
- throw new NotImplementedException();
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/Firebird/FirebirdColumnPropertiesMapper.cs b/src/Migrator.Providers/Impl/Firebird/FirebirdColumnPropertiesMapper.cs
deleted file mode 100644
index 3b7eb296..00000000
--- a/src/Migrator.Providers/Impl/Firebird/FirebirdColumnPropertiesMapper.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-using System;
-using System.Collections.Generic;
-using Migrator.Framework;
-
-namespace Migrator.Providers.Impl.Firebird
-{
- public class FirebirdColumnPropertiesMapper : ColumnPropertiesMapper
- {
- public FirebirdColumnPropertiesMapper(Dialect dialect, string type)
- : base(dialect, type)
- {
- }
-
- public override void MapColumnProperties(Column column)
- {
- Name = column.Name;
-
- indexed = PropertySelected(column.ColumnProperty, ColumnProperty.Indexed);
-
- var vals = new List();
-
- AddName(vals);
-
- AddType(vals);
-
- AddIdentity(column, vals);
-
- //AddUnsigned(column, vals);
-
- AddPrimaryKey(column, vals);
-
- AddIdentityAgain(column, vals);
-
- AddUnique(column, vals);
-
- AddForeignKey(column, vals);
-
- AddDefaultValue(column, vals);
-
- AddNotNull(column, vals);
-
- AddNull(column, vals);
-
- columnSql = String.Join(" ", vals.ToArray());
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/Firebird/FirebirdDialect.cs b/src/Migrator.Providers/Impl/Firebird/FirebirdDialect.cs
deleted file mode 100644
index 323ac4d5..00000000
--- a/src/Migrator.Providers/Impl/Firebird/FirebirdDialect.cs
+++ /dev/null
@@ -1,68 +0,0 @@
-using System;
-using System.Data;
-using Migrator.Framework;
-
-namespace Migrator.Providers.Impl.Firebird
-{
- public class FirebirdDialect : Dialect
- {
- public FirebirdDialect()
- {
- RegisterColumnType(DbType.AnsiStringFixedLength, 8000, "CHAR($l)");
- RegisterColumnType(DbType.AnsiString, 8000, "CHAR($l)");
- RegisterColumnType(DbType.Binary, "BLOB");
- RegisterColumnType(DbType.Binary, 8000, "CHAR");
- RegisterColumnType(DbType.Boolean, "SMALLINT");
- RegisterColumnType(DbType.Byte, "TINYINT");
- RegisterColumnType(DbType.Currency, "MONEY");
- RegisterColumnType(DbType.Date, "TIMESTAMP");
- RegisterColumnType(DbType.DateTime, "TIMESTAMP");
- RegisterColumnType(DbType.DateTimeOffset, "TIMESTAMP");
- RegisterColumnType(DbType.Decimal, "DECIMAL");
- RegisterColumnType(DbType.Double, "DOUBLE PRECISION"); //synonym for FLOAT(53)
- RegisterColumnType(DbType.Guid, "CHAR(38)");
- RegisterColumnType(DbType.Int16, "SMALLINT");
- RegisterColumnType(DbType.Int32, "INT");
- RegisterColumnType(DbType.Int64, "BIGINT");
- RegisterColumnType(DbType.Single, "REAL"); //synonym for FLOAT(24)
- RegisterColumnType(DbType.StringFixedLength, "NCHAR(255)");
- RegisterColumnType(DbType.String, "VARCHAR(255) CHARACTER SET UNICODE_FSS");
- RegisterColumnType(DbType.String, 4000, "VARCHAR($l) CHARACTER SET UNICODE_FSS");
- RegisterColumnType(DbType.String, int.MaxValue, "BLOB SUB_TYPE TEXT");
- RegisterColumnType(DbType.Time, "INTEGER");
-
- this.RegisterProperty(ColumnProperty.Unsigned, "UNSIGNED");
-
- this.RegisterUnsignedCompatible(DbType.Int16);
- this.RegisterUnsignedCompatible(DbType.Int32);
- this.RegisterUnsignedCompatible(DbType.Int64);
- this.RegisterUnsignedCompatible(DbType.Decimal);
- this.RegisterUnsignedCompatible(DbType.Double);
- this.RegisterUnsignedCompatible(DbType.Single);
-
- this.AddReservedWords("KEY", "TIMESTAMP", "VALUE");
- }
-
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope, string providerName)
- {
- return new FirebirdTransformationProvider(dialect, connectionString, scope, providerName);
- }
-
- public override ColumnPropertiesMapper GetColumnMapper(Column column)
- {
- string type = column.Size > 0 ? GetTypeName(column.Type, column.Size) : GetTypeName(column.Type);
- if (!IdentityNeedsType && column.IsIdentity)
- type = String.Empty;
-
- return new FirebirdColumnPropertiesMapper(this, type);
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, IDbConnection connection,
- string defaultSchema,
- string scope, string providerName)
- {
- return new FirebirdTransformationProvider(dialect, connection, scope, providerName);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/Firebird/FirebirdTransformationProvider.cs b/src/Migrator.Providers/Impl/Firebird/FirebirdTransformationProvider.cs
deleted file mode 100644
index ee875b83..00000000
--- a/src/Migrator.Providers/Impl/Firebird/FirebirdTransformationProvider.cs
+++ /dev/null
@@ -1,136 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.Common;
-using System.Linq;
-using Migrator.Framework;
-
-namespace Migrator.Providers.Impl.Firebird
-{
- ///
- /// Firebird transformation provider
- ///
- public class FirebirdTransformationProvider : TransformationProvider
- {
- public FirebirdTransformationProvider(Dialect dialect, string connectionString, string scope, string providerName)
- : base(dialect, connectionString, null, scope)
- {
- if (string.IsNullOrEmpty(providerName)) providerName = "FirebirdSql.Data.FirebirdClient";
- var fac = DbProviderFactoriesHelper.GetFactory(providerName, "FirebirdSql.Data.FirebirdClient", "FirebirdSql.Data.FirebirdClient.FirebirdClientFactory");
- _connection = fac.CreateConnection();
- _connection.ConnectionString = _connectionString;
- this._connection.Open();
- }
-
- public FirebirdTransformationProvider(Dialect dialect, IDbConnection connection, string scope, string providerName)
- : base(dialect, connection, null, scope)
- {
- }
-
- public override void AddColumn(string table, string sqlColumn)
- {
- table = QuoteTableNameIfRequired(table);
- ExecuteNonQuery(String.Format("ALTER TABLE {0} ADD {1}", table, sqlColumn));
- }
-
- public override void DropDatabases(string databaseName)
- {
- if (string.IsNullOrEmpty(databaseName))
- ExecuteNonQuery(string.Format("DROP DATABASE"));
- }
-
- ///
- /// Execute an SQL query returning results.
- ///
- /// The SQL command.
- /// A data iterator, IDataReader.
- public override IDataReader ExecuteQuery(string sql)
- {
- Logger.Trace(sql);
- IDbCommand cmd = BuildCommand(sql);
- {
- try
- {
- return cmd.ExecuteReader();
- }
- catch (Exception ex)
- {
- Logger.Warn("query failed: {0}", cmd.CommandText);
- throw new Exception("Failed to execute sql statement: " + sql, ex);
- }
- }
- }
-
- public override Column[] GetColumns(string table)
- {
- var columns = new List();
- using (
- IDataReader reader =
- ExecuteQuery(
- String.Format("select RDB$FIELD_NAME, RDB$NULL_FLAG from RDB$RELATION_FIELDS where RDB$RELATION_NAME = '{0}'", table.ToUpper())))
- {
- while (reader.Read())
- {
- var column = new Column(reader.GetString(0).Trim(), DbType.String);
- string nullableStr = reader.GetString(1);
- bool isNullable = nullableStr == "1";
- column.ColumnProperty |= isNullable ? ColumnProperty.Null : ColumnProperty.NotNull;
-
- columns.Add(column);
- }
- }
-
- return columns.ToArray();
- }
-
- public override void AddTable(string name, params IDbField[] fields)
- {
- var columns = fields.Where(x => x is Column).Cast().ToArray();
-
- base.AddTable(name, fields);
-
- if (columns.Any(c => c.ColumnProperty == ColumnProperty.PrimaryKeyWithIdentity))
- {
- var identityColumn = columns.First(c => c.ColumnProperty == ColumnProperty.PrimaryKeyWithIdentity);
-
- var seqTName = name.Length > 21 ? name.Substring(0, 21) : name;
- if (seqTName.EndsWith("_"))
- seqTName = seqTName.Substring(0, seqTName.Length - 1);
-
- // Create a sequence for the table
- ExecuteQuery(String.Format("CREATE GENERATOR {0}_SEQUENCE", seqTName));
- ExecuteQuery(String.Format("SET GENERATOR {0}_SEQUENCE TO 0", seqTName));
-
- var sql = ""; // "set term !! ;";
- sql += "CREATE TRIGGER {1}_TRIGGER FOR {0}\n";
- sql += "ACTIVE BEFORE INSERT POSITION 0\n";
- sql += "AS\n";
- sql += "BEGIN\n";
- sql += "if (NEW.{2} is NULL) then NEW.{2} = GEN_ID({1}_SEQUENCE, 1);\n";
- sql += "END\n";
-
- ExecuteQuery(String.Format(sql, name, seqTName, identityColumn.Name));
- }
- }
-
- public override List GetDatabases()
- {
- throw new NotImplementedException();
- }
-
- public override bool ConstraintExists(string table, string name)
- {
- //todo, implement this!!!
-
- //http://edn.embarcadero.com/article/25259 field infos in FB
- //http://www.felix-colibri.com/papers/db/interbase/using_interbase_system_tables/using_interbase_system_tables.html
-
- return false;
- }
-
- public override bool IndexExists(string table, string name)
- {
- return false;
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/Informix/InformixDialect.cs b/src/Migrator.Providers/Impl/Informix/InformixDialect.cs
deleted file mode 100644
index 3861070b..00000000
--- a/src/Migrator.Providers/Impl/Informix/InformixDialect.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-using System.Data;
-
-using Migrator.Framework;
-
-namespace Migrator.Providers.Impl.Informix
-{
- public class InformixDialect : Dialect
- {
- public InformixDialect()
- {
- this.RegisterColumnType(DbType.AnsiStringFixedLength, "CHAR(255)");
- this.RegisterColumnType(DbType.AnsiStringFixedLength, 255, "CHAR($l)");
- this.RegisterColumnType(DbType.AnsiStringFixedLength, 65535, "TEXT");
- this.RegisterColumnType(DbType.AnsiStringFixedLength, 16777215, "MEDIUMTEXT");
- this.RegisterColumnType(DbType.AnsiString, "VARCHAR(255)");
- this.RegisterColumnType(DbType.AnsiString, 255, "VARCHAR($l)");
- this.RegisterColumnType(DbType.AnsiString, 256, "VARCHAR(255)");
- this.RegisterColumnType(DbType.AnsiString, 65535, "TEXT");
- this.RegisterColumnType(DbType.AnsiString, 16777215, "MEDIUMTEXT");
- this.RegisterColumnType(DbType.Binary, "LONGBLOB");
- this.RegisterColumnType(DbType.Binary, 127, "TINYBLOB");
- this.RegisterColumnType(DbType.Binary, 65535, "BLOB");
- this.RegisterColumnType(DbType.Binary, 16777215, "MEDIUMBLOB");
- this.RegisterColumnType(DbType.Boolean, "TINYINT(1)");
- this.RegisterColumnType(DbType.Byte, "TINYINT UNSIGNED");
- this.RegisterColumnType(DbType.Currency, "MONEY");
- this.RegisterColumnType(DbType.Date, "DATE");
- this.RegisterColumnType(DbType.DateTime, "DATETIME");
- this.RegisterColumnType(DbType.DateTimeOffset, "DATETIME");
- this.RegisterColumnType(DbType.Decimal, "NUMERIC(19,5)");
- this.RegisterColumnType(DbType.Decimal, 19, "NUMERIC(19, $l)");
- this.RegisterColumnType(DbType.Double, "DOUBLE");
- this.RegisterColumnType(DbType.Guid, "VARCHAR(40)");
- this.RegisterColumnType(DbType.Int16, "SMALLINT");
- this.RegisterColumnType(DbType.Int32, "INTEGER");
- this.RegisterColumnType(DbType.Int64, "BIGINT");
- this.RegisterColumnType(DbType.Single, "FLOAT");
- this.RegisterColumnType(DbType.StringFixedLength, "CHAR(255)");
- this.RegisterColumnType(DbType.StringFixedLength, 255, "CHAR($l)");
- this.RegisterColumnType(DbType.StringFixedLength, 65535, "TEXT");
- this.RegisterColumnType(DbType.StringFixedLength, 16777215, "MEDIUMTEXT");
- this.RegisterColumnType(DbType.String, "VARCHAR(255)");
- this.RegisterColumnType(DbType.String, 255, "VARCHAR($l)");
- this.RegisterColumnType(DbType.String, 256, "VARCHAR(255)");
- this.RegisterColumnType(DbType.String, 65535, "TEXT");
- this.RegisterColumnType(DbType.String, 16777215, "MEDIUMTEXT");
- this.RegisterColumnType(DbType.String, 1073741823, "LONGTEXT");
- this.RegisterColumnType(DbType.Time, "TIME");
-
- this.RegisterProperty(ColumnProperty.Unsigned, "UNSIGNED");
- this.RegisterProperty(ColumnProperty.Identity, "AUTO_INCREMENT");
-
- this.RegisterUnsignedCompatible(DbType.Int16);
- this.RegisterUnsignedCompatible(DbType.Int32);
- this.RegisterUnsignedCompatible(DbType.Int64);
- this.RegisterUnsignedCompatible(DbType.Decimal);
- this.RegisterUnsignedCompatible(DbType.Double);
- this.RegisterUnsignedCompatible(DbType.Single);
-
- this.AddReservedWords("KEY");
- }
-
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, string connectionString,
- string defaultSchema, string scope, string providerName)
- {
- return new InformixTransformationProvider(dialect, connectionString, scope, providerName);
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, IDbConnection connection,
- string defaultSchema,
- string scope, string providerName)
- {
- return new InformixTransformationProvider(dialect, connection, scope, providerName);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/Informix/InformixTransformationProvider.cs b/src/Migrator.Providers/Impl/Informix/InformixTransformationProvider.cs
deleted file mode 100644
index f2fe1ed5..00000000
--- a/src/Migrator.Providers/Impl/Informix/InformixTransformationProvider.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.Common;
-
-namespace Migrator.Providers.Impl.Informix
-{
- ///
- /// DB2 transformation provider
- ///
- public class InformixTransformationProvider : TransformationProvider
- {
- public InformixTransformationProvider(Dialect dialect, string connectionString, string scope, string providerName)
- : base(dialect, connectionString, null, scope)
- {
- if (string.IsNullOrEmpty(providerName)) providerName = "IBM.Data.Informix.Client";
- var fac = DbProviderFactories.GetFactory(providerName);
- _connection = fac.CreateConnection();
- _connection.ConnectionString = _connectionString;
- this._connection.Open();
- }
-
- public InformixTransformationProvider(Dialect dialect, IDbConnection connection, string scope, string providerName)
- : base(dialect, connection, null, scope)
- {
- }
-
- public override List GetDatabases()
- {
- throw new NotImplementedException();
- }
-
- public override bool ConstraintExists(string table, string name)
- {
- throw new NotImplementedException();
- }
-
- public override bool IndexExists(string table, string name)
- {
- throw new NotImplementedException();
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/Ingres/IngresDialect.cs b/src/Migrator.Providers/Impl/Ingres/IngresDialect.cs
deleted file mode 100644
index f8f1b1be..00000000
--- a/src/Migrator.Providers/Impl/Ingres/IngresDialect.cs
+++ /dev/null
@@ -1,76 +0,0 @@
-using System.Data;
-using Migrator.Framework;
-
-namespace Migrator.Providers.Impl.Ingres
-{
- public class IngresDialect : Dialect
- {
- public IngresDialect()
- {
- this.RegisterColumnType(DbType.AnsiStringFixedLength, "CHAR(255)");
- this.RegisterColumnType(DbType.AnsiStringFixedLength, 255, "CHAR($l)");
- this.RegisterColumnType(DbType.AnsiStringFixedLength, 65535, "TEXT");
- this.RegisterColumnType(DbType.AnsiStringFixedLength, 16777215, "MEDIUMTEXT");
- this.RegisterColumnType(DbType.AnsiString, "VARCHAR(255)");
- this.RegisterColumnType(DbType.AnsiString, 255, "VARCHAR($l)");
- this.RegisterColumnType(DbType.AnsiString, 256, "VARCHAR(255)");
- this.RegisterColumnType(DbType.AnsiString, 65535, "TEXT");
- this.RegisterColumnType(DbType.AnsiString, 16777215, "MEDIUMTEXT");
- this.RegisterColumnType(DbType.Binary, "LONGBLOB");
- this.RegisterColumnType(DbType.Binary, 127, "TINYBLOB");
- this.RegisterColumnType(DbType.Binary, 65535, "BLOB");
- this.RegisterColumnType(DbType.Binary, 16777215, "MEDIUMBLOB");
- this.RegisterColumnType(DbType.Boolean, "TINYINT(1)");
- this.RegisterColumnType(DbType.Byte, "TINYINT UNSIGNED");
- this.RegisterColumnType(DbType.Currency, "MONEY");
- this.RegisterColumnType(DbType.Date, "DATE");
- this.RegisterColumnType(DbType.DateTime, "DATETIME");
- this.RegisterColumnType(DbType.DateTimeOffset, "DATETIME");
- this.RegisterColumnType(DbType.Decimal, "NUMERIC(19,5)");
- this.RegisterColumnType(DbType.Decimal, 19, "NUMERIC(19, $l)");
- this.RegisterColumnType(DbType.Double, "DOUBLE");
- this.RegisterColumnType(DbType.Guid, "VARCHAR(40)");
- this.RegisterColumnType(DbType.Int16, "SMALLINT");
- this.RegisterColumnType(DbType.Int32, "INTEGER");
- this.RegisterColumnType(DbType.Int64, "BIGINT");
- this.RegisterColumnType(DbType.Single, "FLOAT");
- this.RegisterColumnType(DbType.StringFixedLength, "CHAR(255)");
- this.RegisterColumnType(DbType.StringFixedLength, 255, "CHAR($l)");
- this.RegisterColumnType(DbType.StringFixedLength, 65535, "TEXT");
- this.RegisterColumnType(DbType.StringFixedLength, 16777215, "MEDIUMTEXT");
- this.RegisterColumnType(DbType.String, "VARCHAR(255)");
- this.RegisterColumnType(DbType.String, 255, "VARCHAR($l)");
- this.RegisterColumnType(DbType.String, 256, "VARCHAR(255)");
- this.RegisterColumnType(DbType.String, 65535, "TEXT");
- this.RegisterColumnType(DbType.String, 16777215, "MEDIUMTEXT");
- this.RegisterColumnType(DbType.String, 1073741823, "LONGTEXT");
- this.RegisterColumnType(DbType.Time, "TIME");
-
- this.RegisterProperty(ColumnProperty.Unsigned, "UNSIGNED");
- this.RegisterProperty(ColumnProperty.Identity, "AUTO_INCREMENT");
-
- this.RegisterUnsignedCompatible(DbType.Int16);
- this.RegisterUnsignedCompatible(DbType.Int32);
- this.RegisterUnsignedCompatible(DbType.Int64);
- this.RegisterUnsignedCompatible(DbType.Decimal);
- this.RegisterUnsignedCompatible(DbType.Double);
- this.RegisterUnsignedCompatible(DbType.Single);
-
- this.AddReservedWords("KEY");
- }
-
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, string connectionString,
- string defaultSchema, string scope, string providerName)
- {
- return new IngresTransformationProvider(dialect, connectionString, scope, providerName);
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, IDbConnection connection,
- string defaultSchema,
- string scope, string providerName)
- {
- return new IngresTransformationProvider(dialect, connection, scope, providerName);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/Ingres/IngresTransformationProvider.cs b/src/Migrator.Providers/Impl/Ingres/IngresTransformationProvider.cs
deleted file mode 100644
index 6474d592..00000000
--- a/src/Migrator.Providers/Impl/Ingres/IngresTransformationProvider.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.Common;
-
-namespace Migrator.Providers.Impl.Ingres
-{
- public class IngresTransformationProvider : TransformationProvider
- {
- public IngresTransformationProvider(Dialect dialect, string connectionString, string scope, string providerName)
- : base(dialect, connectionString, null, scope)
- {
- if (string.IsNullOrEmpty(providerName)) providerName = "Ingres.Client";
- var fac = DbProviderFactories.GetFactory(providerName);
- _connection = fac.CreateConnection();
- _connection.ConnectionString = _connectionString;
- this._connection.Open();
- }
-
- public IngresTransformationProvider(Dialect dialect, IDbConnection connection, string scope, string providerName)
- : base(dialect, connection, null, scope)
- {
- }
-
- public override List GetDatabases()
- {
- throw new NotImplementedException();
- }
-
- public override bool ConstraintExists(string table, string name)
- {
- throw new NotImplementedException();
- }
-
- public override bool IndexExists(string table, string name)
- {
- throw new NotImplementedException();
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/Mysql/MariaDBDialect.cs b/src/Migrator.Providers/Impl/Mysql/MariaDBDialect.cs
deleted file mode 100644
index dc1fd98d..00000000
--- a/src/Migrator.Providers/Impl/Mysql/MariaDBDialect.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System;
-using System.Data;
-using Migrator.Framework;
-
-namespace Migrator.Providers.Mysql
-{
- public class MariaDBDialect : MysqlDialect
- {
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope, string providerName)
- {
- return new MariaDBTransformationProvider(dialect, connectionString, scope, providerName);
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, IDbConnection connection,
- string defaultSchema,
- string scope, string providerName)
- {
- return new MariaDBTransformationProvider(dialect, connection, scope, providerName);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/Mysql/MariaDBTransformationProvider.cs b/src/Migrator.Providers/Impl/Mysql/MariaDBTransformationProvider.cs
deleted file mode 100644
index afec7e37..00000000
--- a/src/Migrator.Providers/Impl/Mysql/MariaDBTransformationProvider.cs
+++ /dev/null
@@ -1,80 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.Common;
-
-using Migrator.Framework;
-
-namespace Migrator.Providers.Mysql
-{
- ///
- /// MySql transformation provider
- ///
- public class MariaDBTransformationProvider : MySqlTransformationProvider
- {
- public MariaDBTransformationProvider(Dialect dialect, string connectionString, string scope, string providerName)
- : base(dialect, connectionString, scope, providerName)
- {
- if (string.IsNullOrEmpty(providerName)) providerName = "MySql.Data.MySqlClient";
- var fac = DbProviderFactories.GetFactory(providerName);
- _connection = fac.CreateConnection();
- _connection.ConnectionString = _connectionString;
- _connection.Open();
- }
-
- public MariaDBTransformationProvider(Dialect dialect, IDbConnection connection, string scope, string providerName)
- : base(dialect, connection, scope, providerName)
- {
- }
-
- //public override void RenameColumn(string tableName, string oldColumnName, string newColumnName)
- //{
- // if (ColumnExists(tableName, newColumnName))
- // {
- // throw new MigrationException(String.Format("Table '{0}' has column named '{1}' already", tableName, newColumnName));
- // }
-
- // if (!ColumnExists(tableName, oldColumnName))
- // {
- // throw new MigrationException(string.Format("The table '{0}' does not have a column named '{1}'", tableName, oldColumnName));
- // }
-
- // string definition = null;
- // using (IDataReader reader = ExecuteQuery(String.Format("SHOW COLUMNS FROM {0} WHERE Field='{1}'", tableName, oldColumnName)))
- // {
- // if (reader.Read())
- // {
- // // TODO: Could use something similar to construct the columns in GetColumns
- // definition = reader["Type"].ToString();
- // if ("NO" == reader["Null"].ToString())
- // {
- // definition += " " + "NOT NULL";
- // }
-
- // if (!reader.IsDBNull(reader.GetOrdinal("Key")))
- // {
- // string key = reader["Key"].ToString();
- // if ("PRI" == key)
- // {
- // definition += " " + "PRIMARY KEY";
- // }
- // else if ("UNI" == key)
- // {
- // definition += " " + "UNIQUE";
- // }
- // }
-
- // if (!reader.IsDBNull(reader.GetOrdinal("Extra")))
- // {
- // definition += " " + reader["Extra"];
- // }
- // }
- // }
-
- // if (!String.IsNullOrEmpty(definition))
- // {
- // ExecuteNonQuery(String.Format("ALTER TABLE {0} CHANGE {1} {2} {3}", tableName, oldColumnName, newColumnName, definition));
- // }
- //}
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/Mysql/MySqlTransformationProvider.cs b/src/Migrator.Providers/Impl/Mysql/MySqlTransformationProvider.cs
deleted file mode 100644
index 26ce2fe5..00000000
--- a/src/Migrator.Providers/Impl/Mysql/MySqlTransformationProvider.cs
+++ /dev/null
@@ -1,336 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.Common;
-
-using Migrator.Framework;
-
-namespace Migrator.Providers.Mysql
-{
- ///
- /// MySql transformation provider
- ///
- public class MySqlTransformationProvider : TransformationProvider
- {
- public MySqlTransformationProvider(Dialect dialect, string connectionString, string scope, string providerName)
- : base(dialect, connectionString, null, scope) // we ignore schemas for MySql (schema == database for MySql)
- {
- if (string.IsNullOrEmpty(providerName)) providerName = "MySql.Data.MySqlClient";
- var fac = DbProviderFactoriesHelper.GetFactory(providerName, "MySql.Data", "MySql.Data.MySqlClient.MySqlClientFactory");
- _connection = fac.CreateConnection(); //new MySqlConnection(_connectionString) {ConnectionString = _connectionString};
- _connection.ConnectionString = _connectionString;
- _connection.Open();
- }
-
- public MySqlTransformationProvider(Dialect dialect, IDbConnection connection, string scope, string providerName)
- : base(dialect, connection, null, scope)
- {
- }
-
- public override void RemoveForeignKey(string table, string name)
- {
- if (ForeignKeyExists(table, name))
- {
- ExecuteNonQuery(String.Format("ALTER TABLE {0} DROP FOREIGN KEY {1}", table, _dialect.Quote(name)));
- }
- }
-
- public override void RemoveAllIndexes(string table)
- {
- string qry = string.Format(@"SELECT k.TABLE_NAME, i.CONSTRAINT_NAME, i.CONSTRAINT_TYPE
- FROM information_schema.KEY_COLUMN_USAGE k
- INNER JOIN information_schema.TABLE_CONSTRAINTS i
- ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME AND i.TABLE_NAME = k.TABLE_NAME
- WHERE k.REFERENCED_TABLE_SCHEMA='{0}' AND
- (k.REFERENCED_TABLE_NAME='{1}') OR (k.TABLE_NAME='{1}')", GetDatabase(), table);
-
- var l = new List>();
- using (IDataReader reader = ExecuteQuery(qry))
- {
- while (reader.Read())
- {
- l.Add(new Tuple(reader.GetString(0), reader.GetString(1), reader.GetString(2)));
- }
- }
-
- foreach (var tuple in l)
- {
- if (tuple.Item3 == "FOREIGN KEY")
- RemoveForeignKey(tuple.Item1, tuple.Item2);
- else if (tuple.Item3 == "PRIMARY KEY")
- {
- try
- {
- ExecuteNonQuery(String.Format("ALTER TABLE {0} DROP PRIMARY KEY", table));
- }
- catch (Exception)
- { }
- }
- else if (tuple.Item3 == "UNIQUE")
- RemoveIndex(tuple.Item1, tuple.Item2);
- }
- }
-
- public override void RemoveAllForeignKeys(string tableName, string columnName)
- {
- string qry = string.Format(@"SELECT k.TABLE_NAME, i.CONSTRAINT_NAME
- FROM information_schema.KEY_COLUMN_USAGE k
- INNER JOIN information_schema.TABLE_CONSTRAINTS i
- ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME AND i.TABLE_NAME = k.TABLE_NAME
- WHERE k.REFERENCED_TABLE_SCHEMA='{0}' AND i.CONSTRAINT_TYPE = 'FOREIGN KEY' AND
- (k.REFERENCED_TABLE_NAME='{1}' AND REFERENCED_COLUMN_NAME='{2}') OR (k.TABLE_NAME='{1}' AND COLUMN_NAME='{2}')", GetDatabase(), tableName, columnName);
-
- if (string.IsNullOrEmpty(columnName))
- {
- qry = string.Format(@"SELECT k.TABLE_NAME, i.CONSTRAINT_NAME
- FROM information_schema.KEY_COLUMN_USAGE k
- INNER JOIN information_schema.TABLE_CONSTRAINTS i
- ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME AND i.TABLE_NAME = k.TABLE_NAME
- WHERE k.REFERENCED_TABLE_SCHEMA='{0}' AND i.CONSTRAINT_TYPE = 'FOREIGN KEY' AND
- (k.REFERENCED_TABLE_NAME='{1}') OR (k.TABLE_NAME='{1}')", GetDatabase(), tableName);
- }
- var l = new List> ();
- using (IDataReader reader = ExecuteQuery(qry))
- {
- while (reader.Read())
- {
- l.Add(new Tuple(reader.GetString(0), reader.GetString(1)));
- }
- }
-
- foreach (var tuple in l)
- {
- RemoveForeignKey(tuple.Item1, tuple.Item2);
- }
- }
-
- public override void RemoveConstraint(string table, string name)
- {
- if (ConstraintExists(table, name))
- {
- ExecuteNonQuery(String.Format("ALTER TABLE {0} DROP KEY {1}", table, _dialect.Quote(name)));
- }
- }
-
- public override bool ConstraintExists(string table, string name)
- {
- if (!TableExists(table))
- return false;
-
- string sqlConstraint = string.Format("SHOW KEYS FROM {0}", table);
-
- using (IDataReader reader = ExecuteQuery(sqlConstraint))
- {
- while (reader.Read())
- {
- if (reader["Key_name"].ToString().ToLower() == name.ToLower())
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- public bool ForeignKeyExists(string table, string name)
- {
- if (!TableExists(table))
- return false;
-
- string sqlConstraint = string.Format(@"SELECT distinct i.CONSTRAINT_NAME
- FROM information_schema.TABLE_CONSTRAINTS i
- INNER JOIN information_schema.KEY_COLUMN_USAGE k
- ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME
- WHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY'
- AND i.TABLE_SCHEMA = '{1}'
- AND i.TABLE_NAME = '{0}';", table, GetDatabase());
-
- using (IDataReader reader = ExecuteQuery(sqlConstraint))
- {
- while (reader.Read())
- {
- if (reader["CONSTRAINT_NAME"].ToString().ToLower() == name.ToLower())
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- public override Index[] GetIndexes(string table)
- {
- var retVal = new List();
-
- var sql = @"SHOW INDEX FROM {0}";
-
- using (var reader = ExecuteQuery(string.Format(sql, table)))
- {
- while (reader.Read())
- {
- if (!reader.IsDBNull(1))
- {
- var idx = new Index
- {
- Name = reader.GetString(2),
- PrimaryKey = reader.GetString(2) == "PRIMARY",
- Unique = !reader.GetBoolean(1),
- };
- //var cols = reader.GetString(7);
- //cols = cols.Substring(1, cols.Length - 2);
- //idx.KeyColumns = cols.Split(',');
- retVal.Add(idx);
- }
- }
- }
-
- return retVal.ToArray();
- }
-
- public override bool PrimaryKeyExists(string table, string name)
- {
- return ConstraintExists(table, "PRIMARY");
- }
-
- public override Column[] GetColumns(string table)
- {
- var columns = new List();
- using (
- IDataReader reader =
- ExecuteQuery(
- String.Format("SHOW COLUMNS FROM {0}", table)))
- {
- while (reader.Read())
- {
- var column = new Column(reader.GetString(0), DbType.String);
- string nullableStr = reader.GetString(2);
- bool isNullable = nullableStr == "YES";
- column.ColumnProperty |= isNullable ? ColumnProperty.Null : ColumnProperty.NotNull;
-
- columns.Add(column);
- }
- }
-
- return columns.ToArray();
- }
-
- public override string[] GetTables()
- {
- var tables = new List();
- using (IDataReader reader = ExecuteQuery("SHOW TABLES"))
- {
- while (reader.Read())
- {
- tables.Add((string) reader[0]);
- }
- }
-
- return tables.ToArray();
- }
-
- public override void ChangeColumn(string table, string sqlColumn)
- {
- ExecuteNonQuery(String.Format("ALTER TABLE {0} MODIFY {1}", table, sqlColumn));
- }
-
- public override void AddTable(string name, params IDbField[] columns)
- {
- AddTable(name, "INNODB", columns);
- }
-
- public override void AddTable(string name, string engine, string columns)
- {
- string sqlCreate = string.Format("CREATE TABLE {0} ({1}) ENGINE = {2}", name, columns, engine);
- ExecuteNonQuery(sqlCreate);
- }
-
- public override void RenameColumn(string tableName, string oldColumnName, string newColumnName)
- {
- if (ColumnExists(tableName, newColumnName))
- {
- throw new MigrationException(String.Format("Table '{0}' has column named '{1}' already", tableName, newColumnName));
- }
-
- if (!ColumnExists(tableName, oldColumnName))
- {
- throw new MigrationException(string.Format("The table '{0}' does not have a column named '{1}'", tableName, oldColumnName));
- }
-
- string definition = null;
-
- bool dropPrimary = false;
-
- using (IDataReader reader = ExecuteQuery(String.Format("SHOW COLUMNS FROM {0} WHERE Field='{1}'", tableName, oldColumnName)))
- {
- if (reader.Read())
- {
- // TODO: Could use something similar to construct the columns in GetColumns
- definition = reader["Type"].ToString();
- if ("NO" == reader["Null"].ToString())
- {
- definition += " " + "NOT NULL";
- }
-
- if (!reader.IsDBNull(reader.GetOrdinal("Key")))
- {
- string key = reader["Key"].ToString();
- if ("PRI" == key)
- {
- //definition += " " + "PRIMARY KEY";
- dropPrimary = true;
- }
- else if ("UNI" == key)
- {
- definition += " " + "UNIQUE";
- }
- }
-
- if (!reader.IsDBNull(reader.GetOrdinal("Extra")))
- {
- definition += " " + reader["Extra"];
- }
- }
- }
-
- if (!String.IsNullOrEmpty(definition))
- {
- if (dropPrimary)
- ExecuteNonQuery(String.Format("ALTER TABLE {0} DROP PRIMARY KEY", tableName));
- ExecuteNonQuery(String.Format("ALTER TABLE {0} CHANGE {1} {2} {3}", tableName, oldColumnName, newColumnName, definition));
- if (dropPrimary)
- ExecuteNonQuery(String.Format("ALTER TABLE {0} ADD PRIMARY KEY({1});", tableName, newColumnName));
-
- }
- }
-
- public string GetDatabase()
- {
- return ExecuteScalar("SELECT DATABASE()") as string;
- }
-
- public override void RemoveIndex(string table, string name)
- {
- if (IndexExists(table, name))
- {
- ExecuteNonQuery(String.Format("DROP INDEX {1} ON {0}", table, _dialect.Quote(name)));
- }
- }
-
- public override List GetDatabases()
- {
- return ExecuteStringQuery("SHOW DATABASES");
- }
-
- public override bool IndexExists(string table, string name)
- {
- return ConstraintExists(table, name);
- }
-
- public override string Concatenate(params string[] strings)
- {
- return "CONCAT(" + string.Join(", ", strings) + ")";
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/Mysql/MysqlDialect.cs b/src/Migrator.Providers/Impl/Mysql/MysqlDialect.cs
deleted file mode 100644
index 092b3438..00000000
--- a/src/Migrator.Providers/Impl/Mysql/MysqlDialect.cs
+++ /dev/null
@@ -1,100 +0,0 @@
-using System;
-using System.Data;
-using Migrator.Framework;
-
-namespace Migrator.Providers.Mysql
-{
- public class MysqlDialect : Dialect
- {
- public MysqlDialect()
- {
- // TODO: As per http://dev.mysql.com/doc/refman/5.0/en/char.html 5.0.3 and above
- // can handle varchar(n) up to a length OF 65,535 - so the limit of 255 should no longer apply.
-
- RegisterColumnType(DbType.AnsiStringFixedLength, "CHAR(255)");
- RegisterColumnType(DbType.AnsiStringFixedLength, 255, "CHAR($l)");
- RegisterColumnType(DbType.AnsiStringFixedLength, 65535, "TEXT");
- RegisterColumnType(DbType.AnsiStringFixedLength, 16777215, "MEDIUMTEXT");
- RegisterColumnType(DbType.AnsiString, "VARCHAR(255)");
- RegisterColumnType(DbType.AnsiString, 255, "VARCHAR($l)");
- RegisterColumnType(DbType.AnsiString, 256, "VARCHAR(255)");
- RegisterColumnType(DbType.AnsiString, 65535, "TEXT");
- RegisterColumnType(DbType.AnsiString, 16777215, "MEDIUMTEXT");
- RegisterColumnType(DbType.Binary, "LONGBLOB");
- RegisterColumnType(DbType.Binary, 127, "TINYBLOB");
- RegisterColumnType(DbType.Binary, 65535, "BLOB");
- RegisterColumnType(DbType.Binary, 16777215, "MEDIUMBLOB");
- RegisterColumnType(DbType.Boolean, "TINYINT(1)");
- RegisterColumnType(DbType.Byte, "TINYINT UNSIGNED");
- RegisterColumnType(DbType.Currency, "MONEY");
- RegisterColumnType(DbType.Date, "DATE");
- RegisterColumnType(DbType.DateTime, "DATETIME");
- RegisterColumnType(DbType.DateTimeOffset, "DATETIME");
- RegisterColumnType(DbType.Decimal, "NUMERIC(19,5)");
- RegisterColumnType(DbType.Decimal, 19, "NUMERIC(19, $l)");
- RegisterColumnType(DbType.Double, "DOUBLE");
- RegisterColumnType(DbType.Guid, "VARCHAR(40)");
- RegisterColumnType(DbType.Int16, "SMALLINT");
- RegisterColumnType(DbType.Int32, "INTEGER");
- RegisterColumnType(DbType.Int64, "BIGINT");
- RegisterColumnType(DbType.UInt16, "INTEGER");
- RegisterColumnType(DbType.UInt32, "BIGINT");
- RegisterColumnType(DbType.UInt64, "NUMERIC(20,0)");
- RegisterColumnType(DbType.Single, "FLOAT");
- RegisterColumnType(DbType.StringFixedLength, "CHAR(255)");
- RegisterColumnType(DbType.StringFixedLength, 255, "CHAR($l)");
- RegisterColumnType(DbType.StringFixedLength, 65535, "TEXT");
- RegisterColumnType(DbType.StringFixedLength, 16777215, "MEDIUMTEXT");
- RegisterColumnType(DbType.String, "VARCHAR(255)");
- RegisterColumnType(DbType.String, 65535, "VARCHAR($l)");
- //RegisterColumnType(DbType.String, 256, "VARCHAR(255)");
- //RegisterColumnType(DbType.String, 256, "VARCHAR(255)");
- //RegisterColumnType(DbType.String, 65535, "TEXT");
- RegisterColumnType(DbType.String, 16777215, "MEDIUMTEXT");
- //RegisterColumnType(DbType.String, 1073741823, "LONGTEXT");
- RegisterColumnType(DbType.String, int.MaxValue, "LONGTEXT");
- RegisterColumnType(DbType.Time, "TIME");
-
- RegisterProperty(ColumnProperty.Unsigned, "UNSIGNED");
- RegisterProperty(ColumnProperty.Identity, "AUTO_INCREMENT");
- RegisterProperty(ColumnProperty.CaseSensitive, "BINARY");
-
- RegisterUnsignedCompatible(DbType.Int16);
- RegisterUnsignedCompatible(DbType.Int32);
- RegisterUnsignedCompatible(DbType.Int64);
- RegisterUnsignedCompatible(DbType.Decimal);
- RegisterUnsignedCompatible(DbType.Double);
- RegisterUnsignedCompatible(DbType.Single);
-
- AddReservedWords("KEY", "MAXVALUE");
- }
-
- public override string QuoteTemplate
- {
- get { return "`{0}`"; }
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, string connectionString,
- string defaultSchema, string scope, string providerName)
- {
- return new MySqlTransformationProvider(dialect, connectionString, scope, providerName);
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, IDbConnection connection,
- string defaultSchema,
- string scope, string providerName)
- {
- return new MySqlTransformationProvider(dialect, connection, scope, providerName);
- }
-
- public override string Default(object defaultValue)
- {
- if (defaultValue.GetType().Equals(typeof (bool)))
- {
- defaultValue = ((bool) defaultValue) ? 1 : 0;
- }
-
- return base.Default(defaultValue);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/Oracle/MsOracleDialect.cs b/src/Migrator.Providers/Impl/Oracle/MsOracleDialect.cs
deleted file mode 100644
index 138aaf57..00000000
--- a/src/Migrator.Providers/Impl/Oracle/MsOracleDialect.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-using System;
-using System.Data;
-using Migrator.Framework;
-using Migrator.Providers.Impl.Oracle;
-
-namespace Migrator.Providers.Oracle
-{
- public class MsOracleDialect : OracleDialect
- {
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope, string providerName)
- {
- return new MsOracleTransformationProvider(dialect, connectionString, defaultSchema, scope, providerName);
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, IDbConnection connection,
- string defaultSchema,
- string scope, string providerName)
- {
- return new MsOracleTransformationProvider(dialect, connection, defaultSchema, scope, providerName);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/Oracle/MsOracleTransformationProvider.cs b/src/Migrator.Providers/Impl/Oracle/MsOracleTransformationProvider.cs
deleted file mode 100644
index 0fb213a9..00000000
--- a/src/Migrator.Providers/Impl/Oracle/MsOracleTransformationProvider.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.Common;
-using System.Linq;
-using System.Text;
-using Migrator.Framework;
-
-namespace Migrator.Providers.Oracle
-{
- public class MsOracleTransformationProvider : OracleTransformationProvider
- {
- public MsOracleTransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope, string providerName)
- : base(dialect, connectionString, defaultSchema, scope, providerName)
- {
-
- }
-
- public MsOracleTransformationProvider(Dialect dialect, IDbConnection connection, string defaultSchema, string scope, string providerName)
- : base(dialect, connection, defaultSchema, scope, providerName)
- {
- }
-
- protected override void CreateConnection(string providerName)
- {
- if (string.IsNullOrEmpty(providerName)) providerName = "System.Data.OracleClient";
- var fac = DbProviderFactories.GetFactory(providerName);
- _connection = fac.CreateConnection(); // new OracleConnection();
- _connection.ConnectionString = _connectionString;
- _connection.Open();
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/Oracle/OracleColumnPropertiesMapper.cs b/src/Migrator.Providers/Impl/Oracle/OracleColumnPropertiesMapper.cs
deleted file mode 100644
index bcc0590b..00000000
--- a/src/Migrator.Providers/Impl/Oracle/OracleColumnPropertiesMapper.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-using System;
-using System.Collections.Generic;
-using Migrator.Framework;
-
-namespace Migrator.Providers.Impl.Oracle
-{
- public class OracleColumnPropertiesMapper : ColumnPropertiesMapper
- {
- public OracleColumnPropertiesMapper(Dialect dialect, string type) : base(dialect, type)
- {
- }
-
- public override void MapColumnProperties(Column column)
- {
- Name = column.Name;
-
- indexed = PropertySelected(column.ColumnProperty, ColumnProperty.Indexed);
-
- var vals = new List();
-
- AddName(vals);
-
- AddType(vals);
-
- AddIdentity(column, vals);
-
- AddUnsigned(column, vals);
-
- AddPrimaryKey(column, vals);
-
- AddIdentityAgain(column, vals);
-
- AddUnique(column, vals);
-
- AddForeignKey(column, vals);
-
- AddDefaultValue(column, vals);
-
- // null / not-null comes last on Oracle - otherwise if use Null/Not-null + default, bad things happen
- // (http://geekswithblogs.net/faizanahmad/archive/2009/08/07/add-new-columnfield-in-oracle-db-table---ora.aspx)
-
- AddNotNull(column, vals);
-
- AddNull(column, vals);
-
- columnSql = String.Join(" ", vals.ToArray());
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/Oracle/OracleDialect.cs b/src/Migrator.Providers/Impl/Oracle/OracleDialect.cs
deleted file mode 100644
index fc3c03df..00000000
--- a/src/Migrator.Providers/Impl/Oracle/OracleDialect.cs
+++ /dev/null
@@ -1,117 +0,0 @@
-using System;
-using System.Data;
-using Migrator.Framework;
-using Migrator.Providers.Impl.Oracle;
-
-namespace Migrator.Providers.Oracle
-{
- public class OracleDialect : Dialect
- {
- public OracleDialect()
- {
- RegisterColumnType(DbType.AnsiStringFixedLength, "CHAR(255)");
- RegisterColumnType(DbType.AnsiStringFixedLength, 2000, "CHAR($l)");
- RegisterColumnType(DbType.AnsiString, "VARCHAR2(255)");
- RegisterColumnType(DbType.AnsiString, 2000, "VARCHAR2($l)");
- RegisterColumnType(DbType.AnsiString, 2147483647, "CLOB"); // should use the IType.ClobType
- RegisterColumnType(DbType.Binary, "RAW(2000)");
- RegisterColumnType(DbType.Binary, 2000, "RAW($l)");
- RegisterColumnType(DbType.Binary, 2147483647, "BLOB");
- RegisterColumnType(DbType.Boolean, "NUMBER(1,0)");
- RegisterColumnType(DbType.Byte, "NUMBER(3,0)");
- RegisterColumnType(DbType.Currency, "NUMBER(19,1)");
- RegisterColumnType(DbType.Date, "DATE");
- RegisterColumnType(DbType.DateTime, "TIMESTAMP(4)");
- RegisterColumnType(DbType.DateTimeOffset, "TIMESTAMP(4)");
- RegisterColumnType(DbType.Decimal, "NUMBER(19,5)");
- RegisterColumnType(DbType.Decimal, 19, "NUMBER(19, $l)");
- // having problems with both ODP and OracleClient from MS not being able
- // to read values out of a field that is DOUBLE PRECISION
- RegisterColumnType(DbType.Double, "DOUBLE PRECISION"); //"FLOAT(53)" );
- //RegisterColumnType(DbType.Guid, "CHAR(38)");
- RegisterColumnType(DbType.Int16, "NUMBER(5,0)");
- RegisterColumnType(DbType.Int32, "NUMBER(10,0)");
- RegisterColumnType(DbType.Int64, "NUMBER(20,0)");
- RegisterColumnType(DbType.UInt16, "NUMBER(5,0)");
- RegisterColumnType(DbType.UInt32, "NUMBER(10,0)");
- RegisterColumnType(DbType.UInt64, "NUMBER(20,0)");
- RegisterColumnType(DbType.Single, "FLOAT(24)");
- RegisterColumnType(DbType.StringFixedLength, "NCHAR(255)");
- RegisterColumnType(DbType.StringFixedLength, 2000, "NCHAR($l)");
- RegisterColumnType(DbType.String, "NVARCHAR2(255)");
- RegisterColumnType(DbType.String, 2000, "NVARCHAR2($l)");
- //RegisterColumnType(DbType.String, 1073741823, "NCLOB");
- RegisterColumnType(DbType.String, int.MaxValue, "NCLOB");
- RegisterColumnType(DbType.Time, "DATE");
- RegisterColumnType(DbType.Guid, "RAW(16)");
-
- // the original Migrator.Net code had this, but it's a bad idea - when
- // apply a "null" migration to a "not-null" field, it just leaves it as "not-null" and silent fails
- // because Oracle doesn't consider ALTER TABLE
MODIFY (column ) as being a request to make the field null.
-
- //RegisterProperty(ColumnProperty.Null, String.Empty);
-
- AddReservedWords("ACCOUNT", "ACTIVATE", "ADMIN", "ADVISE", "AFTER", "ALL_ROWS", "ALLOCATE", "ANALYZE", "ARCHIVE", "ARCHIVELOG", "ARRAY", "AT", "AUTHENTICATED", "AUTHORIZATION", "AUTOEXTEND", "AUTOMATIC", "BACKUP", "BECOME", "BEFORE", "BEGIN", "BFILE", "BITMAP", "BLOB", "BLOCK", "BODY", "CACHE", "CACHE_INSTANCES", "CANCEL", "CASCADE", "CAST", "CFILE", "CHAINED", "CHANGE", "CHAR_CS", "CHARACTER", "CHECKPOINT", "CHOOSE", "CHUNK", "CLEAR", "CLOB", "CLONE", "CLOSE", "CLOSE_CACHED_OPEN_CURSORS", "COALESCE", "COLUMNS", "COMMIT", "COMMITTED", "COMPATIBILITY", "COMPILE", "COMPLETE", "COMPOSITE_LIMIT", "COMMENT", "COMPUTE", "CONNECT_TIME", "CONSTRAINT", "CONSTRAINTS", "CONTENTS", "CONTINUE", "CONTROLFILE", "CONVERT", "COST", "CPU_PER_CALL", "CPU_PER_SESSION", "CURRENT_SCHEMA", "CURREN_USER", "CURSOR", "CYCLE", "DANGLING", "DATABASE", "DATAFILE", "DATAFILES", "DATAOBJNO", "DBA", "DBHIGH", "DBLOW", "DBMAC", "DEALLOCATE", "DEBUG", "DEC", "DECLARE", "DEFERRABLE", "DEFERRED", "DEGREE", "DEREF", "DIRECTORY", "DISABLE", "DISCONNECT", "DISMOUNT", "DISTRIBUTED", "DML", "DOUBLE", "DUMP", "EACH", "ENABLE", "END", "ENFORCE", "ENTRY", "ESCAPE", "EXCEPT", "EXCEPTIONS", "EXCHANGE", "EXCLUDING", "EXECUTE", "EXPIRE", "EXPLAIN", "EXTENT", "EXTENTS", "EXTERNALLY", "FAILED_LOGIN_ATTEMPTS", "FALSE", "FAST", "FIRST_ROWS", "FLAGGER", "FLOB", "FLUSH", "FORCE", "FOREIGN", "FREELIST", "FREELISTS", "FULL", "FUNCTION", "GLOBAL", "GLOBALLY", "GLOBAL_NAME", "GROUPS", "HASH", "HASHKEYS", "HEADER", "HEAP", "IDGENERATORS", "IDLE_TIME", "IF", "INCLUDING", "INDEXED", "INDEXES", "INDICATOR", "IND_PARTITION", "INITIALLY", "INITRANS", "INSTANCE", "INSTANCES", "INSTEAD", "INT", "INTERMEDIATE", "ISOLATION", "ISOLATION_LEVEL", "KEEP", "KEY", "KILL", "LABEL", "LAYER", "LESS", "LIBRARY", "LIMIT", "LINK", "LIST", "LOB", "LOCAL", "LOCKED", "LOG", "LOGFILE", "LOGGING", "LOGICAL_READS_PER_CALL", "LOGICAL_READS_PER_SESSION", "MANAGE", "MASTER", "MAX", "MAXARCHLOGS", "MAXDATAFILES", "MAXINSTANCES", "MAXLOGFILES", "MAXLOGHISTORY", "MAXLOGMEMBERS", "MAXSIZE", "MAXTRANS", "MAXVALUE", "MIN", "MEMBER", "MINIMUM", "MINEXTENTS", "MINVALUE", "MLS_LABEL_FORMAT", "MOUNT", "MOVE", "MTS_DISPATCHERS", "MULTISET", "NATIONAL", "NCHAR", "NCHAR_CS", "NCLOB", "NEEDED", "NESTED", "NETWORK", "NEW", "NEXT", "NOARCHIVELOG", "NOCACHE", "NOCYCLE", "NOFORCE", "NOLOGGING", "NOMAXVALUE", "NOMINVALUE", "NONE", "NOORDER", "NOOVERRIDE", "NOPARALLEL", "NOPARALLEL", "NOREVERSE", "NORMAL", "NOSORT", "NOTHING", "NUMERIC", "NVARCHAR2", "OBJECT", "OBJNO", "OBJNO_REUSE", "OFF", "OID", "OIDINDEX", "OLD", "ONLY", "OPCODE", "OPEN", "OPTIMAL", "OPTIMIZER_GOAL", "ORGANIZATION", "OSLABEL", "OVERFLOW", "OWN", "PACKAGE", "PARALLEL", "PARTITION", "PASSWORD", "PASSWORD_GRACE_TIME", "PASSWORD_LIFE_TIME", "PASSWORD_LOCK_TIME", "PASSWORD_REUSE_MAX", "PASSWORD_REUSE_TIME", "PASSWORD_VERIFY_FUNCTION", "PCTINCREASE", "PCTTHRESHOLD", "PCTUSED", "PCTVERSION", "PERCENT", "PERMANENT", "PLAN", "PLSQL_DEBUG", "POST_TRANSACTION", "PRECISION", "PRESERVE", "PRIMARY", "PRIVATE", "PRIVATE_SGA", "PRIVILEGE", "PROCEDURE", "PROFILE", "PURGE", "QUEUE", "QUOTA", "RANGE", "RBA", "READ", "READUP", "REAL", "REBUILD", "RECOVER", "RECOVERABLE", "RECOVERY", "REF", "REFERENCES", "REFERENCING", "REFRESH", "REPLACE", "RESET", "RESETLOGS", "RESIZE", "RESTRICTED", "RETURN", "RETURNING", "REUSE", "REVERSE", "ROLE", "ROLES", "ROLLBACK", "RULE", "SAMPLE", "SAVEPOINT", "SB4", "SCAN_INSTANCES", "SCHEMA", "SCN", "SCOPE", "SD_ALL", "SD_INHIBIT", "SD_SHOW", "SEGMENT", "SEG_BLOCK", "SEG_FILE", "SEQUENCE", "SERIALIZABLE", "SESSION_CACHED_CURSORS", "SESSIONS_PER_USER", "SIZE", "SHARED", "SHARED_POOL", "SHRINK", "SKIP", "SKIP_UNUSABLE_INDEXES", "SNAPSHOT", "SOME", "SORT", "SPECIFICATION", "SPLIT", "SQL_TRACE", "STANDBY", "STATEMENT_ID", "STATISTICS", "STOP", "STORAGE", "STORE", "STRUCTURE", "SWITCH", "SYS_OP_ENFORCE_NOT_NULL$", "SYS_OP_NTCIMG$", "SYSDBA", "SYSOPER", "SYSTEM", "TABLES", "TABLESPACE", "TABLESPACE_NO", "TABNO", "TEMPORARY", "THAN", "THE", "THREAD", "TIMESTAMP", "TIME", "TOPLEVEL", "TRACE", "TRACING", "TRANSACTION", "TRANSITIONAL", "TRIGGERS", "TRUE", "TRUNCATE", "TX", "TYPE", "UB2", "UBA", "UNARCHIVED", "UNDO", "UNLIMITED", "UNLOCK", "UNRECOVERABLE", "UNTIL", "UNUSABLE", "UNUSED", "UPDATABLE", "USAGE", "USE", "USING", "VALIDATION", "VALUE", "VALUES", "VARYING", "WHEN", "WITHOUT", "WORK", "WRITE", "WRITEDOWN", "WRITEUP", "XID", "YEAR", "ZONE");
- }
-
- // in Oracle, this: ALTER TABLE EXTERNALSYSTEMREFERENCES MODIFY (TestScriptId RAW(16)) will no make the column nullable, it just leaves it at it's current null/not-null state
-
- public override bool NeedsNullForNullableWhenAlteringTable
- {
- get { return true; }
- }
-
- public override bool ColumnNameNeedsQuote
- {
- get { return false; }
- }
-
- public override bool ConstraintNameNeedsQuote
- {
- get { return false; }
- }
- public override bool TableNameNeedsQuote
- {
- get { return false; }
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope, string providerName)
- {
- return new OracleTransformationProvider(dialect, connectionString, defaultSchema, scope, providerName);
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, IDbConnection connection,
- string defaultSchema,
- string scope, string providerName)
- {
- return new OracleTransformationProvider(dialect, connection, defaultSchema, scope, providerName);
- }
-
- public override ColumnPropertiesMapper GetColumnMapper(Column column)
- {
- string type = column.Size > 0 ? GetTypeName(column.Type, column.Size) : GetTypeName(column.Type);
- if (!IdentityNeedsType && column.IsIdentity)
- type = String.Empty;
-
- return new OracleColumnPropertiesMapper(this, type);
- }
-
- public override string Default(object defaultValue)
- {
- if (defaultValue.GetType().Equals(typeof(bool)))
- {
- return String.Format("DEFAULT {0}", (bool)defaultValue ? "1" : "0");
- }
- else if (defaultValue is Guid)
- {
- return String.Format("DEFAULT HEXTORAW('{0}')", defaultValue.ToString().Replace("-",""));
- }
- else if (defaultValue is DateTime)
- {
- return String.Format("DEFAULT TO_TIMESTAMP('{0}', 'YYYY-MM-DD HH24:MI:SS.FF')", ((DateTime)defaultValue).ToString("yyyy-MM-dd HH:mm:ss.ff"));
- }
-
- return base.Default(defaultValue);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/Oracle/OracleTransformationProvider.cs b/src/Migrator.Providers/Impl/Oracle/OracleTransformationProvider.cs
deleted file mode 100644
index 4607abe9..00000000
--- a/src/Migrator.Providers/Impl/Oracle/OracleTransformationProvider.cs
+++ /dev/null
@@ -1,584 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.Common;
-using System.Linq;
-using System.Text;
-using Migrator.Framework;
-
-namespace Migrator.Providers.Oracle
-{
- public class OracleTransformationProvider : TransformationProvider
- {
- public const string TemporaryColumnName = "TEMPCOL";
-
- public OracleTransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope, string providerName)
- : base(dialect, connectionString, defaultSchema, scope)
- {
- this.CreateConnection(providerName);
- }
-
- public OracleTransformationProvider(Dialect dialect, IDbConnection connection, string defaultSchema, string scope, string providerName)
- : base(dialect, connection, defaultSchema, scope)
- {
- }
-
- protected virtual void CreateConnection(string providerName)
- {
- if (string.IsNullOrEmpty(providerName)) providerName = "Oracle.DataAccess.Client";
- var fac = DbProviderFactories.GetFactory(providerName);
- _connection = fac.CreateConnection(); // new OracleConnection();
- _connection.ConnectionString = _connectionString;
- _connection.Open();
- }
-
- public override void DropDatabases(string databaseName)
- {
- if (string.IsNullOrEmpty(databaseName))
- ExecuteNonQuery(string.Format("DROP DATABASE"));
- }
-
- public override void AddForeignKey(string name, string primaryTable, string[] primaryColumns, string refTable,
- string[] refColumns, ForeignKeyConstraintType constraint)
- {
- GuardAgainstMaximumIdentifierLengthForOracle(name);
-
- if (ConstraintExists(primaryTable, name))
- {
- Logger.Warn("Constraint {0} already exists", name);
- return;
- }
-
- primaryTable = QuoteTableNameIfRequired(primaryTable);
- refTable = QuoteTableNameIfRequired(refTable);
- string primaryColumnsSql = String.Join(",", primaryColumns.Select(col => QuoteColumnNameIfRequired(col)).ToArray());
- string refColumnsSql = String.Join(",", refColumns.Select(col => QuoteColumnNameIfRequired(col)).ToArray());
-
- ExecuteNonQuery(String.Format("ALTER TABLE {0} ADD CONSTRAINT {1} FOREIGN KEY ({2}) REFERENCES {3} ({4})", primaryTable, name, primaryColumnsSql, refTable, refColumnsSql));
- }
-
- void GuardAgainstMaximumIdentifierLengthForOracle(string name)
- {
- if (name.Length > 30)
- {
- throw new ArgumentException(string.Format("The name \"{0}\" is {1} characters in length, bug maximum length for Oracle identifier is 30 characters.", name, name.Length), "name");
- }
- }
-
- protected override string getPrimaryKeyname(string tableName)
- {
- return tableName.Length > 27 ? "PK_" + tableName.Substring(0, 27) : "PK_" + tableName;
- }
-
- public override void ChangeColumn(string table, Column column)
- {
- if (!ColumnExists(table, column.Name))
- {
- Logger.Warn("Column {0}.{1} does not exist", table, column.Name);
- return;
- }
-
- var existingColumn = GetColumnByName(table, column.Name);
-
- if (column.Type == DbType.String)
- {
- RenameColumn(table, column.Name, TemporaryColumnName);
-
- // check if this is not-null
- bool isNotNull = (column.ColumnProperty & ColumnProperty.NotNull) == ColumnProperty.NotNull;
-
- // remove the not-null option
- column.ColumnProperty = (column.ColumnProperty & ~ColumnProperty.NotNull);
-
- AddColumn(table, column);
- CopyDataFromOneColumnToAnother(table, TemporaryColumnName, column.Name);
- RemoveColumn(table, TemporaryColumnName);
- //RenameColumn(table, TemporaryColumnName, column.Name);
-
- string columnName = QuoteColumnNameIfRequired(column.Name);
-
- // now set the column to not-null
- if (isNotNull) ExecuteQuery(String.Format("ALTER TABLE {0} MODIFY ({1} NOT NULL)", table, columnName));
- }
- else
- {
- if (((existingColumn.ColumnProperty & ColumnProperty.NotNull) == ColumnProperty.NotNull)
- && ((column.ColumnProperty & ColumnProperty.NotNull) == ColumnProperty.NotNull))
- {
- // was not null, and is being change to not-null - drop the not-null all together
- column.ColumnProperty = column.ColumnProperty & ~ColumnProperty.NotNull;
- }
- else if
- (((existingColumn.ColumnProperty & ColumnProperty.Null) == ColumnProperty.Null)
- && ((column.ColumnProperty & ColumnProperty.Null) == ColumnProperty.Null))
- {
- // was null, and is being changed to null - drop the null all together
- column.ColumnProperty = column.ColumnProperty & ~ColumnProperty.Null;
- }
-
- ColumnPropertiesMapper mapper = _dialect.GetAndMapColumnProperties(column);
-
- ChangeColumn(table, mapper.ColumnSql);
- }
- }
-
- void CopyDataFromOneColumnToAnother(string table, string fromColumn, string toColumn)
- {
- table = QuoteTableNameIfRequired(table);
- fromColumn = QuoteColumnNameIfRequired(fromColumn);
- toColumn = QuoteColumnNameIfRequired(toColumn);
-
- ExecuteNonQuery(string.Format("UPDATE {0} SET {1} = {2}", table, toColumn, fromColumn));
- }
-
- public override void RenameTable(string oldName, string newName)
- {
- GuardAgainstMaximumIdentifierLengthForOracle(newName);
- GuardAgainstExistingTableWithSameName(newName, oldName);
-
- oldName = QuoteTableNameIfRequired(oldName);
- newName = QuoteTableNameIfRequired(newName);
-
- ExecuteNonQuery(String.Format("ALTER TABLE {0} RENAME TO {1}", oldName, newName));
- }
-
- void GuardAgainstExistingTableWithSameName(string newName, string oldName)
- {
- if (TableExists(newName)) throw new MigrationException(string.Format("Can not rename table \"{0}\" to \"{1}\", a table with that name already exists", oldName, newName));
- }
-
- public override void RenameColumn(string tableName, string oldColumnName, string newColumnName)
- {
- GuardAgainstMaximumIdentifierLengthForOracle(newColumnName);
- GuardAgainstExistingColumnWithSameName(newColumnName, tableName);
-
- tableName = QuoteTableNameIfRequired(tableName);
- oldColumnName = QuoteColumnNameIfRequired(oldColumnName);
- newColumnName = QuoteColumnNameIfRequired(newColumnName);
-
- ExecuteNonQuery(string.Format("ALTER TABLE {0} RENAME COLUMN {1} TO {2}", tableName, oldColumnName, newColumnName));
- }
-
- void GuardAgainstExistingColumnWithSameName(string newColumnName, string tableName)
- {
- if (ColumnExists(tableName, newColumnName)) throw new MigrationException(string.Format("A column with the name \"{0}\" already exists in the table \"{1}\"", newColumnName, tableName));
- }
-
- public override void ChangeColumn(string table, string sqlColumn)
- {
- if (string.IsNullOrEmpty(table)) throw new ArgumentNullException("table");
- if (string.IsNullOrEmpty(table)) throw new ArgumentNullException("sqlColumn");
-
- table = QuoteTableNameIfRequired(table);
- sqlColumn = QuoteColumnNameIfRequired(sqlColumn);
- ExecuteNonQuery(String.Format("ALTER TABLE {0} MODIFY {1}", table, sqlColumn));
- }
-
- public override void AddColumn(string table, string sqlColumn)
- {
- GuardAgainstMaximumIdentifierLengthForOracle(table);
- table = QuoteTableNameIfRequired(table);
- sqlColumn = QuoteColumnNameIfRequired(sqlColumn);
- ExecuteNonQuery(String.Format("ALTER TABLE {0} ADD {1}", table, sqlColumn));
- }
-
- public override string[] GetConstraints(string table)
- {
- var constraints = new List();
- //using (
- // IDataReader reader =
- // ExecuteQuery(
- // String.Format("SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE LOWER(TABLE_NAME) = LOWER('{0}')", table)))
- //{
- // while (reader.Read())
- // {
- // constraints.Add(reader.GetString(0));
- // }
- //}
-
- using (
- IDataReader reader =
- ExecuteQuery(
- String.Format("SELECT constraint_name FROM user_constraints WHERE lower(table_name) = '{0}'", table.ToLower())))
- {
- while (reader.Read())
- {
- constraints.Add(reader.GetString(0));
- }
- }
-
- return constraints.ToArray();
- }
-
- protected override string GetPrimaryKeyConstraintName(string table)
- {
- var constraints = new List();
-
- using (
- IDataReader reader =
- ExecuteQuery(
- String.Format("SELECT constraint_name FROM user_constraints WHERE lower(table_name) = '{0}' and constraint_type = 'P'", table.ToLower())))
- {
- while (reader.Read())
- {
- constraints.Add(reader.GetString(0));
- }
- }
-
- return constraints.FirstOrDefault();
- }
-
- public override bool ConstraintExists(string table, string name)
- {
- string sql =
- string.Format(
- "SELECT COUNT(constraint_name) FROM user_constraints WHERE lower(constraint_name) = '{0}' AND lower(table_name) = '{1}'",
- name.ToLower(), table.ToLower());
- Logger.Log(sql);
- object scalar = ExecuteScalar(sql);
- return Convert.ToInt32(scalar) == 1;
- }
-
- public override bool ColumnExists(string table, string column)
- {
- if (!TableExists(table))
- return false;
-
- string sql =
- string.Format(
- "SELECT COUNT(column_name) FROM user_tab_columns WHERE lower(table_name) = '{0}' AND lower(column_name) = '{1}'",
- table.ToLower(), column.ToLower());
- Logger.Log(sql);
- object scalar = ExecuteScalar(sql);
- return Convert.ToInt32(scalar) == 1;
- }
-
- public override bool TableExists(string table)
- {
- string sql = string.Format("SELECT COUNT(table_name) FROM user_tables WHERE lower(table_name) = '{0}'", table.ToLower());
-
- if (_defaultSchema != null)
- sql = string.Format("SELECT COUNT(table_name) FROM user_tables WHERE lower(owner) = '{0}' and lower(table_name) = '{1}'", _defaultSchema.ToLower(), table.ToLower());
-
- Logger.Log(sql);
- object count = ExecuteScalar(sql);
- return Convert.ToInt32(count) == 1;
- }
-
- public override List GetDatabases()
- {
- throw new NotImplementedException();
- }
-
- public override string[] GetTables()
- {
- var tables = new List();
-
- using (IDataReader reader =
- ExecuteQuery("SELECT table_name FROM user_tables"))
- {
- while (reader.Read())
- {
- tables.Add(reader[0].ToString());
- }
- }
-
- return tables.ToArray();
- }
-
- //public override List AppliedMigrations
- //{
- // get
- // {
- // if (_appliedMigrations == null)
- // {
- // _appliedMigrations = new List();
- // CreateSchemaInfoTable();
- // using (IDataReader reader = Select(QuoteColumnNameIfRequired("Version"), SchemaInfoTableName))
- // {
- // while (reader.Read())
- // {
- // _appliedMigrations.Add(Convert.ToInt64(reader.GetValue(0)));
- // }
- // }
- // }
- // return _appliedMigrations;
- // }
- //}
-
- public override Column[] GetColumns(string table)
- {
- var columns = new List();
-
- using (
- IDataReader reader =
- ExecuteQuery(
- string.Format(
- "select column_name, data_type, data_length, data_precision, data_scale, NULLABLE FROM USER_TAB_COLUMNS WHERE lower(table_name) = '{0}'",
- table.ToLower())))
- {
- while (reader.Read())
- {
- string colName = reader[0].ToString();
- DbType colType = DbType.String;
- string dataType = reader[1].ToString().ToLower();
- bool isNullable = ParseBoolean(reader.GetValue(5));
-
- if (dataType.Equals("number"))
- {
- int precision = Convert.ToInt32(reader.GetValue(3));
- int scale = Convert.ToInt32(reader.GetValue(4));
- if (scale == 0)
- {
- colType = precision <= 10 ? DbType.Int16 : DbType.Int64;
- }
- else
- {
- colType = DbType.Decimal;
- }
- }
- else if (dataType.StartsWith("timestamp") || dataType.Equals("date"))
- {
- colType = DbType.DateTime;
- }
-
- var columnProperties = (isNullable) ? ColumnProperty.Null : ColumnProperty.NotNull;
-
- columns.Add(new Column(colName, colType, columnProperties));
- }
- }
-
- return columns.ToArray();
- }
-
- bool ParseBoolean(object value)
- {
- if (value is string)
- {
- if ("N" == (string)value) return false;
- if ("Y" == (string)value) return true;
- }
-
- return Convert.ToBoolean(value);
- }
-
- public override string GenerateParameterName(int index)
- {
- return ":p" + index;
- }
-
- protected override void ConfigureParameterWithValue(IDbDataParameter parameter, int index, object value)
- {
- if (value is Guid || value is Guid?)
- {
- parameter.DbType = DbType.Binary;
-
- if (value is Guid? && !((Guid?) value).HasValue)
- {
- return;
- }
-
- parameter.Value = ((Guid) value).ToByteArray();
- }
- else if (value is bool || value is bool?)
- {
- parameter.DbType = DbType.Int32;
- parameter.Value = ((bool) value) ? 1 : 0;
- }
- else if (value is UInt16)
- {
- parameter.DbType = DbType.Decimal;
- parameter.Value = value;
- }
- else if (value is UInt32)
- {
- parameter.DbType = DbType.Decimal;
- parameter.Value = value;
- }
- else if (value is UInt64)
- {
- parameter.DbType = DbType.Decimal;
- parameter.Value = value;
- }
- else
- {
- base.ConfigureParameterWithValue(parameter, index, value);
- }
- }
-
- public override void RemoveColumnDefaultValue(string table, string column)
- {
- var sql = string.Format("ALTER TABLE {0} MODIFY {1} DEFAULT NULL", table, column);
- ExecuteNonQuery(sql);
- }
-
- public override void AddTable(string name, params IDbField[] fields)
- {
- GuardAgainstMaximumIdentifierLengthForOracle(name);
-
- var columns = fields.Where(x => x is Column).Cast().ToArray();
-
- GuardAgainstMaximumColumnNameLengthForOracle(name, columns);
-
- base.AddTable(name, fields);
-
- if (columns.Any(c => c.ColumnProperty == ColumnProperty.PrimaryKeyWithIdentity))
- {
- var identityColumn = columns.First(c => c.ColumnProperty == ColumnProperty.PrimaryKeyWithIdentity);
-
- var seqTName = name.Length > 21 ? name.Substring(0, 21) : name;
- if (seqTName.EndsWith("_"))
- seqTName = seqTName.Substring(0, seqTName.Length - 1);
-
- // Create a sequence for the table
- ExecuteQuery(String.Format("CREATE SEQUENCE {0}_SEQUENCE", seqTName));
-
- // Create identity trigger (This all has to be in one line (no whitespace), I learned the hard way :) )
- ExecuteQuery(String.Format(
- @"CREATE OR REPLACE TRIGGER {0}_TRIGGER BEFORE INSERT ON {1} FOR EACH ROW BEGIN SELECT {0}_SEQUENCE.NEXTVAL INTO :NEW.{2} FROM DUAL; END;", seqTName, name, identityColumn.Name));
- }
- }
- public override void RemoveTable(string name)
- {
- base.RemoveTable(name);
- try
- {
- ExecuteQuery(String.Format(@"DROP SEQUENCE {0}_SEQUENCE", name));
- }
- catch (Exception e)
- {
- // swallow this because sequence may not have originally existed.
- }
- }
- void GuardAgainstMaximumColumnNameLengthForOracle(string name, Column[] columns)
- {
- foreach (Column column in columns)
- {
- if (column.Name.Length > 30)
- {
- throw new ArgumentException(
- string.Format("When adding table: \"{0}\", the column: \"{1}\", the name of the column is: {2} characters in length, but maximum length for an oracle identifier is 30 characters", name,
- column.Name, column.Name.Length), "columns");
- }
- }
- }
-
- public override string Encode(Guid guid)
- {
- byte[] bytes = guid.ToByteArray();
- var hex = new StringBuilder(bytes.Length*2);
- foreach (byte b in bytes) hex.AppendFormat("{0:X2}", b);
- return hex.ToString();
- }
-
- public override bool IndexExists(string table, string name)
- {
- string sql =
- string.Format(
- "SELECT COUNT(index_name) FROM user_indexes WHERE lower(index_name) = '{0}' AND lower(table_name) = '{1}'",
- name.ToLower(), table.ToLower());
- Logger.Log(sql);
- object scalar = ExecuteScalar(sql);
- return Convert.ToInt32(scalar) == 1;
- }
-
- /*///
- /// Marks a Migration attribute as having been applied
- ///
- /// The migration attribute that was applied
- public override void MigrationApplied(long version)
- {
- CreateSchemaInfoTable();
- Insert(SchemaInfoTableName, new[] { "version" }, new[] { version.ToString() });
- _appliedMigrations.Add(version);
- }
-
- ///
- /// Marks a Migration attribute as having been rolled back from the database
- ///
- /// The migration attribute that was removed
- public override void MigrationUnApplied(long version)
- {
- CreateSchemaInfoTable();
- Delete(SchemaInfoTableName, "version", version.ToString());
- _appliedMigrations.Remove(version);
- }*/
-
- //protected override void CreateSchemaInfoTable()
- //{
- // EnsureHasConnection();
- // if (!TableExists("SchemaInfo"))
- // {
- // AddTable(SchemaInfoTableName, new Column("Version", DbType.Int64, ColumnProperty.PrimaryKey));
- // }
- //}
-
- private string SchemaInfoTableName
- {
- get
- {
- if (_defaultSchema == null)
- return "SchemaInfo";
- return string.Format("{0}.{1}", _defaultSchema, "SchemaInfo");
- }
- }
-
- //protected override string GetPrimaryKeyConstraintName(string table)
- //{
- // var sql = "select constraint_name " +
- // "from user_indexes join user_constraints on user_indexes.index_name = user_constraints.constraint_name " +
- // "where lower(user_indexes.table_name) = lower('{0}') and constraint_type = 'P'";
-
- // sql = string.Format(sql, table);
-
- // using (IDataReader reader = ExecuteQuery(sql))
- // {
- // return reader.Read() ? reader.GetString(0) : null;
- // }
- //}
-
- public override Index[] GetIndexes(string table)
- {
- var sql = "select user_indexes.index_name, constraint_type, uniqueness " +
- "from user_indexes left outer join user_constraints on user_indexes.index_name = user_constraints.constraint_name " +
- "where lower(user_indexes.table_name) = lower('{0}') and index_type = 'NORMAL'";
-
- sql = string.Format(sql, table);
-
- var indexes = new List();
-
- using (IDataReader reader = ExecuteQuery(sql))
- {
- while (reader.Read())
- {
- var index = new Index
- {
- Name = reader.GetString(0),
- Unique = reader.GetString(2) == "UNIQUE" ? true : false
- };
-
- if (!reader.IsDBNull(1))
- {
- index.PrimaryKey = reader.GetString(1) == "P" ? true : false;
- }
- else
- index.PrimaryKey = false;
-
- index.Clustered = false; //???
-
- //if (!reader.IsDBNull(3)) index.KeyColumns = (reader.GetString(3).Split(','));
- //if (!reader.IsDBNull(4)) index.IncludeColumns = (reader.GetString(4).Split(','));
-
- indexes.Add(index);
- }
- }
-
- return indexes.ToArray();
- }
-
- public override string Concatenate(params string[] strings)
- {
- return string.Join(" || ", strings);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/PostgreSQL/PostgreSQL82Dialect.cs b/src/Migrator.Providers/Impl/PostgreSQL/PostgreSQL82Dialect.cs
deleted file mode 100644
index 4fe73add..00000000
--- a/src/Migrator.Providers/Impl/PostgreSQL/PostgreSQL82Dialect.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-using System.Data;
-
-namespace Migrator.Providers.PostgreSQL
-{
- public class PostgreSQL82Dialect : PostgreSQLDialect
- {
- public PostgreSQL82Dialect()
- {
- RegisterColumnType(DbType.Guid, "uuid"); // Requires postgresql 8.2 and up
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/PostgreSQL/PostgreSQLDialect.cs b/src/Migrator.Providers/Impl/PostgreSQL/PostgreSQLDialect.cs
deleted file mode 100644
index 0545c8a6..00000000
--- a/src/Migrator.Providers/Impl/PostgreSQL/PostgreSQLDialect.cs
+++ /dev/null
@@ -1,111 +0,0 @@
-using System;
-using System.Data;
-using Migrator.Framework;
-using Migrator.Providers.Oracle;
-
-namespace Migrator.Providers.PostgreSQL
-{
- public class PostgreSQLDialect : Dialect
- {
- public PostgreSQLDialect()
- {
- RegisterColumnType(DbType.AnsiStringFixedLength, "char(255)");
- RegisterColumnType(DbType.AnsiStringFixedLength, 8000, "char($l)");
- RegisterColumnType(DbType.AnsiString, "varchar(255)");
- RegisterColumnType(DbType.AnsiString, 8000, "varchar($l)");
- RegisterColumnType(DbType.AnsiString, 2147483647, "text");
- RegisterColumnType(DbType.Binary, "bytea");
- RegisterColumnType(DbType.Binary, 2147483647, "bytea");
- RegisterColumnType(DbType.Boolean, "boolean");
- RegisterColumnType(DbType.Byte, "int2");
- RegisterColumnType(DbType.Currency, "decimal(16,4)");
- RegisterColumnType(DbType.Date, "date");
- RegisterColumnType(DbType.DateTime, "timestamp");
- RegisterColumnType(DbType.DateTimeOffset, "timestamp");
- RegisterColumnType(DbType.Decimal, "decimal(19,5)");
- RegisterColumnType(DbType.Decimal, 19, "decimal(18, $l)");
- RegisterColumnType(DbType.Double, "float8");
- RegisterColumnType(DbType.Int16, "int2");
- RegisterColumnType(DbType.Int32, "int4");
- RegisterColumnType(DbType.Int64, "int8");
- RegisterColumnType(DbType.UInt16, "int4");
- RegisterColumnType(DbType.UInt32, "int8");
- RegisterColumnType(DbType.UInt64, "decimal(20,0)");
- RegisterColumnType(DbType.Single, "float4");
- RegisterColumnType(DbType.StringFixedLength, "char(255)");
- RegisterColumnType(DbType.StringFixedLength, 4000, "char($l)");
- RegisterColumnType(DbType.String, "varchar(255)");
- RegisterColumnType(DbType.String, 4000, "varchar($l)");
- RegisterColumnType(DbType.String, 1073741823, "text");
- RegisterColumnType(DbType.Time, "time");
- RegisterColumnType(DbType.Guid, "uuid");
-
- RegisterProperty(ColumnProperty.Identity, "serial");
-
- AddReservedWords("ABS", "ABSOLUTE", "ACCESS", "ACTION", "ADA", "ADD", "ADMIN", "AFTER", "AGGREGATE", "ALIAS", "ALL", "ALLOCATE", "ALTER", "ANALYSE", "ANALYZE", "AND", "ANY", "ARE",
- "ARRAY", "AS", "ASC", "ASENSITIVE", "ASSERTION", "ASSIGNMENT", "ASYMMETRIC", "AT", "ATOMIC", "AUTHORIZATION", "AVG", "BACKWARD", "BEFORE", "BEGIN", "BETWEEN", "BIGINT", "BINARY",
- "BIT", "BITVAR", "BIT_LENGTH", "BLOB", "BOOLEAN", "BOTH", "BREADTH", "BY", "C", "CACHE", "CALL", "CALLED", "CARDINALITY", "CASCADE", "CASCADED", "CASE", "CAST", "CATALOG",
- "CATALOG_NAME", "CHAIN", "CHAR", "CHARACTER", "CHARACTERISTICS", "CHARACTER_LENGTH", "CHARACTER_SET_CATALOG", "CHARACTER_SET_NAME", "CHARACTER_SET_SCHEMA", "CHAR_LENGTH",
- "CHECK", "CHECKED", "CHECKPOINT", "CLASS", "CLASS_ORIGIN", "CLOB", "CLOSE", "CLUSTER", "COALESCE", "COBOL", "COLLATE", "COLLATION", "COLLATION_CATALOG", "COLLATION_NAME",
- "COLLATION_SCHEMA", "COLUMN", "COLUMN_NAME", "COMMAND_FUNCTION", "COMMAND_FUNCTION_CODE", "COMMENT", "COMMIT", "COMMITTED", "COMPLETION", "CONDITION_NUMBER", "CONNECT",
- "CONNECTION", "CONNECTION_NAME", "CONSTRAINT", "CONSTRAINTS", "CONSTRAINT_CATALOG", "CONSTRAINT_NAME", "CONSTRAINT_SCHEMA", "CONSTRUCTOR", "CONTAINS", "CONTENTS", "CONTINUE",
- "CONVERSION",
- "CONVERT", "COPY", "CORRESPONDING", "COUNT", "CREATE", "CREATEDB", "CREATEUSER", "CROSS", "CUBE", "CURRENT", "CURRENT_DATE", "CURRENT_PATH", "CURRENT_ROLE", "CURRENT_TIME",
- "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR", "CURSOR_NAME", "CYCLE", "DATABASE", "DATE", "DATETIME_INTERVAL_CODE", "DATETIME_INTERVAL_PRECISION", "DAY", "DEALLOCATE",
- "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DEFERRABLE", "DEFERRED", "DEFINED", "DEFINER", "DELETE", "DELIMITER", "DELIMITERS", "DEPTH", "DEREF", "DESC", "DESCRIBE", "DESCRIPTOR",
- "DESTROY", "DESTRUCTOR", "DETERMINISTIC", "DIAGNOSTICS", "DICTIONARY", "DISCONNECT", "DISPATCH", "DISTINCT", "DO", "DOMAIN", "DOUBLE", "DROP", "DYNAMIC", "DYNAMIC_FUNCTION",
- "DYNAMIC_FUNCTION_CODE", "EACH", "ELSE", "ENCODING", "ENCRYPTED", "END", "END-EXEC", "EQUALS", "ESCAPE", "EVERY", "EXCEPT", "EXCEPTION", "EXCLUSIVE", "EXEC", "EXECUTE",
- "EXISTING", "EXISTS", "EXPLAIN", "EXTERNAL", "EXTRACT", "FALSE", "FETCH", "FINAL", "FIRST", "FLOAT", "FOR", "FORCE", "FOREIGN", "FORTRAN", "FORWARD", "FOUND", "FREE", "FREEZE",
- "FROM", "FULL", "FUNCTION", "G", "GENERAL", "GENERATED", "GET", "GLOBAL", "GO", "GOTO", "GRANT", "GRANTED", "GROUP", "GROUPING", "HANDLER", "HAVING", "HIERARCHY", "HOLD", "HOST",
- "HOUR", "IDENTITY", "IGNORE", "ILIKE", "IMMEDIATE", "IMMUTABLE", "IMPLEMENTATION", "IMPLICIT", "IN", "INCREMENT", "INDEX", "INDICATOR", "INFIX", "INHERITS", "INITIALIZE",
- "INITIALLY", "INNER", "INOUT", "INPUT", "INSENSITIVE", "INSERT", "INSTANCE", "INSTANTIABLE", "INSTEAD", "INT", "INTEGER", "INTERSECT", "INTERVAL", "INTO", "INVOKER", "IS",
- "ISNULL", "ISOLATION", "ITERATE", "JOIN", "K", "KEY", "KEY_MEMBER", "KEY_TYPE", "LANCOMPILER", "LANGUAGE", "LARGE", "LAST", "LATERAL", "LEADING", "LEFT", "LENGTH", "LESS",
- "LEVEL", "LIKE", "LIMIT", "LISTEN", "LOAD", "LOCAL", "LOCALTIME", "LOCALTIMESTAMP", "LOCATOR", "LOCK", "LOWER", "M", "MAP", "MATCH", "MAX", "MAXVALUE",
- "MESSAGE_LENGTH", "MESSAGE_OCTET_LENGTH", "MESSAGE_TEXT", "METHOD", "MIN", "MINUTE", "MINVALUE", "MOD", "MODE", "MODIFIES", "MODIFY", "MODULE", "MONTH", "MORE", "MOVE", "MUMPS",
- "NAMES", "NATIONAL", "NATURAL", "NCHAR", "NCLOB", "NEW", "NEXT", "NO", "NOCREATEDB", "NOCREATEUSER", "NONE", "NOT", "NOTHING", "NOTIFY", "NOTNULL", "NULL", "NULLABLE",
- "NULLIF", "NUMBER", "NUMERIC", "OBJECT", "OCTET_LENGTH", "OF", "OFF", "OFFSET", "OIDS", "OLD", "ON", "ONLY", "OPEN", "OPERATION", "OPERATOR", "OPTION", "OPTIONS", "OR", "ORDER",
- "ORDINALITY", "OUT", "OUTER", "OUTPUT", "OVERLAPS", "OVERLAY", "OVERRIDING", "OWNER", "PAD", "PARAMETER", "PARAMETERS", "PARAMETER_MODE", "PARAMETER_NAME",
- "PARAMETER_ORDINAL_POSITION", "PARAMETER_SPECIFIC_CATALOG", "PARAMETER_SPECIFIC_NAME", "PARAMETER_SPECIFIC_SCHEMA", "PARTIAL", "PASCAL", "PATH", "PENDANT", "PLACING",
- "PLI", "POSITION", "POSTFIX", "PRECISION", "PREFIX", "PREORDER", "PREPARE", "PRESERVE", "PRIMARY", "PRIOR", "PRIVILEGES", "PROCEDURAL", "PROCEDURE", "PUBLIC", "READ", "READS",
- "REAL", "RECHECK", "RECURSIVE", "REF", "REFERENCES", "REFERENCING", "REINDEX", "RELATIVE", "RENAME", "REPEATABLE", "REPLACE", "RESET", "RESTRICT", "RESULT", "RETURN",
- "RETURNED_LENGTH", "RETURNED_OCTET_LENGTH", "RETURNED_SQLSTATE", "RETURNS", "REVOKE", "RIGHT", "ROLE", "ROLLBACK", "ROLLUP", "ROUTINE", "ROUTINE_CATALOG", "ROUTINE_NAME",
- "ROUTINE_SCHEMA", "ROW", "ROWS", "ROW_COUNT", "RULE", "SAVEPOINT", "SCALE", "SCHEMA", "SCHEMA_NAME", "SCOPE", "SCROLL", "SEARCH", "SECOND", "SECTION", "SECURITY", "SELECT",
- "SELF", "SENSITIVE", "SEQUENCE", "SERIALIZABLE", "SERVER_NAME", "SESSION", "SESSION_USER", "SET", "SETOF", "SETS", "SHARE", "SHOW", "SIMILAR", "SIMPLE", "SIZE", "SMALLINT",
- "SOME", "SPACE", "SPECIFIC", "SPECIFICTYPE", "SPECIFIC_NAME", "SQL", "SQLCODE", "SQLERROR", "SQLEXCEPTION", "SQLSTATE", "SQLWARNING", "STABLE", "START",
- "STATEMENT", "STATIC", "STATISTICS", "STDIN", "STDOUT", "STORAGE", "STRICT", "STRUCTURE", "STYLE", "SUBCLASS_ORIGIN", "SUBLIST", "SUBSTRING", "SUM", "SYMMETRIC", "SYSID",
- "SYSTEM", "SYSTEM_USER", "TABLE", "TABLE_NAME", "TEMP", "TEMPLATE", "TEMPORARY", "TERMINATE", "THAN", "THEN", "TIME", "TIMESTAMP", "TIMEZONE_HOUR", "TIMEZONE_MINUTE", "TO",
- "TOAST", "TRAILING", "TRANSACTION", "TRANSACTIONS_COMMITTED", "TRANSACTIONS_ROLLED_BACK", "TRANSACTION_ACTIVE", "TRANSFORM", "TRANSFORMS", "TRANSLATE", "TRANSLATION", "TREAT",
- "TRIGGER", "TRIGGER_CATALOG", "TRIGGER_SCHEMA", "TRIM", "TRUE", "TRUNCATE", "TRUSTED", "UNCOMMITTED", "UNDER", "UNENCRYPTED", "UNION", "UNIQUE",
- "UNKNOWN", "UNLISTEN", "UNNAMED", "UNNEST", "UNTIL", "UPDATE", "UPPER", "USAGE", "USER", "USER_DEFINED_TYPE_CATALOG", "USER_DEFINED_TYPE_NAME", "USER_DEFINED_TYPE_SCHEMA",
- "USING", "VACUUM", "VALID", "VALIDATOR", "VALUES", "VARCHAR", "VARIABLE", "VARYING", "VERBOSE", "VERSION", "VIEW", "VOLATILE", "WHEN", "WHENEVER", "WHERE", "WITH",
- "WITHOUT", "WORK", "WRITE", "XMAX", "XMIN", "YEAR", "ZONE");
- }
-
- public override bool TableNameNeedsQuote
- {
- get { return false; }
- }
-
- public override bool ConstraintNameNeedsQuote
- {
- get { return false; }
- }
-
- public override bool IdentityNeedsType
- {
- get { return false; }
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope, string providerName)
- {
- return new PostgreSQLTransformationProvider(dialect, connectionString, defaultSchema, scope, providerName);
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, IDbConnection connection,
- string defaultSchema,
- string scope, string providerName)
- {
- return new PostgreSQLTransformationProvider(dialect, connection, defaultSchema, scope, providerName);
- }
- }
-}
diff --git a/src/Migrator.Providers/Impl/PostgreSQL/PostgreSQLTransformationProvider.cs b/src/Migrator.Providers/Impl/PostgreSQL/PostgreSQLTransformationProvider.cs
deleted file mode 100644
index c0608164..00000000
--- a/src/Migrator.Providers/Impl/PostgreSQL/PostgreSQLTransformationProvider.cs
+++ /dev/null
@@ -1,303 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.Common;
-
-using Migrator.Framework;
-
-namespace Migrator.Providers.PostgreSQL
-{
- ///
- /// Migration transformations provider for PostgreSql (using NPGSql .Net driver)
- ///
- public class PostgreSQLTransformationProvider : TransformationProvider
- {
- public PostgreSQLTransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope, string providerName)
- : base(dialect, connectionString, defaultSchema, scope)
- {
- if (string.IsNullOrEmpty(providerName)) providerName = "Npgsql";
- var fac = DbProviderFactoriesHelper.GetFactory(providerName, "Npgsql", "Npgsql.NpgsqlFactory");
- _connection = fac.CreateConnection(); //new NpgsqlConnection();
- _connection.ConnectionString = _connectionString;
- _connection.Open();
- }
-
- public PostgreSQLTransformationProvider(Dialect dialect, IDbConnection connection, string defaultSchema, string scope, string providerName)
- : base(dialect, connection, defaultSchema, scope)
- {
- }
-
- public override Index[] GetIndexes(string table)
- {
- var retVal = new List();
-
- var sql = @"
-SELECT * FROM (
-SELECT i.relname as indname,
- idx.indisprimary,
- idx.indisunique,
- i.relowner as indowner,
- cast(idx.indrelid::regclass as varchar) as tablenm,
- am.amname as indam,
- idx.indkey,
- ARRAY(
- SELECT pg_get_indexdef(idx.indexrelid, k + 1, true)
- FROM generate_subscripts(idx.indkey, 1) as k
- ORDER BY k
- ) as indkey_names,
- idx.indexprs IS NOT NULL as indexprs,
- idx.indpred IS NOT NULL as indpred
-FROM pg_index as idx
-JOIN pg_class as i
-ON i.oid = idx.indexrelid
-JOIN pg_am as am
-ON i.relam = am.oid
-JOIN pg_namespace as ns
-ON ns.oid = i.relnamespace
-AND ns.nspname = ANY(current_schemas(false))) AS t
-WHERE lower(tablenm) = lower('{0}')
-;";
-
-
-
- using (var reader = ExecuteQuery(string.Format(sql, table)))
- {
- while (reader.Read())
- {
- if (!reader.IsDBNull(1))
- {
- var idx = new Index
- {
- Name = reader.GetString(0),
- PrimaryKey = reader.GetBoolean(1),
- Unique = reader.GetBoolean(2),
- };
- //var cols = reader.GetString(7);
- //cols = cols.Substring(1, cols.Length - 2);
- //idx.KeyColumns = cols.Split(',');
- retVal.Add(idx);
- }
- }
- }
-
- return retVal.ToArray();
- }
-
- public override void RemoveTable(string name)
- {
- if (!TableExists(name))
- {
- throw new MigrationException(String.Format("Table with name '{0}' does not exist to rename", name));
- }
-
- ExecuteNonQuery(String.Format("DROP TABLE IF EXISTS {0} CASCADE", name));
- }
-
- public override bool ConstraintExists(string table, string name)
- {
- using (IDataReader reader =
- ExecuteQuery(string.Format("SELECT constraint_name FROM information_schema.table_constraints WHERE table_schema = 'public' AND constraint_name = lower('{0}')", name)))
- {
- return reader.Read();
- }
- }
-
- public override bool ColumnExists(string table, string column)
- {
- if (!TableExists(table))
- return false;
-
- using (IDataReader reader =
- ExecuteQuery(String.Format("SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = lower('{0}') AND (column_name = lower('{1}') OR column_name = '{1}')", table, column)))
- {
- return reader.Read();
- }
- }
-
- public override bool TableExists(string table)
- {
- using (IDataReader reader =
- ExecuteQuery(String.Format("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name = lower('{0}')", table)))
- {
- return reader.Read();
- }
- }
-
- public override List GetDatabases()
- {
- return ExecuteStringQuery("SELECT datname FROM pg_database WHERE datistemplate = false");
- }
-
- //public override void ChangeColumn(string table, Column column)
- //{
- // if (!ColumnExists(table, column.Name))
- // {
- // Logger.Warn("Column {0}.{1} does not exist", table, column.Name);
- // return;
- // }
-
- // var existingColumn = GetColumnByName(table, column.Name);
-
- // column.Name = existingColumn.Name; // name might have different case.
-
- // string tempColumn = "temp_" + column.Name;
- // RenameColumn(table, column.Name, tempColumn);
-
- // // check if this is not-null
- // bool isNotNull = (column.ColumnProperty & ColumnProperty.NotNull) == ColumnProperty.NotNull;
-
- // // remove the not-null option
- // column.ColumnProperty = (column.ColumnProperty & ~ColumnProperty.NotNull);
-
- // AddColumn(table, column);
- // ExecuteQuery(String.Format("UPDATE {0} SET {1}={2}", table, Dialect.Quote(column.Name), Dialect.Quote(tempColumn)));
- // RemoveColumn(table, tempColumn);
-
- // // if is not null, set that now
- // if (isNotNull) ExecuteQuery(string.Format("ALTER TABLE {0} ALTER COLUMN {1} SET NOT NULL", table, Dialect.Quote(column.Name)));
- //}
-
- public override void ChangeColumn(string table, Column column)
- {
- var oldColumn = GetColumnByName(table, column.Name);
-
- var isUniqueSet = column.ColumnProperty.IsSet(ColumnProperty.Unique);
-
- column.ColumnProperty = column.ColumnProperty.Clear(ColumnProperty.Unique);
-
- if (!ColumnExists(table, column.Name))
- {
- Logger.Warn("Column {0}.{1} does not exist", table, column.Name);
- return;
- }
-
- ColumnPropertiesMapper mapper = _dialect.GetAndMapColumnProperties(column);
-
- string change1 = string.Format("{0} TYPE {1}", QuoteColumnNameIfRequired(mapper.Name), mapper.type);
-
- #region Field Type Converters...
- if ((oldColumn.Type == DbType.Int16 || oldColumn.Type == DbType.Int32 || oldColumn.Type == DbType.Int64 || oldColumn.Type == DbType.Decimal) && column.Type == DbType.Boolean)
- {
- change1 += string.Format(" USING CASE {0} WHEN 1 THEN true ELSE false END", QuoteColumnNameIfRequired(mapper.Name));
- }
- else if (column.Type == DbType.Boolean)
- {
- change1 += string.Format(" USING CASE {0} WHEN '1' THEN true ELSE false END", QuoteColumnNameIfRequired(mapper.Name));
- }
- #endregion
- ChangeColumn(table, change1);
-
- if (mapper.Default != null)
- {
- string change2 = string.Format("{0} SET {1}", QuoteColumnNameIfRequired(mapper.Name), _dialect.Default(mapper.Default));
- ChangeColumn(table, change2);
- }
- else
- {
- string change2 = string.Format("{0} DROP DEFAULT", QuoteColumnNameIfRequired(mapper.Name));
- ChangeColumn(table, change2);
- }
-
- if (isUniqueSet)
- {
- AddUniqueConstraint(string.Format("UX_{0}_{1}", table, column.Name), table, new string[] { column.Name });
- }
- }
-
- public override void CreateDatabases(string databaseName)
- {
- ExecuteNonQuery(string.Format("CREATE DATABASE {0}", _dialect.Quote(databaseName)));
- }
-
- public override void SwitchDatabase(string databaseName)
- {
- _connection.ChangeDatabase(_dialect.Quote(databaseName));
- }
-
- public override void DropDatabases(string databaseName)
- {
- ExecuteNonQuery(string.Format("DROP DATABASE {0}", _dialect.Quote(databaseName)));
- }
-
- public override string[] GetTables()
- {
- var tables = new List();
- using (IDataReader reader = ExecuteQuery("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'"))
- {
- while (reader.Read())
- {
- tables.Add((string) reader[0]);
- }
- }
- return tables.ToArray();
- }
-
- public override Column[] GetColumns(string table)
- {
- var columns = new List();
- using (
- IDataReader reader =
- ExecuteQuery(
- String.Format("select COLUMN_NAME, IS_NULLABLE from information_schema.columns where table_schema = 'public' AND table_name = lower('{0}');", table)))
- {
- // FIXME: Mostly duplicated code from the Transformation provider just to support stupid case-insensitivty of Postgre
- while (reader.Read())
- {
- var column = new Column(reader[0].ToString(), DbType.String);
- bool isNullable = reader.GetString(1) == "YES";
- column.ColumnProperty |= isNullable ? ColumnProperty.Null : ColumnProperty.NotNull;
-
- columns.Add(column);
- }
- }
-
- return columns.ToArray();
- }
-
- public override Column GetColumnByName(string table, string columnName)
- {
- // Duplicate because of the lower case issue
- return Array.Find(GetColumns(table), column => column.Name == columnName.ToLower() || column.Name == columnName);
- }
-
- public override bool IndexExists(string table, string name)
- {
- using (IDataReader reader =
- ExecuteQuery(string.Format("SELECT indexname FROM pg_catalog.pg_indexes WHERE indexname = lower('{0}')", name)))
- {
- return reader.Read();
- }
- }
-
- protected override void ConfigureParameterWithValue(IDbDataParameter parameter, int index, object value)
- {
- if (value is UInt16)
- {
- parameter.DbType = DbType.Int32;
- parameter.Value = Convert.ToInt32(value);
- }
- else if (value is UInt32)
- {
- parameter.DbType = DbType.Int64;
- parameter.Value = Convert.ToInt64(value);
- }
- else
- {
- base.ConfigureParameterWithValue(parameter, index, value);
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/SQLite/SQLiteDialect.cs b/src/Migrator.Providers/Impl/SQLite/SQLiteDialect.cs
deleted file mode 100644
index 0c7b0561..00000000
--- a/src/Migrator.Providers/Impl/SQLite/SQLiteDialect.cs
+++ /dev/null
@@ -1,69 +0,0 @@
-using System;
-using System.Data;
-using Migrator.Framework;
-
-namespace Migrator.Providers.SQLite
-{
- public class SQLiteDialect : Dialect
- {
- public SQLiteDialect()
- {
- RegisterColumnType(DbType.Binary, "BINARY");
- RegisterColumnType(DbType.Byte, "TINYINT");
- RegisterColumnType(DbType.Int16, "SMALLINT");
- RegisterColumnType(DbType.Int32, "INTEGER");
- RegisterColumnType(DbType.Int64, "INTEGER");
- RegisterColumnType(DbType.SByte, "INTEGER");
- RegisterColumnType(DbType.UInt16, "INTEGER");
- RegisterColumnType(DbType.UInt32, "INTEGER");
- RegisterColumnType(DbType.UInt64, "INTEGER");
-
- RegisterColumnType(DbType.Currency, "CURRENCY");
- RegisterColumnType(DbType.Decimal, "DECIMAL");
- RegisterColumnType(DbType.Double, "DOUBLE");
- RegisterColumnType(DbType.Single, "REAL");
- RegisterColumnType(DbType.VarNumeric, "NUMERIC");
-
- RegisterColumnType(DbType.String, "TEXT");
- RegisterColumnType(DbType.StringFixedLength, "TEXT");
- RegisterColumnType(DbType.AnsiString, "TEXT");
- RegisterColumnType(DbType.AnsiStringFixedLength, "TEXT");
-
- RegisterColumnType(DbType.Date, "DATE");
- RegisterColumnType(DbType.DateTime, "DATETIME");
- RegisterColumnType(DbType.DateTimeOffset, "TEXT");
- RegisterColumnType(DbType.Time, "TIME");
- RegisterColumnType(DbType.Boolean, "BOOLEAN"); // Important for Dapper to know it should map to a bool
- RegisterColumnType(DbType.Guid, "UNIQUEIDENTIFIER");
-
- RegisterProperty(ColumnProperty.Identity, "AUTOINCREMENT");
- RegisterProperty(ColumnProperty.CaseSensitive, "COLLATE NOCASE");
- }
-
- public override string Default(object defaultValue)
- {
- if (defaultValue is bool)
- {
- return String.Format("DEFAULT {0}", (bool)defaultValue ? "1" : "0");
- }
-
- return base.Default(defaultValue);
- }
-
- public override bool NeedsNotNullForIdentity
- {
- get { return false; }
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope, string providerName)
- {
- return new SQLiteTransformationProvider(dialect, connectionString, scope, providerName);
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, IDbConnection connection, string defaultSchema,
- string scope, string providerName)
- {
- return new SQLiteTransformationProvider(dialect, connection, scope, providerName);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/SQLite/SQLiteMonoDialect.cs b/src/Migrator.Providers/Impl/SQLite/SQLiteMonoDialect.cs
deleted file mode 100644
index 10b41f0b..00000000
--- a/src/Migrator.Providers/Impl/SQLite/SQLiteMonoDialect.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using System.Data;
-using Migrator.Framework;
-
-namespace Migrator.Providers.SQLite
-{
- public class SQLiteMonoDialect : SQLiteDialect
- {
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope, string providerName)
- {
- return new SQLiteMonoTransformationProvider(dialect, connectionString, scope, providerName);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/SQLite/SQLiteMonoTransformationProvider.cs b/src/Migrator.Providers/Impl/SQLite/SQLiteMonoTransformationProvider.cs
deleted file mode 100644
index e18e98cc..00000000
--- a/src/Migrator.Providers/Impl/SQLite/SQLiteMonoTransformationProvider.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.Common;
-
-using Migrator.Framework;
-
-namespace Migrator.Providers.SQLite
-{
- ///
- /// Summary description for SQLiteTransformationProvider.
- ///
- public class SQLiteMonoTransformationProvider : SQLiteTransformationProvider
- {
- public SQLiteMonoTransformationProvider(Dialect dialect, string connectionString, string scope, string providerName)
- : base(dialect, connectionString, scope, providerName)
- {
-
- }
-
- public SQLiteMonoTransformationProvider(Dialect dialect, IDbConnection connection, string scope, string providerName)
- : base(dialect, connection, scope, providerName)
- {
- }
-
- protected override void CreateConnection(string providerName)
- {
- if (string.IsNullOrEmpty(providerName))
- providerName = "Mono.Data.Sqlite";
- var fac = DbProviderFactoriesHelper.GetFactory(providerName, "Mono.Data.Sqlite", "Mono.Data.Sqlite.SQLiteFactory");
- _connection = fac.CreateConnection(); // new SQLiteConnection(_connectionString);
- _connection.ConnectionString = _connectionString;
- _connection.Open();
- }
- }
-}
diff --git a/src/Migrator.Providers/Impl/SQLite/SQLiteTransformationProvider.cs b/src/Migrator.Providers/Impl/SQLite/SQLiteTransformationProvider.cs
deleted file mode 100644
index 64cec3d8..00000000
--- a/src/Migrator.Providers/Impl/SQLite/SQLiteTransformationProvider.cs
+++ /dev/null
@@ -1,591 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.Common;
-//using System.Data.SQLite;
-using System.Linq;
-
-using Migrator.Framework;
-
-using ForeignKeyConstraint = Migrator.Framework.ForeignKeyConstraint;
-
-namespace Migrator.Providers.SQLite
-{
- ///
- /// Summary description for SQLiteTransformationProvider.
- ///
- public class SQLiteTransformationProvider : TransformationProvider
- {
- public SQLiteTransformationProvider(Dialect dialect, string connectionString, string scope, string providerName)
- : base(dialect, connectionString, null, scope)
- {
- this.CreateConnection(providerName);
- }
-
- public SQLiteTransformationProvider(Dialect dialect, IDbConnection connection, string scope, string providerName)
- : base(dialect, connection, null, scope)
- {
- }
-
- protected virtual void CreateConnection(string providerName)
- {
- if (string.IsNullOrEmpty(providerName))
- providerName = "System.Data.SQLite";
- var fac = DbProviderFactoriesHelper.GetFactory(providerName, "System.Data.SQLite", "System.Data.SQLite.SQLiteFactory");
- _connection = fac.CreateConnection(); // new SQLiteConnection(_connectionString);
- _connection.ConnectionString = _connectionString;
- _connection.Open();
- }
-
- public override void AddForeignKey(string name, string primaryTable, string[] primaryColumns, string refTable,
- string[] refColumns, ForeignKeyConstraintType constraint)
- {
- // NOOP Because SQLite doesn't support foreign keys
- }
-
- private string GetSqlForAddTable(string tableName, string colDefsSql, string compositeDefSql)
- {
- return compositeDefSql != null ? colDefsSql.TrimEnd(')') + "," + compositeDefSql : colDefsSql;
- }
-
- public string[] GetColumnDefs(string table, out string compositeDefSql)
- {
- return ParseSqlColumnDefs(GetSqlDefString(table), out compositeDefSql);
- }
-
- public string GetSqlDefString(string table)
- {
- string sqldef = null;
- using (IDataReader reader = ExecuteQuery(String.Format("SELECT sql FROM sqlite_master WHERE type='table' AND name='{0}'", table)))
- {
- if (reader.Read())
- {
- sqldef = (string)reader[0];
- }
- }
- return sqldef;
- }
-
- public string[] ParseSqlColumnDefs(string sqldef, out string compositeDefSql)
- {
- if (String.IsNullOrEmpty(sqldef))
- {
- compositeDefSql = null;
- return null;
- }
-
- sqldef = sqldef.Replace(Environment.NewLine, " ");
- int start = sqldef.IndexOf("(");
-
- // Code to handle composite primary keys /mol
- int compositeDefIndex = sqldef.IndexOf("PRIMARY KEY ("); // Not ideal to search for a string like this but I'm lazy
- if (compositeDefIndex > -1)
- {
- compositeDefSql = sqldef.Substring(compositeDefIndex, sqldef.LastIndexOf(")") - compositeDefIndex);
- sqldef = sqldef.Substring(0, compositeDefIndex).TrimEnd(',', ' ') + ")";
- }
- else
- compositeDefSql = null;
-
- int end = sqldef.LastIndexOf(")"); // Changed from 'IndexOf' to 'LastIndexOf' to handle foreign key definitions /mol
-
- sqldef = sqldef.Substring(0, end);
- sqldef = sqldef.Substring(start + 1);
-
- string[] cols = sqldef.Split(new char[] { ',' });
- for (int i = 0; i < cols.Length; i++)
- {
- cols[i] = cols[i].Trim();
- }
- return cols;
- }
-
- ///
- /// Turn something like 'columnName INTEGER NOT NULL' into just 'columnName'
- ///
- public string[] ParseSqlForColumnNames(string sqldef, out string compositeDefSql)
- {
- string[] parts = ParseSqlColumnDefs(sqldef, out compositeDefSql);
- return ParseSqlForColumnNames(parts);
- }
-
- public string[] ParseSqlForColumnNames(string[] parts)
- {
- if (null == parts)
- return null;
-
- for (int i = 0; i < parts.Length; i++)
- {
- parts[i] = ExtractNameFromColumnDef(parts[i]);
- }
- return parts;
- }
-
- ///
- /// Name is the first value before the space.
- ///
- ///
- ///
- public string ExtractNameFromColumnDef(string columnDef)
- {
- int idx = columnDef.IndexOf(" ");
- if (idx > 0)
- {
- return columnDef.Substring(0, idx);
- }
- return null;
- }
-
- public DbType ExtractTypeFromColumnDef(string columnDef)
- {
- int idx = columnDef.IndexOf(" ") + 1;
- if (idx > 0)
- {
- var idy = columnDef.IndexOf(" ", idx) - idx;
-
- if (idy > 0)
- return _dialect.GetDbType(columnDef.Substring(idx, idy));
- else
- return _dialect.GetDbType(columnDef.Substring(idx));
- }
- else
- throw new Exception("Error extracting type from column definition: '" + columnDef + "'");
- }
-
- public override void RemoveForeignKey(string table, string name)
- {
- //Check the impl...
- return;
-
- // Generate new table definition with foreign key
- string compositeDefSql;
- string[] origColDefs = GetColumnDefs(table, out compositeDefSql);
- List colDefs = new List();
-
- foreach (string origdef in origColDefs)
- {
- // Strip the constraint part of the column definition
- var constraintIndex = origdef.IndexOf(string.Format(" CONSTRAINT {0}", name), StringComparison.OrdinalIgnoreCase);
- if (constraintIndex > -1)
- colDefs.Add(origdef.Substring(0, constraintIndex));
- else
- colDefs.Add(origdef);
- }
-
- string[] newColDefs = colDefs.ToArray();
- string colDefsSql = String.Join(",", newColDefs);
-
- string[] colNames = ParseSqlForColumnNames(newColDefs);
- string colNamesSql = String.Join(",", colNames);
-
- // Create new table with temporary name
- AddTable(table + "_temp", null, GetSqlForAddTable(table, colDefsSql, compositeDefSql));
-
- // Copy data from original table to temporary table
- ExecuteNonQuery(String.Format("INSERT INTO {0}_temp SELECT {1} FROM {0}", table, colNamesSql));
-
- // Add indexes from original table
- MoveIndexesFromOriginalTable(table, table + "_temp");
-
- //PerformForeignKeyAffectedAction(() =>
- //{
- // Remove original table
- RemoveTable(table);
-
- // Rename temporary table to original table name
- ExecuteNonQuery(String.Format("ALTER TABLE {0}_temp RENAME TO {0}", table));
- //});
- }
-
- public string[] GetCreateIndexSqlStrings(string table)
- {
- var sqlStrings = new List();
-
- using (IDataReader reader = ExecuteQuery(String.Format("SELECT sql FROM sqlite_master WHERE type='index' AND sql NOT NULL AND tbl_name='{0}'", table)))
- while (reader.Read())
- sqlStrings.Add((string)reader[0]);
-
- return sqlStrings.ToArray();
- }
-
- public void MoveIndexesFromOriginalTable(string origTable, string newTable)
- {
- var indexSqls = GetCreateIndexSqlStrings(origTable);
- foreach (var indexSql in indexSqls)
- {
- var origTableStart = indexSql.IndexOf(" ON ", StringComparison.OrdinalIgnoreCase) + 4;
- var origTableEnd = indexSql.IndexOf("(", origTableStart);
-
- // First remove original index, because names have to be unique
- var createIndexDef = " INDEX ";
- var indexNameStart = indexSql.IndexOf(createIndexDef, StringComparison.OrdinalIgnoreCase) + createIndexDef.Length;
- ExecuteNonQuery("DROP INDEX " + indexSql.Substring(indexNameStart, (origTableStart - 4) - indexNameStart));
-
- // Create index on new table
- ExecuteNonQuery(indexSql.Substring(0, origTableStart) + newTable + " " + indexSql.Substring(origTableEnd));
- }
- }
-
- public override void RemoveColumn(string table, string column)
- {
- if (! (TableExists(table) && ColumnExists(table, column)))
- return;
-
-
- var newColumns = GetColumns(table).Where(x => x.Name != column).ToArray();
-
- AddTable(table + "_temp", null, newColumns);
- var colNamesSql = string.Join(", ", newColumns.Select(x => x.Name));
- ExecuteQuery(String.Format("INSERT INTO {0}_temp SELECT {1} FROM {0}", table, colNamesSql));
- RemoveTable(table);
- ExecuteQuery(String.Format("ALTER TABLE {0}_temp RENAME TO {0}", table));
- }
-
- public override void RenameColumn(string tableName, string oldColumnName, string newColumnName)
- {
- if (ColumnExists(tableName, newColumnName))
- throw new MigrationException(String.Format("Table '{0}' has column named '{1}' already", tableName, newColumnName));
-
- if (ColumnExists(tableName, oldColumnName))
- {
- var columnDef = GetColumns(tableName).First(x => x.Name == oldColumnName);
-
- //if (columnDef.IsPrimaryKey)
- {
- columnDef.Name = newColumnName;
- this.changeColumnInternal(tableName, new[] { oldColumnName }, new[] { columnDef });
- }
- /*else
- {
- columnDef.Name = newColumnName;
- AddColumn(tableName, columnDef);
- ExecuteQuery(String.Format("UPDATE {0} SET {1}={2}", tableName, newColumnName, oldColumnName));
- RemoveColumn(tableName, oldColumnName);
- }*/
- }
- }
-
- public override void RemoveColumnDefaultValue(string table, string column)
- {
- var columnDef = GetColumns(table).First(x => x.Name == column);
- columnDef.DefaultValue = null;
- changeColumnInternal(table, new[] { column }, new[] { columnDef });
- }
-
- public override void AddPrimaryKey(string name, string table, params string[] columns)
- {
- List newCol = new List();
- foreach (var column in columns)
- {
- var columnDef = GetColumns(table).First(x => x.Name == column);
- columnDef.ColumnProperty |= ColumnProperty.PrimaryKey;
- newCol.Add(columnDef);
- }
- this.changeColumnInternal(table, columns, newCol.ToArray());
- }
-
- public override void AddUniqueConstraint(string name, string table, params string[] columns)
- {
- var constr = new Unique() {KeyColumns = columns, Name = name};
-
- this.changeColumnInternal(table, new string[] {}, new[] {constr});
- }
-
- private void changeColumnInternal(string table, string[] old, IDbField[] columns)
- {
- var newColumns = GetColumns(table).Where(x => !old.Any(y => x.Name.ToLower() == y.ToLower())).ToList();
- var oldColumnNames = newColumns.Select(x => x.Name).ToList();
- newColumns.AddRange(columns.Where(x => x is Column).Cast());
- oldColumnNames.AddRange(old);
-
- var newFieldsPlusUnique = newColumns.Cast().ToList();
- newFieldsPlusUnique.AddRange(columns.Where(x => x is Unique));
-
- AddTable(table + "_temp", null, newFieldsPlusUnique.ToArray());
- var colNamesNewSql = string.Join(", ", newColumns.Select(x => x.Name));
- var colNamesSql = string.Join(", ", oldColumnNames);
- ExecuteQuery(String.Format("INSERT INTO {1}_temp ({0}) SELECT {2} FROM {1}", colNamesNewSql, table, colNamesSql));
- RemoveTable(table);
- ExecuteQuery(String.Format("ALTER TABLE {0}_temp RENAME TO {0}", table));
- }
-
-
- public override void ChangeColumn(string table, Column column)
- {
- if (! ColumnExists(table, column.Name))
- {
- Logger.Warn("Column {0}.{1} does not exist", table, column.Name);
- return;
- }
-
- if (
- (column.ColumnProperty & ColumnProperty.PrimaryKey) != ColumnProperty.PrimaryKey &&
- (column.ColumnProperty & ColumnProperty.Unique) != ColumnProperty.Unique &&
- ((column.ColumnProperty & ColumnProperty.NotNull) != ColumnProperty.NotNull || column.DefaultValue != null) &&
- (column.DefaultValue == null || (column.DefaultValue.ToString() != "'CURRENT_TIME'" && column.DefaultValue.ToString() != "'CURRENT_DATE'") && column.DefaultValue.ToString() != "'CURRENT_TIMESTAMP'")
- )
- {
- string tempColumn = "temp_" + column.Name;
- RenameColumn(table, column.Name, tempColumn);
- AddColumn(table, column);
- ExecuteQuery(String.Format("UPDATE {0} SET {1}={2}", table, column.Name, tempColumn));
- RemoveColumn(table, tempColumn);
- }
- else
- {
- var newColumns = GetColumns(table).ToArray();
-
- for (int i = 0; i < newColumns.Count(); i++)
- {
- if (newColumns[i].Name == column.Name)
- {
- newColumns[i] = column;
- break;
- }
- }
-
- AddTable(table + "_temp", null, newColumns);
-
- var colNamesSql = string.Join(", ", newColumns.Select(x => x.Name));
- ExecuteQuery(String.Format("INSERT INTO {0}_temp SELECT {1} FROM {0}", table, colNamesSql));
- RemoveTable(table);
- ExecuteQuery(String.Format("ALTER TABLE {0}_temp RENAME TO {0}", table));
- }
- }
-
- public override int TruncateTable(string table)
- {
- return ExecuteNonQuery(String.Format("DELETE FROM {0} ", table));
- }
-
- public override bool TableExists(string table)
- {
- using (IDataReader reader =
- ExecuteQuery(String.Format("SELECT name FROM sqlite_master WHERE type='table' and lower(name)=lower('{0}')", table)))
- {
- return reader.Read();
- }
- }
-
- public override List GetDatabases()
- {
- throw new NotImplementedException();
- }
-
- public override bool ConstraintExists(string table, string name)
- {
- return false;
- }
-
- public override string[] GetConstraints(string table)
- {
- return new string[] { };
- }
-
- public override string[] GetTables()
- {
- var tables = new List();
-
- using (IDataReader reader = ExecuteQuery("SELECT name FROM sqlite_master WHERE type='table' AND name <> 'sqlite_sequence' ORDER BY name"))
- {
- while (reader.Read())
- {
- tables.Add((string) reader[0]);
- }
- }
-
- return tables.ToArray();
- }
-
- public override Column[] GetColumns(string table)
- {
- var columns = new List();
- using (IDataReader reader = ExecuteQuery(String.Format("PRAGMA table_info('{0}')", table)))
- {
- while (reader.Read())
- {
- var column = new Column((string)reader[1]);
-
- column.Type = _dialect.GetDbTypeFromString((string)reader[2]);
-
- if (Convert.ToBoolean(reader[3]))
- {
- column.ColumnProperty |= ColumnProperty.NotNull;
- }
- else
- {
- column.ColumnProperty |= ColumnProperty.Null;
- }
-
- column.DefaultValue = reader[4] == DBNull.Value ? null : reader[4];
-
- if (Convert.ToBoolean(reader[5]))
- {
- column.ColumnProperty |= ColumnProperty.PrimaryKey;
- }
-
- columns.Add(column);
-
- }
- }
-
-
-
- return columns.ToArray();
- }
-
- public bool IsNullable(string columnDef)
- {
- return ! columnDef.Contains("NOT NULL");
- }
-
- public bool ColumnMatch(string column, string columnDef)
- {
- return columnDef.StartsWith(column + " ") || columnDef.StartsWith(_dialect.Quote(column));
- }
-
- public override bool IndexExists(string table, string name)
- {
- using (IDataReader reader =
- ExecuteQuery(String.Format("SELECT name FROM sqlite_master WHERE type='index' and name='{0}'", name)))
- {
- return reader.Read();
- }
- }
-
- public override void AddTable(string name, string engine, params IDbField[] fields)
- {
- if (TableExists(name))
- {
- Logger.Warn("Table {0} already exists", name);
- return;
- }
-
- var columns = fields.Where(x => x is Column).Cast().ToArray();
-
- List pks = GetPrimaryKeys(columns);
- bool compoundPrimaryKey = pks.Count > 1;
-
- var columnProviders = new List(columns.Length);
- foreach (Column column in columns)
- {
- // Remove the primary key notation if compound primary key because we'll add it back later
- if (compoundPrimaryKey && column.IsPrimaryKey)
- {
- column.ColumnProperty = column.ColumnProperty ^ ColumnProperty.PrimaryKey;
- column.ColumnProperty = column.ColumnProperty | ColumnProperty.NotNull; // PK is always not-null
- }
-
- ColumnPropertiesMapper mapper = _dialect.GetAndMapColumnProperties(column);
- columnProviders.Add(mapper);
- }
-
- string columnsAndIndexes = JoinColumnsAndIndexes(columnProviders);
-
- var table = _dialect.TableNameNeedsQuote ? _dialect.Quote(name) : name;
- string sqlCreate;
-
- sqlCreate = String.Format("CREATE TABLE {0} ({1}", table, columnsAndIndexes);
-
- if (compoundPrimaryKey)
- {
- sqlCreate += String.Format(", PRIMARY KEY ({0}) ", String.Join(",", pks.ToArray()));
- }
-
- var uniques = fields.Where(x => x is Unique).Cast().ToArray();
- foreach (var u in uniques)
- {
- var nm = "";
- if (!string.IsNullOrEmpty(u.Name))
- nm = string.Format(" CONSTRAINT {0}", u.Name);
- sqlCreate += String.Format(",{0} UNIQUE ({1})", nm, String.Join(",", u.KeyColumns));
- }
-
- var foreignKeys = fields.Where(x => x is ForeignKeyConstraint).Cast().ToArray();
- foreach (var fk in foreignKeys)
- {
- var nm = "";
- if (!string.IsNullOrEmpty(fk.Name))
- nm = string.Format(" CONSTRAINT {0}", fk.Name);
- sqlCreate += String.Format(",{0} FOREIGN KEY ({1}) REFERENCES {2}({3})", nm, String.Join(",", fk.Columns), fk.PkTable, String.Join(",", fk.PkColumns));
- }
-
-
-
- //table = QuoteTableNameIfRequired(table);
- //ExecuteNonQuery(String.Format("ALTER TABLE {0} ADD CONSTRAINT {1} UNIQUE({2}) ", table, name, string.Join(", ", columns)));
-
-
-
- sqlCreate += ")";
-
- ExecuteNonQuery(sqlCreate);
-
- var indexes = fields.Where(x => x is Index).Cast().ToArray();
- foreach (var index in indexes)
- {
- AddIndex(name, index);
- }
- }
-
- protected override string GetPrimaryKeyConstraintName(string table)
- {
- throw new NotImplementedException();
- }
-
- public override void RemovePrimaryKey(string table)
- {
- if (!TableExists(table)) return;
-
- var columnDefs = GetColumns(table);
-
- foreach (var columnDef in columnDefs.Where(columnDef => columnDef.IsPrimaryKey))
- {
- columnDef.ColumnProperty = columnDef.ColumnProperty.Clear(ColumnProperty.PrimaryKey);
- columnDef.ColumnProperty = columnDef.ColumnProperty.Clear(ColumnProperty.PrimaryKeyWithIdentity);
- }
-
- changeColumnInternal(table, columnDefs.Select(x => x.Name).ToArray(), columnDefs);
- }
-
- public override void RemoveAllIndexes(string table)
- {
- if (!TableExists(table)) return;
-
- var columnDefs = GetColumns(table);
-
- foreach (var columnDef in columnDefs.Where(columnDef => columnDef.IsPrimaryKey))
- {
- columnDef.ColumnProperty = columnDef.ColumnProperty.Clear(ColumnProperty.PrimaryKey);
- columnDef.ColumnProperty = columnDef.ColumnProperty.Clear(ColumnProperty.PrimaryKeyWithIdentity);
- columnDef.ColumnProperty = columnDef.ColumnProperty.Clear(ColumnProperty.Unique);
- columnDef.ColumnProperty = columnDef.ColumnProperty.Clear(ColumnProperty.Indexed);
- }
-
- changeColumnInternal(table, columnDefs.Select(x => x.Name).ToArray(), columnDefs);
- }
-
- protected override void ConfigureParameterWithValue(IDbDataParameter parameter, int index, object value)
- {
- if (value is UInt16)
- {
- parameter.DbType = DbType.Int32;
- parameter.Value = Convert.ToInt32(value);
- }
- else if (value is UInt32)
- {
- parameter.DbType = DbType.Int64;
- parameter.Value = Convert.ToInt64(value);
- }
- else if (value is Guid || value is Guid?)
- {
- parameter.DbType = DbType.Binary;
- parameter.Value = ((Guid)value).ToByteArray();
- }
- else
- {
- base.ConfigureParameterWithValue(parameter, index, value);
- }
- }
- }
-}
diff --git a/src/Migrator.Providers/Impl/SqlServer/SqlServer2005Dialect.cs b/src/Migrator.Providers/Impl/SqlServer/SqlServer2005Dialect.cs
deleted file mode 100644
index e583aa9f..00000000
--- a/src/Migrator.Providers/Impl/SqlServer/SqlServer2005Dialect.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-using System.Data;
-using Migrator.Framework;
-
-namespace Migrator.Providers.SqlServer
-{
- public class SqlServer2005Dialect : SqlServerDialect
- {
- public SqlServer2005Dialect()
- {
- RegisterColumnType(DbType.AnsiString, 2147483647, "VARCHAR(MAX)");
- RegisterColumnType(DbType.Binary, 2147483647, "VARBINARY(MAX)");
- RegisterColumnType(DbType.String, 1073741823, "NVARCHAR(MAX)");
- RegisterColumnType(DbType.Xml, "XML");
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope, string providerName)
- {
- return new SqlServerTransformationProvider(dialect, connectionString, defaultSchema ?? DboSchemaName, scope, providerName);
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, IDbConnection connection,
- string defaultSchema,
- string scope, string providerName)
- {
- return new SqlServerTransformationProvider(dialect, connection, defaultSchema ?? DboSchemaName, scope, providerName);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/SqlServer/SqlServerCeDialect.cs b/src/Migrator.Providers/Impl/SqlServer/SqlServerCeDialect.cs
deleted file mode 100644
index c5113016..00000000
--- a/src/Migrator.Providers/Impl/SqlServer/SqlServerCeDialect.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-using System.Data;
-using Migrator.Framework;
-
-namespace Migrator.Providers.SqlServer
-{
- public class SqlServerCeDialect : SqlServerDialect
- {
- public SqlServerCeDialect()
- {
- RegisterColumnType(DbType.AnsiStringFixedLength, "NCHAR(255)");
- RegisterColumnType(DbType.AnsiStringFixedLength, 4000, "NCHAR($l)");
- RegisterColumnType(DbType.AnsiString, "NVARCHAR(255)");
- RegisterColumnType(DbType.AnsiString, 4000, "NVARCHAR($l)");
- RegisterColumnType(DbType.AnsiString, 1073741823, "TEXT");
- RegisterColumnType(DbType.Double, "FLOAT");
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope, string providerName)
- {
- return new SqlServerCeTransformationProvider(dialect, connectionString, scope, providerName);
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, IDbConnection connection,
- string defaultSchema,
- string scope, string providerName)
- {
- return new SqlServerCeTransformationProvider(dialect, connection, scope, providerName);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/SqlServer/SqlServerCeTransformationProvider.cs b/src/Migrator.Providers/Impl/SqlServer/SqlServerCeTransformationProvider.cs
deleted file mode 100644
index b44866ea..00000000
--- a/src/Migrator.Providers/Impl/SqlServer/SqlServerCeTransformationProvider.cs
+++ /dev/null
@@ -1,116 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-using System;
-using System.Data;
-using System.Data.Common;
-//using System.Data.SqlServerCe;
-using Migrator.Framework;
-
-namespace Migrator.Providers.SqlServer
-{
- ///
- /// Migration transformations provider for Microsoft SQL Server Compact Edition.
- ///
- public class SqlServerCeTransformationProvider : SqlServerTransformationProvider
- {
- public SqlServerCeTransformationProvider(Dialect dialect, string connectionString, string scope, string providerName)
- : base(dialect, connectionString, null, scope, providerName)
- {
- }
-
- public SqlServerCeTransformationProvider(Dialect dialect, IDbConnection connection, string scope, string providerName)
- : base(dialect, connection, null, scope, providerName)
- {
- }
-
- protected override void CreateConnection(string providerName)
- {
- if (string.IsNullOrEmpty(providerName)) providerName = "System.Data.SqlServerCe.3.5";
- var fac = DbProviderFactories.GetFactory(providerName);
- _connection = fac.CreateConnection(); // new SqlConnection();
- _connection.ConnectionString = _connectionString;
- _connection.Open();
- }
-
- public override bool ConstraintExists(string table, string name)
- {
- using (IDataReader reader =
- ExecuteQuery(string.Format("SELECT cont.constraint_name FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS cont WHERE cont.Constraint_Name='{0}'", name)))
- {
- return reader.Read();
- }
- }
-
- protected string GetSchemaName(string longTableName)
- {
- throw new MigrationException("SQL CE does not support database schemas.");
- }
-
- public override bool TableExists(string table)
- {
- using (IDataReader reader = base.ExecuteQuery(string.Format("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{0}'", table)))
- {
- return reader.Read();
- }
- }
-
- public override bool ColumnExists(string table, string column)
- {
- if (!TableExists(table))
- {
- return false;
- }
- int firstIndex = table.IndexOf(".");
- if (firstIndex >= 0)
- {
- table = table.Substring(firstIndex + 1);
- }
-
- using (
- IDataReader reader = base.ExecuteQuery(string.Format("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='{0}' AND COLUMN_NAME='{1}'", table, column)))
- {
- return reader.Read();
- }
- }
-
- public override void RenameColumn(string tableName, string oldColumnName, string newColumnName)
- {
- if (ColumnExists(tableName, newColumnName))
- throw new MigrationException(String.Format("Table '{0}' has column named '{1}' already", tableName, newColumnName));
-
- if (ColumnExists(tableName, oldColumnName))
- {
- Column column = GetColumnByName(tableName, oldColumnName);
-
- AddColumn(tableName, new Column(newColumnName, column.Type, column.ColumnProperty, column.DefaultValue));
- ExecuteNonQuery(string.Format("UPDATE {0} SET {1}={2}", tableName, newColumnName, oldColumnName));
- RemoveColumn(tableName, oldColumnName);
- }
- }
-
- // Not supported by SQLCe when we have a better schemadumper which gives the exact sql construction including constraints we may use it to insert into a new table and then drop the old table...but this solution is dangerous for big tables.
- public override void RenameTable(string oldName, string newName)
- {
- throw new NotSupportedException("Table Rename is not supported in SQL CE");
- }
-
- protected override string FindConstraints(string table, string column)
- {
- return
- string.Format("SELECT cont.constraint_name FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE cont "
- + "WHERE cont.Table_Name='{0}' AND cont.column_name = '{1}'",
- table, column);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/SqlServer/SqlServerDialect.cs b/src/Migrator.Providers/Impl/SqlServer/SqlServerDialect.cs
deleted file mode 100644
index fb827f34..00000000
--- a/src/Migrator.Providers/Impl/SqlServer/SqlServerDialect.cs
+++ /dev/null
@@ -1,127 +0,0 @@
-using System;
-using System.Data;
-using Migrator.Framework;
-
-namespace Migrator.Providers.SqlServer
-{
- public class SqlServerDialect : Dialect
- {
- public const string DboSchemaName = "dbo";
-
- public SqlServerDialect()
- {
- RegisterColumnType(DbType.AnsiStringFixedLength, "CHAR(255)");
- RegisterColumnType(DbType.AnsiStringFixedLength, int.MaxValue - 1, "CHAR($l)");
- RegisterColumnType(DbType.AnsiStringFixedLength, int.MaxValue, "CHAR(max)");
- RegisterColumnType(DbType.AnsiString, "VARCHAR(255)");
- RegisterColumnType(DbType.AnsiString, 8000, "VARCHAR($l)");
- RegisterColumnType(DbType.AnsiString, 2147483647, "TEXT");
- RegisterColumnType(DbType.Binary, "VARBINARY(8000)");
- RegisterColumnType(DbType.Binary, int.MaxValue-1, "VARBINARY($l)");
- RegisterColumnType(DbType.Binary, int.MaxValue, "VARBINARY(max)");
- RegisterColumnType(DbType.Boolean, "BIT");
- RegisterColumnType(DbType.Byte, "TINYINT");
- RegisterColumnType(DbType.Currency, "MONEY");
- RegisterColumnType(DbType.Date, "DATETIME");
- RegisterColumnType(DbType.DateTime, "DATETIME");
- RegisterColumnType(DbType.DateTimeOffset, "DATETIMEOffset(7)");
- RegisterColumnType(DbType.Decimal, "DECIMAL(19,5)");
- RegisterColumnType(DbType.Decimal, 19, "DECIMAL(19, $l)");
- RegisterColumnType(DbType.Double, "DOUBLE PRECISION"); //synonym for FLOAT(53)
- RegisterColumnType(DbType.Double, 24, "FLOAT(24)");
- RegisterColumnType(DbType.Double, 53, "FLOAT(53)");
- RegisterColumnType(DbType.Guid, "UNIQUEIDENTIFIER");
- RegisterColumnType(DbType.Int16, "SMALLINT");
- RegisterColumnType(DbType.Int32, "INT");
- RegisterColumnType(DbType.Int64, "BIGINT");
- RegisterColumnType(DbType.UInt16, "INT");
- RegisterColumnType(DbType.UInt32, "BIGINT");
- RegisterColumnType(DbType.UInt64, "DECIMAL(20,0)");
- RegisterColumnType(DbType.Single, "REAL"); //synonym for FLOAT(24)
- RegisterColumnType(DbType.StringFixedLength, "NCHAR(255)");
- RegisterColumnType(DbType.StringFixedLength, int.MaxValue - 1, "NCHAR($l)");
- RegisterColumnType(DbType.StringFixedLength, int.MaxValue, "NCHAR(max)");
- RegisterColumnType(DbType.String, "NVARCHAR(255)");
- RegisterColumnType(DbType.String, int.MaxValue - 1, "NVARCHAR($l)");
- RegisterColumnType(DbType.String, int.MaxValue, "NVARCHAR(max)");
- //RegisterColumnType(DbType.String, 1073741823, "NTEXT");
- RegisterColumnType(DbType.Time, "DATETIME");
- RegisterColumnType(DbType.VarNumeric, "NUMERIC(18,0)");
- RegisterColumnType(DbType.VarNumeric, 38, "NUMERIC($l,0)");
-
- RegisterProperty(ColumnProperty.Identity, "IDENTITY");
-
- AddReservedWords("ADD", "EXCEPT", "PERCENT", "ALL", "EXEC", "PLAN", "ALTER", "EXECUTE", "PRECISION", "AND", "EXISTS", "PRIMARY", "ANY", "EXIT", "PRINT", "AS", "FETCH", "PROC", "ASC", "FILE", "PROCEDURE", "AUTHORIZATION", "FILLFACTOR", "PUBLIC", "BACKUP", "FOR", "RAISERROR", "BEGIN", "FOREIGN", "READ", "BETWEEN", "FREETEXT", "READTEXT", "BREAK", "FREETEXTTABLE", "RECONFIGURE", "BROWSE", "FROM", "REFERENCES", "BULK", "FULL", "REPLICATION", "BY", "FUNCTION", "RESTORE", "CASCADE", "GOTO", "RESTRICT", "CASE", "GRANT", "RETURN", "CHECK", "GROUP", "REVOKE", "CHECKPOINT", "HAVING", "RIGHT", "CLOSE", "HOLDLOCK", "ROLLBACK", "CLUSTERED", "IDENTITY", "ROWCOUNT", "COALESCE", "IDENTITY_INSERT", "ROWGUIDCOL", "COLLATE", "IDENTITYCOL", "RULE", "COLUMN", "IF", "SAVE", "COMMIT", "IN", "SCHEMA", "COMPUTE", "INDEX", "SELECT", "CONSTRAINT", "INNER", "SESSION_USER", "CONTAINS", "INSERT", "SET", "CONTAINSTABLE", "INTERSECT", "SETUSER", "CONTINUE", "INTO", "SHUTDOWN", "CONVERT", "IS", "SOME", "CREATE", "JOIN", "STATISTICS", "CROSS", "KEY", "SYSTEM_USER", "CURRENT", "KILL", "TABLE", "CURRENT_DATE", "LEFT", "TEXTSIZE", "CURRENT_TIME", "LIKE", "THEN", "CURRENT_TIMESTAMP", "LINENO", "TO", "CURRENT_USER", "LOAD", "TOP", "CURSOR", "NATIONAL", "TRAN", "DATABASE", "NOCHECK", "TRANSACTION", "DBCC", "NONCLUSTERED", "TRIGGER", "DEALLOCATE", "NOT", "TRUNCATE", "DECLARE", "NULL", "TSEQUAL", "DEFAULT", "NULLIF", "UNION", "DELETE", "OF", "UNIQUE", "DENY", "OFF", "UPDATE", "DESC", "OFFSETS", "UPDATETEXT", "DISK", "ON", "USE", "DISTINCT", "OPEN", "USER", "DISTRIBUTED", "OPENDATASOURCE", "VALUES", "DOUBLE", "OPENQUERY", "VARYING", "DROP", "OPENROWSET", "VIEW", "DUMMY", "OPENXML", "WAITFOR", "DUMP", "OPTION", "WHEN", "ELSE", "OR", "WHERE", "END", "ORDER", "WHILE", "ERRLVL", "OUTER", "WITH", "ESCAPE", "OVER", "WRITETEXT");
- }
-
- public override bool SupportsIndex
- {
- get { return false; }
- }
-
- public override bool ColumnNameNeedsQuote
- {
- get { return true; }
- }
-
- public override bool TableNameNeedsQuote
- {
- get { return true; }
- }
-
- public override string QuoteTemplate
- {
- get { return "[{0}]"; }
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope, string providerName)
- {
- return new SqlServerTransformationProvider(dialect, connectionString, defaultSchema ?? DboSchemaName, scope, providerName);
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, IDbConnection connection,
- string defaultSchema,
- string scope, string providerName)
- {
- return new SqlServerTransformationProvider(dialect, connection, defaultSchema ?? DboSchemaName, scope, providerName);
- }
-
- public override string Quote(string value)
- {
- int firstDotIndex = value.IndexOf('.');
- if (firstDotIndex >= 0)
- {
- string owner = value.Substring(0, firstDotIndex);
- string table = value.Substring(firstDotIndex + 1);
- return (string.Format(QuoteTemplate, owner) + "." + string.Format(QuoteTemplate, table));
- }
- return string.Format(QuoteTemplate, value);
- }
-
- public override string Default(object defaultValue)
- {
- if (defaultValue.GetType().Equals(typeof (bool)))
- {
- return String.Format("DEFAULT {0}", (bool)defaultValue ? "1" : "0");
- }
- else if (defaultValue.GetType().Equals(typeof(Guid)))
- {
- return "DEFAULT '" + ((Guid) defaultValue).ToString("D") + "'";
- }
- else if (defaultValue.GetType().Equals(typeof(DateTime)))
- {
- return "DEFAULT CONVERT(DateTime,'"
- + ((DateTime)defaultValue).Year.ToString("D4") + '-'
- + ((DateTime)defaultValue).Month.ToString("D2") + '-'
- + ((DateTime)defaultValue).Day.ToString("D2") + ' '
- + ((DateTime)defaultValue).Hour.ToString("D2") + ':'
- + ((DateTime)defaultValue).Minute.ToString("D2") + ':'
- + ((DateTime)defaultValue).Second.ToString("D2") + '.'
- + ((DateTime)defaultValue).Millisecond.ToString("D3")
- + "',121)";
- }
-
- return base.Default(defaultValue);
- }
- }
-}
diff --git a/src/Migrator.Providers/Impl/SqlServer/SqlServerTransformationProvider.cs b/src/Migrator.Providers/Impl/SqlServer/SqlServerTransformationProvider.cs
deleted file mode 100644
index a7e11bdd..00000000
--- a/src/Migrator.Providers/Impl/SqlServer/SqlServerTransformationProvider.cs
+++ /dev/null
@@ -1,480 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using Migrator.Framework;
-
-namespace Migrator.Providers.SqlServer
-{
- ///
- /// Migration transformations provider for Microsoft SQL Server.
- ///
- public class SqlServerTransformationProvider : TransformationProvider
- {
- public SqlServerTransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope, string providerName)
- : base(dialect, connectionString, defaultSchema, scope)
- {
- CreateConnection(providerName);
- }
-
- public SqlServerTransformationProvider(Dialect dialect, IDbConnection connection, string defaultSchema, string scope, string providerName)
- : base(dialect, connection, defaultSchema, scope)
- {
- }
-
-
- protected virtual void CreateConnection(string providerName)
- {
- if (string.IsNullOrEmpty(providerName))
- providerName = "System.Data.SqlClient";
- var fac = DbProviderFactories.GetFactory(providerName);
- _connection = fac.CreateConnection(); // new SqlConnection();
- _connection.ConnectionString = _connectionString;
- _connection.Open();
-
- string collationString = null;
- var collation = this.ExecuteScalar("SELECT DATABASEPROPERTYEX('" + _connection.Database + "', 'Collation')");
- if (collation != null)
- collationString = collation.ToString();
- if (string.IsNullOrWhiteSpace(collationString))
- collationString = "Latin1_General_CI_AS";
- this.Dialect.RegisterProperty(ColumnProperty.CaseSensitive, "COLLATE " + collationString.Replace("_CI_", "_CS_"));
- }
-
- public override bool ConstraintExists(string table, string name)
- {
- bool retVal = false;
- using (IDataReader reader = ExecuteQuery(string.Format("SELECT TOP 1 * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME ='{0}'", name)))
- {
- retVal = reader.Read();
- }
-
- if (!retVal)
- using (IDataReader reader = ExecuteQuery(string.Format("SELECT TOP 1 * FROM SYS.DEFAULT_CONSTRAINTS WHERE PARENT_OBJECT_ID = OBJECT_ID('{0}') AND Name = '{1}'", table, name)))
- {
- return reader.Read();
- }
- return true;
- }
-
- public override void AddColumn(string table, string sqlColumn)
- {
- table = _dialect.TableNameNeedsQuote ? _dialect.Quote(table) : table;
- ExecuteNonQuery(string.Format("ALTER TABLE {0} ADD {1}", table, sqlColumn));
- }
-
- public override void AddIndex(string table, Index index)
- {
- if (IndexExists(table, index.Name))
- {
- Logger.Warn("Index {0} already exists", index.Name);
- return;
- }
-
- var name = QuoteConstraintNameIfRequired(index.Name);
-
- table = QuoteTableNameIfRequired(table);
-
- var columns = QuoteColumnNamesIfRequired(index.KeyColumns);
-
- if (index.IncludeColumns != null && index.IncludeColumns.Length > 0)
- {
- var include = QuoteColumnNamesIfRequired(index.IncludeColumns);
- ExecuteNonQuery(String.Format("CREATE {0}{1} INDEX {2} ON {3} ({4}) INCLUDE ({5})", (index.Unique ? "UNIQUE " : ""), (index.Clustered ? "CLUSTERED" : "NONCLUSTERED"), name, table, string.Join(", ", columns), string.Join(", ", include)));
- }
- else
- {
- ExecuteNonQuery(String.Format("CREATE {0}{1} INDEX {2} ON {3} ({4})", (index.Unique ? "UNIQUE " : ""), (index.Clustered ? "CLUSTERED" : "NONCLUSTERED"), name, table, string.Join(", ", columns)));
- }
- }
-
- public override void ChangeColumn(string table, Column column)
- {
- if (column.DefaultValue == null || column.DefaultValue == DBNull.Value)
- {
- base.ChangeColumn(table, column);
- }
- else
- {
- var def = column.DefaultValue;
- var notNull = column.ColumnProperty.IsSet(ColumnProperty.NotNull);
- column.DefaultValue = null;
- column.ColumnProperty = column.ColumnProperty.Set(ColumnProperty.Null);
- column.ColumnProperty = column.ColumnProperty.Clear(ColumnProperty.NotNull);
-
- base.ChangeColumn(table,column);
-
- ColumnPropertiesMapper mapper = _dialect.GetAndMapColumnPropertiesWithoutDefault(column);
- ExecuteNonQuery(string.Format("ALTER TABLE {0} ADD CONSTRAINT {1} {2} FOR {3}", this.QuoteTableNameIfRequired(table), "DF_" + table + "_" + column.Name, _dialect.Default(def), this.QuoteColumnNameIfRequired(column.Name)));
-
- if (notNull)
- {
- column.ColumnProperty = column.ColumnProperty.Set(ColumnProperty.NotNull);
- column.ColumnProperty = column.ColumnProperty.Clear(ColumnProperty.Null);
- base.ChangeColumn(table, column);
- }
- }
- }
-
- public override bool ColumnExists(string table, string column)
- {
- string schema;
- if (!TableExists(table))
- {
- return false;
- }
- int firstIndex = table.IndexOf(".");
- if (firstIndex >= 0)
- {
- schema = table.Substring(0, firstIndex);
- table = table.Substring(firstIndex + 1);
- }
- else
- {
- schema = _defaultSchema;
- }
- using (
- IDataReader reader = base.ExecuteQuery(string.Format("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{0}' AND TABLE_NAME='{1}' AND COLUMN_NAME='{2}'", schema, table, column)))
- {
- return reader.Read();
- }
- }
-
- public override void RemoveColumnDefaultValue(string table, string column)
- {
- var sql = string.Format("SELECT Name FROM SYS.DEFAULT_CONSTRAINTS WHERE PARENT_OBJECT_ID = OBJECT_ID('{0}') AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns WHERE NAME = '{1}' AND object_id = OBJECT_ID('{0}'))", table, column);
- var constraintName = ExecuteScalar(sql);
- if (constraintName != null)
- RemoveConstraint(table, constraintName.ToString());
- }
-
-
- public override bool TableExists(string table)
- {
- string schema;
-
- int firstIndex = table.IndexOf(".");
- if (firstIndex >= 0)
- {
- schema = table.Substring(0, firstIndex);
- table = table.Substring(firstIndex + 1);
- }
- else
- {
- schema = _defaultSchema;
- }
-
- using (IDataReader reader = base.ExecuteQuery(string.Format("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{0}' AND TABLE_SCHEMA='{1}'", table, schema)))
- {
- return reader.Read();
- }
- }
-
- public override Index[] GetIndexes(string table)
- {
- var retVal = new List();
-
- var sql = @"SELECT Tab.[name] AS TableName,
- Ind.[name] AS IndexName,
- Ind.[type_desc] AS IndexType,
- Ind.[is_unique] AS IndexUnique,
- SUBSTRING(( SELECT ',' + AC.name
- FROM sys.[tables] AS T
- INNER JOIN sys.[indexes] I ON T.[object_id] = I.[object_id]
- INNER JOIN sys.[index_columns] IC ON I.[object_id] = IC.[object_id]
- AND I.[index_id] = IC.[index_id]
- INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id]
- AND IC.[column_id] = AC.[column_id]
- WHERE Ind.[object_id] = I.[object_id]
- AND Ind.index_id = I.index_id
- AND IC.is_included_column = 0
- ORDER BY IC.key_ordinal
- FOR
- XML PATH('') ), 2, 8000) AS KeyCols,
- SUBSTRING(( SELECT ',' + AC.name
- FROM sys.[tables] AS T
- INNER JOIN sys.[indexes] I ON T.[object_id] = I.[object_id]
- INNER JOIN sys.[index_columns] IC ON I.[object_id] = IC.[object_id]
- AND I.[index_id] = IC.[index_id]
- INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id]
- AND IC.[column_id] = AC.[column_id]
- WHERE Ind.[object_id] = I.[object_id]
- AND Ind.index_id = I.index_id
- AND IC.is_included_column = 1
- ORDER BY IC.key_ordinal
- FOR
- XML PATH('') ), 2, 8000) AS IncludeCols
-FROM sys.[indexes] Ind
- INNER JOIN sys.[tables] AS Tab ON Tab.[object_id] = Ind.[object_id]
- WHERE LOWER(Tab.[name]) = LOWER('{0}')";
-
- using (var reader=ExecuteQuery(string.Format(sql, table)))
- {
- while (reader.Read())
- {
- if (!reader.IsDBNull(1))
- {
- var idx = new Index
- {
- Name = reader.GetString(1),
- Clustered = reader.GetString(2) == "CLUSTERED",
- PrimaryKey = reader.GetString(2) == "CLUSTERED",
- Unique = reader.GetBoolean(3)
- };
- if (!reader.IsDBNull(4)) idx.KeyColumns = (reader.GetString(4).Split(','));
- if (!reader.IsDBNull(5)) idx.IncludeColumns = (reader.GetString(5).Split(','));
- retVal.Add(idx);
- }
- }
- }
-
- return retVal.ToArray();
- }
-
- public override Column[] GetColumns(string table)
- {
- var pkColumns = new List();
- try
- {
- pkColumns = this.ExecuteStringQuery("SELECT cu.COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE cu WHERE EXISTS ( SELECT tc.* FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc WHERE tc.TABLE_NAME = '{0}' AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.CONSTRAINT_NAME = cu.CONSTRAINT_NAME )", table);
- }
- catch (Exception ex)
- { }
-
- var columns = new List();
- using (
- IDataReader reader =
- ExecuteQuery(
- String.Format("select COLUMN_NAME, IS_NULLABLE, DATA_TYPE, ISNULL(CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION), COLUMN_DEFAULT from INFORMATION_SCHEMA.COLUMNS where table_name = '{0}'", table)))
- {
- while (reader.Read())
- {
- var column = new Column(reader.GetString(0), DbType.String);
-
- if (pkColumns.Contains(column.Name))
- column.ColumnProperty |= ColumnProperty.PrimaryKey;
-
- string nullableStr = reader.GetString(1);
- bool isNullable = nullableStr == "YES";
- if (!reader.IsDBNull(2))
- {
- string type = reader.GetString(2);
- column.Type = Dialect.GetDbTypeFromString(type);
- }
- if (!reader.IsDBNull(3))
- {
- column.Size = reader.GetInt32(3);
- }
- if (!reader.IsDBNull(4))
- {
- column.DefaultValue = reader.GetValue(4);
-
- if (column.DefaultValue.ToString()[1] == '(' || column.DefaultValue.ToString()[1] == '\'')
- column.DefaultValue = column.DefaultValue.ToString().Substring(2, column.DefaultValue.ToString().Length - 4); // Example "((10))" or "('false')"
- else
- column.DefaultValue = column.DefaultValue.ToString().Substring(1, column.DefaultValue.ToString().Length - 2); // Example "(CONVERT([datetime],'20000101',(112)))"
-
- if (column.Type == DbType.Int16 || column.Type == DbType.Int32 || column.Type == DbType.Int64)
- column.DefaultValue = Int64.Parse(column.DefaultValue.ToString());
-
- if (column.Type == DbType.UInt16 || column.Type == DbType.UInt32 || column.Type == DbType.UInt64)
- column.DefaultValue = UInt64.Parse(column.DefaultValue.ToString());
-
- if (column.Type == DbType.Double || column.Type == DbType.Single)
- column.DefaultValue = double.Parse(column.DefaultValue.ToString());
- }
-
- column.ColumnProperty |= isNullable ? ColumnProperty.Null : ColumnProperty.NotNull;
-
- columns.Add(column);
- }
- }
-
- return columns.ToArray();
- }
-
- public override List GetDatabases()
- {
- return ExecuteStringQuery("SELECT name FROM sys.databases");
- }
-
- public override void DropDatabases(string databaseName)
- {
- ExecuteNonQuery(string.Format("USE [master]" + System.Environment.NewLine + "DROP DATABASE {0}", databaseName));
- }
-
- public override void RemoveColumn(string table, string column)
- {
- DeleteColumnConstraints(table, column);
- DeleteColumnIndexes(table, column);
- RemoveColumnDefaultValue(table, column);
- base.RemoveColumn(table, column);
- }
-
- public override void RenameColumn(string tableName, string oldColumnName, string newColumnName)
- {
- if (ColumnExists(tableName, newColumnName))
- throw new MigrationException(String.Format("Table '{0}' has column named '{1}' already", tableName, newColumnName));
-
- if (ColumnExists(tableName, oldColumnName))
- ExecuteNonQuery(String.Format("EXEC sp_rename '{0}.{1}', '{2}', 'COLUMN'", tableName, oldColumnName, newColumnName));
- }
-
- public override void RenameTable(string oldName, string newName)
- {
- if (TableExists(newName))
- {
- throw new MigrationException(String.Format("Table with name '{0}' already exists", newName));
- }
-
- if (!TableExists(oldName))
- {
- throw new MigrationException(String.Format("Table with name '{0}' does not exist to rename", oldName));
- }
-
- ExecuteNonQuery(String.Format("EXEC sp_rename '{0}', '{1}'", oldName, newName));
- }
-
- // Deletes all constraints linked to a column. Sql Server
- // doesn't seems to do this.
- void DeleteColumnConstraints(string table, string column)
- {
- string sqlContrainte = FindConstraints(table, column);
- var constraints = new List();
- using (IDataReader reader = ExecuteQuery(sqlContrainte))
- {
- while (reader.Read())
- {
- constraints.Add(reader.GetString(0));
- }
- }
- // Can't share the connection so two phase modif
- foreach (string constraint in constraints)
- {
- RemoveForeignKey(table, constraint);
- }
- }
-
- void DeleteColumnIndexes(string table, string column)
- {
- string sqlIndex = this.FindIndexes(table, column);
- var indexes = new List();
- using (IDataReader reader = ExecuteQuery(sqlIndex))
- {
- while (reader.Read())
- {
- indexes.Add(reader.GetString(0));
- }
- }
- // Can't share the connection so two phase modif
- foreach (string index in indexes)
- {
- this.RemoveIndex(table, index);
- }
- }
-
- protected virtual string FindIndexes(string table, string column)
- {
- return string.Format(@"
-select
- i.name as IndexName
-from sys.indexes i
-join sys.objects o on i.object_id = o.object_id
-join sys.index_columns ic on ic.object_id = i.object_id
- and ic.index_id = i.index_id
-join sys.columns co on co.object_id = i.object_id
- and co.column_id = ic.column_id
-where i.[type] = 2
-and o.[Name] = '{0}'
-and co.[Name] = '{1}'",
- table, column);
- }
-
- // FIXME: We should look into implementing this with INFORMATION_SCHEMA if possible
- // so that it would be usable by all the SQL Server implementations
- protected virtual string FindConstraints(string table, string column)
- {
- return string.Format(@"SELECT DISTINCT CU.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CU
-INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
-ON CU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME
-WHERE TC.CONSTRAINT_TYPE = 'FOREIGN KEY'
-AND CU.TABLE_NAME = '{0}'
-AND CU.COLUMN_NAME = '{1}'",
- table, column);
-
- /*return string.Format(
- "SELECT cont.name FROM sysobjects cont, syscolumns col, sysconstraints cnt "
- + "WHERE cont.parent_obj = col.id AND cnt.constid = cont.id AND cnt.colid=col.colid "
- + "AND col.name = '{1}' AND col.id = object_id('{0}')",
- table, column);*/
- }
-
- public override bool IndexExists(string table, string name)
- {
- using (IDataReader reader =
- ExecuteQuery(string.Format("SELECT top 1 * FROM sys.indexes WHERE object_id = OBJECT_ID('{0}') AND name = '{1}'", table, name)))
- {
- return reader.Read();
- }
- }
-
- public override void RemoveIndex(string table, string name)
- {
- if (TableExists(table) && IndexExists(table, name))
- {
- ExecuteNonQuery(String.Format("DROP INDEX {0} ON {1}", QuoteConstraintNameIfRequired(name), QuoteTableNameIfRequired(table)));
- }
- }
-
- protected override string GetPrimaryKeyConstraintName(string table)
- {
- using (IDataReader reader =
- ExecuteQuery(string.Format("SELECT name FROM sys.indexes WHERE object_id = OBJECT_ID('{0}') AND is_primary_key = 1", table)))
- {
- return reader.Read() ? reader.GetString(0) : null;
- }
- }
-
- protected override void ConfigureParameterWithValue(IDbDataParameter parameter, int index, object value)
- {
- if (value is UInt16)
- {
- parameter.DbType = DbType.Int32;
- parameter.Value = value;
- }
- else if (value is UInt32)
- {
- parameter.DbType = DbType.Int64;
- parameter.Value = value;
- }
- else if (value is UInt64)
- {
- parameter.DbType = DbType.Decimal;
- parameter.Value = value;
- }
- else
- {
- base.ConfigureParameterWithValue(parameter, index, value);
- }
- }
-
- public override string Concatenate(params string[] strings)
- {
- return string.Join(" + ", strings);
- }
- }
-}
diff --git a/src/Migrator.Providers/Impl/Sybase/SybaseDialect.cs b/src/Migrator.Providers/Impl/Sybase/SybaseDialect.cs
deleted file mode 100644
index c4575a65..00000000
--- a/src/Migrator.Providers/Impl/Sybase/SybaseDialect.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using System.Data;
-using Migrator.Framework;
-using Migrator.Providers.Impl.DB2;
-using Migrator.Providers.Impl.Ingres;
-
-namespace Migrator.Providers.Impl.Sybase
-{
- public class SybaseDialect : Dialect
- {
- public SybaseDialect()
- {
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope, string providerName)
- {
- return new SybaseTransformationProvider(dialect, connectionString, scope, providerName);
- }
-
- public override ITransformationProvider GetTransformationProvider(Dialect dialect, IDbConnection connection,
- string defaultSchema,
- string scope, string providerName)
- {
- return new SybaseTransformationProvider(dialect, connection, scope, providerName);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Impl/Sybase/SybaseTransformationProvider.cs b/src/Migrator.Providers/Impl/Sybase/SybaseTransformationProvider.cs
deleted file mode 100644
index 13fff94d..00000000
--- a/src/Migrator.Providers/Impl/Sybase/SybaseTransformationProvider.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.Common;
-
-namespace Migrator.Providers.Impl.Sybase
-{
- public class SybaseTransformationProvider : TransformationProvider
- {
- public SybaseTransformationProvider(Dialect dialect, string connectionString, string scope, string providerName)
- : base(dialect, connectionString, null, scope)
- {
- if (string.IsNullOrEmpty(providerName)) providerName = "Sybase.Data.AseClient";
- var fac = DbProviderFactories.GetFactory(providerName);
- _connection = fac.CreateConnection();
- _connection.ConnectionString = _connectionString;
- this._connection.Open();
- }
-
- public SybaseTransformationProvider(Dialect dialect, IDbConnection connection, string scope, string providerName)
- : base(dialect, connection, null, scope)
- {
- }
-
- public override List GetDatabases()
- {
- throw new NotImplementedException();
- }
-
- public override bool ConstraintExists(string table, string name)
- {
- throw new NotImplementedException();
- }
-
- public override bool IndexExists(string table, string name)
- {
- throw new NotImplementedException();
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/MigratorDotNet.snk b/src/Migrator.Providers/MigratorDotNet.snk
deleted file mode 100644
index 5032d709..00000000
Binary files a/src/Migrator.Providers/MigratorDotNet.snk and /dev/null differ
diff --git a/src/Migrator.Providers/NoOpTransformationProvider.cs b/src/Migrator.Providers/NoOpTransformationProvider.cs
deleted file mode 100644
index f54b6215..00000000
--- a/src/Migrator.Providers/NoOpTransformationProvider.cs
+++ /dev/null
@@ -1,508 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using Migrator.Framework;
-using Migrator.Framework.SchemaBuilder;
-
-using ForeignKeyConstraint = Migrator.Framework.ForeignKeyConstraint;
-
-namespace Migrator.Providers
-{
- ///
- /// No Op (Null Object Pattern) implementation of the ITransformationProvider
- ///
- public class NoOpTransformationProvider : ITransformationProvider
- {
- public static readonly NoOpTransformationProvider Instance = new NoOpTransformationProvider();
-
- NoOpTransformationProvider()
- {
- }
-
- public Dialect Dialect
- {
- get { return null; }
- }
-
- public string ConnectionString
- {
- get { return String.Empty; }
- }
-
- public virtual ILogger Logger
- {
- get { return null; }
- set { }
- }
-
- public string[] GetTables()
- {
- return null;
- }
-
- public ForeignKeyConstraint[] GetForeignKeyConstraints(string table)
- {
- return null;
- }
-
- public int Insert(string table, string[] columns, object[] values)
- {
- return 0;
- }
-
- public List ExecuteStringQuery(string sql, params object[] args)
- {
- return new List();
- }
-
- public Index[] GetIndexes(string table)
- {
- return null;
- }
-
- public Column[] GetColumns(string table)
- {
- return null;
- }
-
- public Column GetColumnByName(string table, string column)
- {
- return null;
- }
-
- public void RemoveForeignKey(string table, string name)
- {
- // No Op
- }
-
- public void RemoveConstraint(string table, string name)
- {
- // No Op
- }
-
- public void RemoveAllConstraints(string table)
- {
- // No Op
- }
-
- public void RemovePrimaryKey(string table)
- {
- // No Op
- }
-
- public void AddView(string name, string tableName, params IViewField[] fields)
- {
- // No Op
- }
-
- public void AddTable(string name, params IDbField[] columns)
- {
- // No Op
- }
-
- public void AddTable(string name, string engine, params IDbField[] columns)
- {
- // No Op
- }
-
- public void RemoveTable(string name)
- {
- // No Op
- }
-
- public void RenameTable(string oldName, string newName)
- {
- // No Op
- }
-
- public void RenameColumn(string tableName, string oldColumnName, string newColumnName)
- {
- // No Op
- }
-
- public void RemoveColumn(string table, string column)
- {
- // No Op
- }
-
- public void RemoveColumnDefaultValue(string table, string column)
- {
- // No Op
- }
-
- public bool ColumnExists(string table, string column)
- {
- return false;
- }
-
- public bool TableExists(string table)
- {
- return false;
- }
-
- public void AddColumn(string table, string column, DbType type, int size, ColumnProperty property, object defaultValue)
- {
- // No Op
- }
-
- public void AddColumn(string table, string column, DbType type)
- {
- // No Op
- }
-
- public void AddColumn(string table, string column, DbType type, object defaultValue)
- {
- // No Op
- }
-
- public void AddColumn(string table, string column, DbType type, int size)
- {
- // No Op
- }
-
- public void AddColumn(string table, string column, DbType type, ColumnProperty property)
- {
- // No Op
- }
-
- public void AddColumn(string table, string column, DbType type, int size, ColumnProperty property)
- {
- // No Op
- }
-
- public void AddPrimaryKey(string name, string table, params string[] columns)
- {
- // No Op
- }
-
- public void GenerateForeignKey(string primaryTable, string primaryColumn, string refTable, string refColumn)
- {
- // No Op
- }
-
- public void GenerateForeignKey(string primaryTable, string[] primaryColumns, string refTable, string[] refColumns)
- {
- // No Op
- }
-
- public void GenerateForeignKey(string primaryTable, string primaryColumn, string refTable, string refColumn, ForeignKeyConstraintType constraint)
- {
- // No Op
- }
-
- public void GenerateForeignKey(string primaryTable, string[] primaryColumns, string refTable,
- string[] refColumns, ForeignKeyConstraintType constraint)
- {
- // No Op
- }
-
- public void AddForeignKey(string name, string primaryTable, string primaryColumn, string refTable,
- string refColumn)
- {
- // No Op
- }
-
- public void AddForeignKey(string name, string primaryTable, string[] primaryColumns, string refTable, string[] refColumns)
- {
- // No Op
- }
-
- public void AddForeignKey(string name, string primaryTable, string primaryColumn, string refTable, string refColumn, ForeignKeyConstraintType constraint)
- {
- // No Op
- }
-
- public void AddForeignKey(string name, string primaryTable, string[] primaryColumns, string refTable,
- string[] refColumns, ForeignKeyConstraintType constraint)
- {
- // No Op
- }
-
- public void AddUniqueConstraint(string name, string table, params string[] columns)
- {
- // No Op
- }
-
- public void AddCheckConstraint(string name, string table, string checkSql)
- {
- // No Op
- }
-
- public bool ConstraintExists(string table, string name)
- {
- return false;
- }
-
- public void ChangeColumn(string table, Column column)
- {
- // No Op
- }
-
- public bool PrimaryKeyExists(string table, string name)
- {
- return false;
- }
-
- public int ExecuteNonQuery(string sql)
- {
- return 0;
- }
- public int ExecuteNonQuery(string sql, int timeout)
- {
- return 0;
- }
- public int ExecuteNonQuery(string sql, int timeout, object[] parameters)
- {
- return 0;
- }
-
- public IDataReader ExecuteQuery(string sql)
- {
- return null;
- }
-
- public object ExecuteScalar(string sql)
- {
- return null;
- }
-
- public IDataReader Select(string what, string from)
- {
- return null;
- }
-
- public IDataReader Select(string what, string from, string where)
- {
- return null;
- }
-
- public object SelectScalar(string what, string from)
- {
- return null;
- }
-
- public object SelectScalar(string what, string from, string where)
- {
- return null;
- }
-
- public int Update(string table, string[] columns, object[] values)
- {
- return 0;
- }
-
- public int Update(string table, string[] columns, object[] values, string where)
- {
- return 0;
- }
-
- public int Update(string table, string[] columns, object[] values, string[] whereColumns, object[] whereValues)
- {
- return 0;
- }
-
- public int Delete(string table, string[] columns, string[] columnValues)
- {
- return 0;
- }
-
- public int Delete(string table, string column, string value)
- {
- return 0;
- }
-
- public int TruncateTable(string table)
- {
- return 0;
- }
-
- public void BeginTransaction()
- {
- // No Op
- }
-
- public void Rollback()
- {
- // No Op
- }
-
- public void Commit()
- {
- // No Op
- }
-
- public ITransformationProvider this[string provider]
- {
- get { return this; }
- }
-
- public string SchemaInfoTable { get; set; }
-
- public void MigrationApplied(long version, string scope)
- {
- //no op
- }
-
- public void MigrationUnApplied(long version, string scope)
- {
- //no op
- }
-
- public List AppliedMigrations
- {
- get { return new List(); }
- }
-
- public void AddColumn(string table, Column column)
- {
- // No Op
- }
-
- public void GenerateForeignKey(string primaryTable, string refTable)
- {
- // No Op
- }
-
- public void GenerateForeignKey(string primaryTable, string refTable, ForeignKeyConstraintType constraint)
- {
- // No Op
- }
-
- public IDbCommand GetCommand()
- {
- return null;
- }
-
- public void ExecuteSchemaBuilder(SchemaBuilder schemaBuilder)
- {
- // No Op
- }
-
- public void RemoveAllForeignKeys(string tableName, string columnName)
- {
-
- }
-
- public bool IsThisProvider(string provider)
- {
- return false;
- }
-
- public string[] QuoteColumnNamesIfRequired(params string[] columnNames)
- {
- throw new NotImplementedException();
- }
-
- public string QuoteColumnNameIfRequired(string name)
- {
- throw new NotImplementedException();
- }
-
- public string QuoteTableNameIfRequired(string name)
- {
- throw new NotImplementedException();
- }
-
- public string Encode(Guid guid)
- {
- return guid.ToString();
- }
-
- public void SwitchDatabase(string databaseName)
- {
-
- }
-
- public List GetDatabases()
- {
- return new List();
- }
-
- public bool DatabaseExists(string name)
- {
- return true;
- }
-
- public void CreateDatabases(string databaseName)
- {
-
- }
-
- public void DropDatabases(string databaseName)
- {
-
- }
-
- public void AddIndex(string table, Index index)
- {
-
- }
-
- public void Dispose()
- {
- //No Op
- }
-
- public void AddColumn(string table, string sqlColumn)
- {
- // No Op
- }
-
- public int Insert(string table, string[] columns, string[] columnValues)
- {
- return 0;
- }
-
- protected void CreateSchemaInfoTable()
- {
- }
-
- public void RemoveIndex(string table, string name)
- {
- // No Op
- }
-
- public void AddIndex(string name, string table, params string[] columns)
- {
- // No Op
- }
-
- public bool IndexExists(string table, string name)
- {
- return false;
- }
-
- public string GenerateParameterName(int index)
- {
- return "@p" + index;
- }
-
- public void RemoveAllIndexes(string table)
- {
- // No Op
- }
-
- public string Concatenate(params string[] strings)
- {
- return "";
- }
-
- public IDbConnection Connection
- {
- get
- {
- return null;
- }
- }
-
- public IEnumerable GetTables(string schema)
- {
- throw new NotImplementedException();
- }
-
- public IEnumerable GetColumns(string schema, string table)
- {
- throw new NotImplementedException();
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/ProviderTypes.cs b/src/Migrator.Providers/ProviderTypes.cs
deleted file mode 100644
index 80c3d459..00000000
--- a/src/Migrator.Providers/ProviderTypes.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace Migrator.Providers
-{
- public enum ProviderTypes
- {
- none,
- SqlServer2005,
- SqlServerCe,
- SqlServer,
- Mysql,
- MariaDB,
- SQLite,
- MonoSQLite,
- PostgreSQL82,
- PostgreSQL,
- Oracle,
- MsOracle,
- IBM_DB2,
- IBM_Informix,
- Firebird,
- Ingres,
- Sybase,
- }
-}
diff --git a/src/Migrator.Providers/TransformationProvider.cs b/src/Migrator.Providers/TransformationProvider.cs
deleted file mode 100644
index bc83be8a..00000000
--- a/src/Migrator.Providers/TransformationProvider.cs
+++ /dev/null
@@ -1,1630 +0,0 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.Common;
-using System.IO;
-using System.Linq;
-using System.Text;
-using Migrator.Framework;
-using Migrator.Framework.Loggers;
-using Migrator.Framework.SchemaBuilder;
-using Migrator.Framework.Support;
-
-using ForeignKeyConstraintType = Migrator.Framework.ForeignKeyConstraintType;
-using ForeignKeyConstraint = Migrator.Framework.ForeignKeyConstraint;
-
-namespace Migrator.Providers
-{
- ///
- /// Base class for every transformation providers.
- /// A 'tranformation' is an operation that modifies the database.
- ///
- public abstract class TransformationProvider : ITransformationProvider
- {
- private string _scope;
- protected readonly string _connectionString;
- protected readonly string _defaultSchema;
- readonly ForeignKeyConstraintMapper constraintMapper = new ForeignKeyConstraintMapper();
- protected List _appliedMigrations;
- protected IDbConnection _connection;
- protected bool _outsideConnection = false;
- protected Dialect _dialect;
- ILogger _logger;
- IDbTransaction _transaction;
-
- protected TransformationProvider(Dialect dialect, string connectionString, string defaultSchema, string scope)
- {
- _dialect = dialect;
- _connectionString = connectionString;
- _defaultSchema = defaultSchema;
- _logger = new Logger(false);
- _scope = scope;
- }
-
- protected TransformationProvider(Dialect dialect, IDbConnection connection, string defaultSchema, string scope)
- {
- _dialect = dialect;
- _connection = connection;
- _outsideConnection = true;
- _defaultSchema = defaultSchema;
- _logger = new Logger(false);
- _scope = scope;
- }
-
- public IMigration CurrentMigration { get; set; }
-
- private string _schemaInfotable = "SchemaInfo";
- public string SchemaInfoTable
- {
- get
- {
- return _schemaInfotable;
- }
- set
- {
- _schemaInfotable = value;
- }
- }
-
- public Dialect Dialect
- {
- get { return _dialect; }
- }
-
- public string ConnectionString { get { return _connectionString; }}
-
- ///
- /// Returns the event logger
- ///
- public virtual ILogger Logger
- {
- get { return _logger; }
- set { _logger = value; }
- }
-
- public virtual ITransformationProvider this[string provider]
- {
- get
- {
- if (null != provider && IsThisProvider(provider))
- return this;
-
- return NoOpTransformationProvider.Instance;
- }
- }
-
- public virtual Index[] GetIndexes(string table)
- {
- throw new NotImplementedException();
- }
-
- public virtual Column[] GetColumns(string table)
- {
- var columns = new List();
- using (
- IDataReader reader =
- ExecuteQuery(
- String.Format("select COLUMN_NAME, IS_NULLABLE from INFORMATION_SCHEMA.COLUMNS where table_name = '{0}'", table)))
- {
- while (reader.Read())
- {
- var column = new Column(reader.GetString(0), DbType.String);
- string nullableStr = reader.GetString(1);
- bool isNullable = nullableStr == "YES";
- column.ColumnProperty |= isNullable ? ColumnProperty.Null : ColumnProperty.NotNull;
-
- columns.Add(column);
- }
- }
-
- return columns.ToArray();
- }
-
- public ForeignKeyConstraint[] GetForeignKeyConstraints(string table)
- {
- var constraints = new List();
- using (
- IDataReader reader =
- ExecuteQuery(
- String.Format("SELECT K_Table = FK.TABLE_NAME, FK_Column = CU.COLUMN_NAME, PK_Table = PK.TABLE_NAME, PK_Column = PT.COLUMN_NAME, Constraint_Name = C.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME INNER JOIN ( SELECT i1.TABLE_NAME, i2.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' ) PT ON PT.TABLE_NAME = PK.TABLE_NAME WHERE FK.table_name = '{0}'", table)))
- {
- while (reader.Read())
- {
- var constraint = new ForeignKeyConstraint();
- constraint.Name = reader.GetString(4);
- constraint.Table = reader.GetString(0);
- constraint.Columns = new[] { reader.GetString(1) };
- constraint.PkTable = reader.GetString(2);
- constraint.PkColumns = new[] { reader.GetString(3) };
-
- constraints.Add(constraint);
- }
- }
-
- return constraints.ToArray();
- }
-
- public virtual string[] GetConstraints(string table)
- {
- var constraints = new List();
- using (
- IDataReader reader =
- ExecuteQuery(
- String.Format("SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE LOWER(TABLE_NAME) = LOWER('{0}')", table)))
- {
- while (reader.Read())
- {
- constraints.Add(reader.GetString(0));
- }
- }
-
- return constraints.ToArray();
- }
-
- public virtual Column GetColumnByName(string table, string columnName)
- {
- var columns = GetColumns(table);
- return columns.First(column => column.Name.Equals(columnName, StringComparison.OrdinalIgnoreCase));
- }
-
- public virtual string[] GetTables()
- {
- var tables = new List();
- using (IDataReader reader = ExecuteQuery("SELECT table_name FROM INFORMATION_SCHEMA.TABLES"))
- {
- while (reader.Read())
- {
- tables.Add((string)reader[0]);
- }
- }
- return tables.ToArray();
- }
-
- public virtual void RemoveForeignKey(string table, string name)
- {
- RemoveConstraint(table, name);
- }
-
- public virtual void RemoveConstraint(string table, string name)
- {
- if (TableExists(table) && ConstraintExists(table, name))
- {
- ExecuteNonQuery(String.Format("ALTER TABLE {0} DROP CONSTRAINT {1}", QuoteTableNameIfRequired(table), QuoteConstraintNameIfRequired(name)));
- }
- }
-
- public virtual void RemoveAllConstraints(string table)
- {
- foreach (var constraint in GetConstraints(table))
- {
- this.RemoveConstraint(table, constraint);
- }
- }
-
- public virtual void AddView(string name, string tableName, params IViewField[] fields)
- {
- var lst =
- fields.Where(x => string.IsNullOrEmpty(x.TableName) || x.TableName == tableName)
- .Select(x => x.ColumnName)
- .ToList();
-
- int nr = 0;
- string joins = "";
- foreach (var joinTable in fields.Where(x => !string.IsNullOrEmpty(x.TableName) && x.TableName != tableName).GroupBy(x=>x.TableName))
- {
- foreach (var viewField in joinTable)
- {
- joins += string.Format("JOIN {0} {1} ON {1}.{2} = {3}.{4} ", viewField.TableName, " T" + nr,
- viewField.KeyColumnName, viewField.ParentTableName, viewField.ParentKeyColumnName);
- lst.Add(" T" + nr + "." + viewField.ColumnName);
- }
- }
-
- var select = string.Format("SELECT {0} FROM {1} {2}", string.Join(",", lst), tableName, joins);
-
- var sql = string.Format("CREATE VIEW {0} AS {1}", name, select);
-
- ExecuteNonQuery(sql);
- }
-
- ///
- /// Add a new table
- ///
- /// Table name
- /// Columns
- ///
- /// Adds the Test table with two columns:
- ///
- /// Database.AddTable("Test",
- /// new Column("Id", typeof(int), ColumnProperty.PrimaryKey),
- /// new Column("Title", typeof(string), 100)
- /// );
- ///
- ///
- public virtual void AddTable(string name, params IDbField[] columns)
- {
- // Most databases don't have the concept of a storage engine, so default is to not use it.
- AddTable(name, null, columns);
- }
-
- ///
- /// Add a new table
- ///
- /// Table name
- /// Columns
- /// the database storage engine to use
- ///
- /// Adds the Test table with two columns:
- ///
- /// Database.AddTable("Test", "INNODB",
- /// new Column("Id", typeof(int), ColumnProperty.PrimaryKey),
- /// new Column("Title", typeof(string), 100)
- /// );
- ///
- ///
- public virtual void AddTable(string name, string engine, params IDbField[] fields)
- {
- if (TableExists(name))
- {
- Logger.Warn("Table {0} already exists", name);
- return;
- }
-
- if (name.Length > 30)
- {
- Logger.Warn("Tablename {0} is bigger then 30 char's This is a Problem if you want to use Oracle!", name);
- }
-
- var columns = fields.Where(x => x is Column).Cast().ToArray();
-
- List pks = GetPrimaryKeys(columns);
- bool compoundPrimaryKey = pks.Count > 1;
-
- var columnProviders = new List(columns.Count());
- foreach (Column column in columns)
- {
- // Remove the primary key notation if compound primary key because we'll add it back later
- if (compoundPrimaryKey && column.IsPrimaryKey)
- {
- column.ColumnProperty = column.ColumnProperty ^ ColumnProperty.PrimaryKey;
- column.ColumnProperty = column.ColumnProperty | ColumnProperty.NotNull; // PK is always not-null
- }
-
- ColumnPropertiesMapper mapper = _dialect.GetAndMapColumnProperties(column);
- columnProviders.Add(mapper);
- }
-
- string columnsAndIndexes = JoinColumnsAndIndexes(columnProviders);
- AddTable(name, engine, columnsAndIndexes);
-
- if (compoundPrimaryKey)
- {
- AddPrimaryKey(getPrimaryKeyname(name), name, pks.ToArray());
- }
-
- var indexes = fields.Where(x => x is Index).Cast().ToArray();
- foreach (var index in indexes)
- {
- AddIndex(name, index);
- }
-
- var foreignKeys = fields.Where(x => x is ForeignKeyConstraint).Cast().ToArray();
- foreach (var foreignKey in foreignKeys)
- {
- this.AddForeignKey(name, foreignKey);
- }
- }
-
- protected virtual string getPrimaryKeyname(string tableName)
- {
- return "PK_" + tableName;
- }
- public virtual void RemoveTable(string name)
- {
- if (!TableExists(name))
- {
- throw new MigrationException(String.Format("Table with name '{0}' does not exist to rename", name));
- }
-
- ExecuteNonQuery(String.Format("DROP TABLE {0}", name));
- }
-
- public virtual void RenameTable(string oldName, string newName)
- {
- oldName = QuoteTableNameIfRequired(oldName);
- newName = QuoteTableNameIfRequired(newName);
-
- if (TableExists(newName))
- {
- throw new MigrationException(String.Format("Table with name '{0}' already exists", newName));
- }
-
- if (!TableExists(oldName))
- {
- throw new MigrationException(String.Format("Table with name '{0}' does not exist to rename", oldName));
- }
-
- ExecuteNonQuery(String.Format("ALTER TABLE {0} RENAME TO {1}", oldName, newName));
- }
-
- public virtual void RenameColumn(string tableName, string oldColumnName, string newColumnName)
- {
- if (ColumnExists(tableName, newColumnName))
- {
- throw new MigrationException(String.Format("Table '{0}' has column named '{1}' already", tableName, newColumnName));
- }
-
- if (!ColumnExists(tableName, oldColumnName))
- {
- throw new MigrationException(string.Format("The table '{0}' does not have a column named '{1}'", tableName, oldColumnName));
- }
-
- var column = GetColumnByName(tableName, oldColumnName);
-
- var quotedNewColumnName = QuoteColumnNameIfRequired(newColumnName);
-
- ExecuteNonQuery(String.Format("ALTER TABLE {0} RENAME COLUMN {1} TO {2}", tableName, Dialect.Quote(column.Name), quotedNewColumnName));
- }
-
- public virtual void RemoveColumn(string table, string column)
- {
- if (!ColumnExists(table, column, true))
- {
- throw new MigrationException(string.Format("The table '{0}' does not have a column named '{1}'", table, column));
- }
-
- var existingColumn = GetColumnByName(table, column);
-
- ExecuteNonQuery(String.Format("ALTER TABLE {0} DROP COLUMN {1} ", table, Dialect.Quote(existingColumn.Name)));
- }
-
- public virtual bool ColumnExists(string table, string column)
- {
- return ColumnExists(table, column, true);
- }
-
- public virtual bool ColumnExists(string table, string column, bool ignoreCase)
- {
- try
- {
- if (ignoreCase)
- return GetColumns(table).Any(col => col.Name.ToLower() == column.ToLower());
- return GetColumns(table).Any(col => col.Name == column);
- }
- catch (Exception ex)
- {
- return false;
- }
- }
-
- public virtual void ChangeColumn(string table, Column column)
- {
- var isUniqueSet = column.ColumnProperty.IsSet(ColumnProperty.Unique);
-
- column.ColumnProperty = column.ColumnProperty.Clear(ColumnProperty.Unique);
-
- if (!ColumnExists(table, column.Name))
- {
- Logger.Warn("Column {0}.{1} does not exist", table, column.Name);
- return;
- }
-
- ColumnPropertiesMapper mapper = _dialect.GetAndMapColumnProperties(column);
-
- ChangeColumn(table, mapper.ColumnSql);
-
- if (isUniqueSet)
- {
- AddUniqueConstraint(string.Format("UX_{0}_{1}", table, column.Name), table, new string[]{column.Name});
- }
- }
-
- public virtual void RemoveColumnDefaultValue(string table, string column)
- {
- var sql = string.Format("ALTER TABLE {0} ALTER {1} DROP DEFAULT", table, column);
- ExecuteNonQuery(sql);
- }
-
- public virtual bool TableExists(string table)
- {
- try
- {
- ExecuteNonQuery("SELECT COUNT(*) FROM " + table);
- return true;
- }
- catch (Exception)
- {
- return false;
- }
- }
-
- public virtual void SwitchDatabase(string databaseName)
- {
- _connection.ChangeDatabase(databaseName);
- }
-
- public abstract List GetDatabases();
-
- public bool DatabaseExists(string name)
- {
- return GetDatabases().Any(c => string.Equals(name, c, StringComparison.InvariantCultureIgnoreCase));
- }
-
- public virtual void CreateDatabases(string databaseName)
- {
- ExecuteNonQuery(string.Format("CREATE DATABASE {0}", databaseName));
- }
-
- public virtual void DropDatabases(string databaseName)
- {
- ExecuteNonQuery(string.Format("DROP DATABASE {0}", databaseName));
- }
-
- ///
- /// Add a new column to an existing table.
- ///
- /// Table to which to add the column
- /// Column name
- /// Date type of the column
- /// Max length of the column
- /// Properties of the column, see ColumnProperty,
- /// Default value
- public virtual void AddColumn(string table, string column, DbType type, int size, ColumnProperty property,
- object defaultValue)
- {
- if (ColumnExists(table, column))
- {
- Logger.Warn("Column {0}.{1} already exists", table, column);
- return;
- }
-
- if (column.Length > 30)
- {
- Logger.Warn("Columnname {0} is bigger then 30 char's This is a Problem if you want to use Oracle!", column);
- }
-
- ColumnPropertiesMapper mapper =
- _dialect.GetAndMapColumnProperties(new Column(column, type, size, property, defaultValue));
-
- AddColumn(table, mapper.ColumnSql);
- }
-
- ///
- ///
- /// AddColumn(string, string, Type, int, ColumnProperty, object)
- ///
- ///
- public virtual void AddColumn(string table, string column, DbType type)
- {
- AddColumn(table, column, type, 0, ColumnProperty.Null, null);
- }
-
- ///
- ///
- /// AddColumn(string, string, Type, int, ColumnProperty, object)
- ///
- ///
- public virtual void AddColumn(string table, string column, DbType type, int size)
- {
- AddColumn(table, column, type, size, ColumnProperty.Null, null);
- }
-
- public virtual void AddColumn(string table, string column, DbType type, object defaultValue)
- {
- if (ColumnExists(table, column))
- {
- Logger.Warn("Column {0}.{1} already exists", table, column);
- return;
- }
-
- ColumnPropertiesMapper mapper =
- _dialect.GetAndMapColumnProperties(new Column(column, type, defaultValue));
-
- AddColumn(table, mapper.ColumnSql);
- }
-
- ///
- ///
- /// AddColumn(string, string, Type, int, ColumnProperty, object)
- ///
- ///
- public virtual void AddColumn(string table, string column, DbType type, ColumnProperty property)
- {
- AddColumn(table, column, type, 0, property, null);
- }
-
- ///
- ///
- /// AddColumn(string, string, Type, int, ColumnProperty, object)
- ///
- ///
- public virtual void AddColumn(string table, string column, DbType type, int size, ColumnProperty property)
- {
- AddColumn(table, column, type, size, property, null);
- }
-
- ///
- /// Append a primary key to a table.
- ///
- /// Constraint name
- /// Table name
- /// Primary column names
- public virtual void AddPrimaryKey(string name, string table, params string[] columns)
- {
- if (ConstraintExists(table, name))
- {
- Logger.Warn("Primary key {0} already exists", name);
- return;
- }
-
- ExecuteNonQuery(
- String.Format("ALTER TABLE {0} ADD CONSTRAINT {1} PRIMARY KEY ({2}) ", table, name,
- String.Join(",", QuoteColumnNamesIfRequired(columns))));
- }
-
- public virtual void AddUniqueConstraint(string name, string table, params string[] columns)
- {
- if (ConstraintExists(table, name))
- {
- Logger.Warn("Constraint {0} already exists", name);
- return;
- }
-
- QuoteColumnNames(columns);
-
- table = QuoteTableNameIfRequired(table);
-
- ExecuteNonQuery(String.Format("ALTER TABLE {0} ADD CONSTRAINT {1} UNIQUE({2}) ", table, name, string.Join(", ", columns)));
- }
-
- public virtual void AddCheckConstraint(string name, string table, string checkSql)
- {
- if (ConstraintExists(table, name))
- {
- Logger.Warn("Constraint {0} already exists", name);
- return;
- }
-
- table = QuoteTableNameIfRequired(table);
-
- ExecuteNonQuery(String.Format("ALTER TABLE {0} ADD CONSTRAINT {1} CHECK ({2}) ", table, name, checkSql));
- }
-
- ///
- /// Guesses the name of the foreign key and add it
- ///
- public virtual void GenerateForeignKey(string primaryTable, string primaryColumn, string refTable, string refColumn)
- {
- AddForeignKey("FK_" + primaryTable + "_" + refTable, primaryTable, primaryColumn, refTable, refColumn);
- }
-
- ///
- /// Guesses the name of the foreign key and add it
- ///
- ///
- public virtual void GenerateForeignKey(string primaryTable, string[] primaryColumns, string refTable,
- string[] refColumns)
- {
- AddForeignKey("FK_" + primaryTable + "_" + refTable, primaryTable, primaryColumns, refTable, refColumns);
- }
-
- ///
- /// Guesses the name of the foreign key and add it
- ///
- public virtual void GenerateForeignKey(string primaryTable, string primaryColumn, string refTable,
- string refColumn, ForeignKeyConstraintType constraint)
- {
- AddForeignKey("FK_" + primaryTable + "_" + refTable, primaryTable, primaryColumn, refTable, refColumn,
- constraint);
- }
-
- ///
- /// Guesses the name of the foreign key and add it
- ///
- ///
- public virtual void GenerateForeignKey(string primaryTable, string[] primaryColumns, string refTable,
- string[] refColumns, ForeignKeyConstraintType constraint)
- {
- AddForeignKey("FK_" + primaryTable + "_" + refTable, primaryTable, primaryColumns, refTable, refColumns,
- constraint);
- }
-
- public virtual void AddForeignKey(string table, ForeignKeyConstraint fk)
- {
- AddForeignKey(fk.Name, table, fk.Columns, fk.PkTable, fk.PkColumns);
- }
-
- public virtual void AddForeignKey(string name, string primaryTable, string primaryColumn, string refTable, string refColumn)
- {
- try
- {
- AddForeignKey(name, primaryTable, new[] { primaryColumn }, refTable, new[] { refColumn });
- }
- catch (Exception ex)
- {
- throw new Exception(string.Format("Error occured while adding foreign key: \"{0}\" between table: \"{1}\" and table: \"{2}\" - see inner exception for details", name, primaryTable, refTable), ex);
- }
- }
-
-
- ///
- ///
- /// AddForeignKey(string, string, string, string, string)
- ///
- ///
- public virtual void AddForeignKey(string name, string primaryTable, string[] primaryColumns, string refTable, string[] refColumns)
- {
- AddForeignKey(name, primaryTable, primaryColumns, refTable, refColumns, ForeignKeyConstraintType.NoAction);
- }
-
- public virtual void AddForeignKey(string name, string primaryTable, string primaryColumn, string refTable, string refColumn, ForeignKeyConstraintType constraint)
- {
- AddForeignKey(name, primaryTable, new[] { primaryColumn }, refTable, new[] { refColumn },
- constraint);
- }
-
- public virtual void AddForeignKey(string name, string primaryTable, string[] primaryColumns, string refTable,
- string[] refColumns, ForeignKeyConstraintType constraint)
- {
- if (ConstraintExists(primaryTable, name))
- {
- Logger.Warn("Constraint {0} already exists", name);
- return;
- }
-
- refTable = QuoteTableNameIfRequired(refTable);
- primaryTable = QuoteTableNameIfRequired(primaryTable);
- QuoteColumnNames(primaryColumns);
- QuoteColumnNames(refColumns);
-
- string constraintResolved = constraintMapper.SqlForConstraint(constraint);
-
- ExecuteNonQuery(
- String.Format(
- "ALTER TABLE {0} ADD CONSTRAINT {1} FOREIGN KEY ({2}) REFERENCES {3} ({4}) ON UPDATE {5} ON DELETE {6}",
- primaryTable, name, String.Join(",", primaryColumns),
- refTable, String.Join(",", refColumns), constraintResolved, constraintResolved));
- }
-
- ///
- /// Determines if a constraint exists.
- ///
- /// Constraint name
- /// Table owning the constraint
- /// true if the constraint exists.
- public abstract bool ConstraintExists(string table, string name);
-
- public virtual bool PrimaryKeyExists(string table, string name)
- {
- return ConstraintExists(table, name);
- }
-
- public virtual int ExecuteNonQuery(string sql)
- {
- return ExecuteNonQuery(sql, 30);
- }
-
- public virtual int ExecuteNonQuery(string sql, int timeout)
- {
- return this.ExecuteNonQuery(sql, timeout, null);
- }
-
- public virtual int ExecuteNonQuery(string sql, int timeout, params object[] args)
- {
- if (args==null)
- {
- Logger.Trace(sql);
- Logger.ApplyingDBChange(sql);
- }
- else
- {
- Logger.Trace(string.Format(sql, args));
- Logger.ApplyingDBChange(string.Format(sql, args));
- }
-
- using (IDbCommand cmd = BuildCommand(sql))
- {
- try
- {
- cmd.CommandTimeout = timeout;
-
- if (args != null)
- {
- int index = 0;
- foreach (object obj in args)
- {
- IDbDataParameter parameter = cmd.CreateParameter();
- this.ConfigureParameterWithValue(parameter, index, obj);
- parameter.ParameterName = this.GenerateParameterName(index);
- cmd.Parameters.Add((object)parameter);
- ++index;
- }
- }
-
- return cmd.ExecuteNonQuery();
- }
- catch (Exception ex)
- {
- Logger.Warn(ex.Message);
- throw new Exception(string.Format("Error occured executing sql: {0}, see inner exception for details, error: " + ex, sql), ex);
- }
- }
- }
-
- public List ExecuteStringQuery(string sql, params object[] args)
- {
- var values = new List();
-
- using (var reader = ExecuteQuery(string.Format(sql, args)))
- {
- while (reader.Read())
- {
- var value = reader[0];
-
- if (value == null || value == DBNull.Value)
- {
- values.Add(null);
- }
- else
- {
- values.Add(value.ToString());
- }
- }
- }
-
- return values;
- }
-
- public virtual void ExecuteScript(string fileName)
- {
- if (CurrentMigration != null)
- {
- var assembly = CurrentMigration.GetType().Assembly;
-
- string sqlText;
- string file = (new System.Uri(assembly.CodeBase)).AbsolutePath;
- using (var reader = File.OpenText(file))
- sqlText = reader.ReadToEnd();
-
- ExecuteNonQuery(sqlText);
- }
- }
-
- public virtual void ExecuteEmbededScript(string resourceName)
- {
- if (CurrentMigration != null)
- {
- var assembly = CurrentMigration.GetType().Assembly;
-
- string sqlText;
- string embeddedResourceName = TransformationProviderUtility.GetQualifiedResourcePath(assembly, resourceName);
-
- using (var stream = assembly.GetManifestResourceStream(embeddedResourceName))
- using (var reader = new StreamReader(stream))
- {
- sqlText = reader.ReadToEnd();
- }
- ExecuteNonQuery(sqlText);
- }
- }
-
- ///
- /// Execute an SQL query returning results.
- ///
- /// The SQL command.
- /// A data iterator, IDataReader.
- public virtual IDataReader ExecuteQuery(string sql)
- {
- Logger.Trace(sql);
- using (IDbCommand cmd = BuildCommand(sql))
- {
- try
- {
- return cmd.ExecuteReader();
- }
- catch (Exception ex)
- {
- Logger.Warn("query failed: {0}", cmd.CommandText);
- throw new Exception("Failed to execute sql statement: " + sql, ex);
- }
- }
- }
-
- public virtual object ExecuteScalar(string sql)
- {
- Logger.Trace(sql);
- using (IDbCommand cmd = BuildCommand(sql))
- {
- try
- {
- return cmd.ExecuteScalar();
- }
- catch
- {
- Logger.Warn("Query failed: {0}", cmd.CommandText);
- throw;
- }
- }
- }
-
- public virtual IDataReader Select(string what, string from)
- {
- return Select(what, from, "1=1");
- }
-
- public virtual IDataReader Select(string what, string from, string where)
- {
- return ExecuteQuery(String.Format("SELECT {0} FROM {1} WHERE {2}", what, from, where));
- }
-
- public object SelectScalar(string what, string from)
- {
- return SelectScalar(what, from, "1=1");
- }
-
- public virtual object SelectScalar(string what, string from, string where)
- {
- return ExecuteScalar(String.Format("SELECT {0} FROM {1} WHERE {2}", what, from, where));
- }
-
- public virtual int Update(string table, string[] columns, object[] values)
- {
- return Update(table, columns, values, null);
- }
-
- public virtual int Update(string table, string[] columns, object[] values, string where)
- {
- if (string.IsNullOrEmpty(table)) throw new ArgumentNullException("table");
- if (columns == null) throw new ArgumentNullException("columns");
- if (values == null) throw new ArgumentNullException("values");
- if (columns.Length != values.Length) throw new Exception(string.Format("The number of columns: {0} does not match the number of supplied values: {1}", columns.Length, values.Length));
-
- table = QuoteTableNameIfRequired(table);
-
- var builder = new StringBuilder();
- for (int i = 0; i < values.Length; i++)
- {
- if (builder.Length > 0) builder.Append(", ");
- builder.Append(QuoteColumnNameIfRequired(columns[i]));
- builder.Append(" = ");
- builder.Append(GenerateParameterName(i));
- }
-
- using (IDbCommand command = _connection.CreateCommand())
- {
- command.Transaction = _transaction;
-
- var query = String.Format("UPDATE {0} SET {1}", table, builder.ToString());
- if (!String.IsNullOrEmpty(where))
- {
- query += " WHERE " + where;
- }
- command.CommandText = query;
- command.CommandType = CommandType.Text;
-
- int paramCount = 0;
-
- foreach (object value in values)
- {
- IDbDataParameter parameter = command.CreateParameter();
-
- ConfigureParameterWithValue(parameter, paramCount, value);
-
- parameter.ParameterName = GenerateParameterName(paramCount);
-
- command.Parameters.Add(parameter);
-
- paramCount++;
- }
-
- return command.ExecuteNonQuery();
- }
- }
-
- public virtual int Update(string table, string[] columns, object[] values, string[] whereColumns, object[] whereValues)
- {
- if (string.IsNullOrEmpty(table)) throw new ArgumentNullException("table");
- if (columns == null) throw new ArgumentNullException("columns");
- if (values == null) throw new ArgumentNullException("values");
- if (columns.Length != values.Length) throw new Exception(string.Format("The number of columns: {0} does not match the number of supplied values: {1}", columns.Length, values.Length));
-
- table = QuoteTableNameIfRequired(table);
-
- var builder = new StringBuilder();
- for (int i = 0; i < values.Length; i++)
- {
- if (builder.Length > 0) builder.Append(", ");
- builder.Append(QuoteColumnNameIfRequired(columns[i]));
- builder.Append(" = ");
- builder.Append(GenerateParameterName(i));
- }
-
- var builder2 = new StringBuilder();
- for (int i = 0; i < whereColumns.Length; i++)
- {
- if (builder2.Length > 0) builder2.Append(" AND ");
- builder2.Append(QuoteColumnNameIfRequired(whereColumns[i]));
- builder2.Append(" = ");
- builder2.Append(GenerateParameterName(i + values.Count()));
- }
-
- using (IDbCommand command = _connection.CreateCommand())
- {
- command.Transaction = _transaction;
-
- var query = String.Format("UPDATE {0} SET {1} WHERE {2}", table, builder.ToString(), builder2.ToString());
-
- command.CommandText = query;
- command.CommandType = CommandType.Text;
-
- int paramCount = 0;
-
- foreach (object value in values)
- {
- IDbDataParameter parameter = command.CreateParameter();
-
- ConfigureParameterWithValue(parameter, paramCount, value);
-
- parameter.ParameterName = GenerateParameterName(paramCount);
-
- command.Parameters.Add(parameter);
-
- paramCount++;
- }
-
- foreach (object value in whereValues)
- {
-
- IDbDataParameter parameter = command.CreateParameter();
-
- ConfigureParameterWithValue(parameter, paramCount, value);
-
- parameter.ParameterName = GenerateParameterName(paramCount);
-
- command.Parameters.Add(parameter);
-
- paramCount++;
- }
-
- return command.ExecuteNonQuery();
- }
- }
-
- public virtual int Insert(string table, string[] columns, object[] values)
- {
- if (string.IsNullOrEmpty(table)) throw new ArgumentNullException("table");
- if (columns == null) throw new ArgumentNullException("columns");
- if (values == null) throw new ArgumentNullException("values");
- if (columns.Length != values.Length) throw new Exception(string.Format("The number of columns: {0} does not match the number of supplied values: {1}", columns.Length, values.Length));
-
- table = QuoteTableNameIfRequired(table);
-
- string columnNames = string.Join(", ", columns.Select(col => QuoteColumnNameIfRequired(col)).ToArray());
-
- var builder = new StringBuilder();
-
- for (int i = 0; i < values.Length; i++)
- {
- if (builder.Length > 0) builder.Append(", ");
- builder.Append(GenerateParameterName(i));
- }
-
- string parameterNames = builder.ToString();
-
- using (IDbCommand command = _connection.CreateCommand())
- {
- command.Transaction = _transaction;
-
- command.CommandText = String.Format("INSERT INTO {0} ({1}) VALUES ({2})", table, columnNames, parameterNames);
- command.CommandType = CommandType.Text;
-
- int paramCount = 0;
-
- foreach (object value in values)
- {
- IDbDataParameter parameter = command.CreateParameter();
-
- ConfigureParameterWithValue(parameter, paramCount, value);
-
- parameter.ParameterName = GenerateParameterName(paramCount);
-
- command.Parameters.Add(parameter);
-
- paramCount++;
- }
-
- return command.ExecuteNonQuery();
- }
- }
-
- public virtual int Delete(string table, string[] columns, string[] values)
- {
- if (null == columns || null == values)
- {
- return ExecuteNonQuery(String.Format("DELETE FROM {0}", table));
- }
- else
- {
- return ExecuteNonQuery(String.Format("DELETE FROM {0} WHERE ({1})", table, JoinColumnsAndValues(columns, values)));
- }
- }
-
- public virtual int Delete(string table, string wherecolumn, string wherevalue)
- {
- if (string.IsNullOrEmpty(wherecolumn) && string.IsNullOrEmpty(wherevalue))
- {
- return Delete(table, (string[])null, null);
- }
-
- return ExecuteNonQuery(String.Format("DELETE FROM {0} WHERE {1} = {2}", table, wherecolumn, QuoteValues(wherevalue)));
- }
-
- public virtual int TruncateTable(string table)
- {
- return ExecuteNonQuery(String.Format("TRUNCATE TABLE {0} ", table));
- }
-
- ///
- /// Starts a transaction. Called by the migration mediator.
- ///
- public virtual void BeginTransaction()
- {
- if (_transaction == null && _connection != null)
- {
- EnsureHasConnection();
- _transaction = _connection.BeginTransaction(IsolationLevel.ReadCommitted);
- }
- }
-
- ///
- /// Rollback the current migration. Called by the migration mediator.
- ///
- public virtual void Rollback()
- {
- if (_transaction != null && _connection != null && _connection.State == ConnectionState.Open)
- {
- try
- {
- _transaction.Rollback();
- }
- finally
- {
- if (!_outsideConnection)
- {
- _connection.Close();
- }
- }
- }
- _transaction = null;
- }
-
- ///
- /// Commit the current transaction. Called by the migrations mediator.
- ///
- public virtual void Commit()
- {
- if (_transaction != null && _connection != null && _connection.State == ConnectionState.Open)
- {
- try
- {
- _transaction.Commit();
- }
- finally
- {
- if (!_outsideConnection)
- {
- _connection.Close();
- }
- }
- }
- _transaction = null;
- }
-
- ///
- /// The list of Migrations currently applied to the database.
- ///
- public virtual List AppliedMigrations
- {
- get
- {
- if (_appliedMigrations == null)
- {
- _appliedMigrations = new List();
- CreateSchemaInfoTable();
-
- string versionColumn = "Version";
- string scopeColumn = "Scope";
-
- versionColumn = QuoteColumnNameIfRequired(versionColumn);
- scopeColumn = QuoteColumnNameIfRequired(scopeColumn);
-
- using (IDataReader reader = Select(versionColumn, _schemaInfotable, string.Format("{0} = '{1}'", scopeColumn, _scope)))
- {
- while (reader.Read())
- {
- if (reader.GetFieldType(0) == typeof(Decimal))
- {
- _appliedMigrations.Add((long)reader.GetDecimal(0));
- }
- else
- {
- _appliedMigrations.Add(reader.GetInt64(0));
- }
- }
- }
- }
- return _appliedMigrations;
- }
- }
-
- ///
- /// Marks a Migration version number as having been applied
- ///
- /// The version number of the migration that was applied
- public virtual void MigrationApplied(long version, string scope)
- {
- CreateSchemaInfoTable();
- Insert(_schemaInfotable, new string[] { "Scope", "Version", "TimeStamp" }, new object[] { scope ?? _scope, version, DateTime.Now });
- _appliedMigrations.Add(version);
- }
-
- ///
- /// Marks a Migration version number as having been rolled back from the database
- ///
- /// The version number of the migration that was removed
- public virtual void MigrationUnApplied(long version, string scope)
- {
- CreateSchemaInfoTable();
- Delete(_schemaInfotable, new[] { "Scope", "Version" }, new[] { scope ?? _scope, version.ToString() });
- _appliedMigrations.Remove(version);
- }
-
- public virtual void AddColumn(string table, Column column)
- {
- AddColumn(table, column.Name, column.Type, column.Size, column.ColumnProperty, column.DefaultValue);
- }
-
- public virtual void GenerateForeignKey(string primaryTable, string refTable)
- {
- GenerateForeignKey(primaryTable, refTable, ForeignKeyConstraintType.NoAction);
- }
-
- public virtual void GenerateForeignKey(string primaryTable, string refTable, ForeignKeyConstraintType constraint)
- {
- GenerateForeignKey(primaryTable, refTable + "Id", refTable, "Id", constraint);
- }
-
- public virtual IDbCommand GetCommand()
- {
- return BuildCommand(null);
- }
-
- public virtual void ExecuteSchemaBuilder(SchemaBuilder builder)
- {
- foreach (ISchemaBuilderExpression expr in builder.Expressions)
- expr.Create(this);
- }
-
- public void Dispose()
- {
- if (_connection != null && _connection.State == ConnectionState.Open)
- {
- if (!_outsideConnection)
- {
- _connection.Close();
- }
- }
-
- if (_connection != null)
- {
- if (!_outsideConnection)
- {
- _connection.Close();
- }
- }
-
- _connection = null;
- }
-
- public virtual string QuoteColumnNameIfRequired(string name)
- {
- if (Dialect.ColumnNameNeedsQuote || Dialect.IsReservedWord(name))
- {
- return Dialect.Quote(name);
- }
- return name;
- }
-
- public virtual string QuoteTableNameIfRequired(string name)
- {
- if (Dialect.TableNameNeedsQuote || Dialect.IsReservedWord(name))
- {
- return Dialect.Quote(name);
- }
- return name;
- }
-
- public virtual string Encode(Guid guid)
- {
- return guid.ToString();
- }
-
- public virtual string[] QuoteColumnNamesIfRequired(params string[] columnNames)
- {
- var quotedColumns = new string[columnNames.Length];
-
- for (int i = 0; i < columnNames.Length; i++)
- {
- quotedColumns[i] = QuoteColumnNameIfRequired(columnNames[i]);
- }
-
- return quotedColumns;
- }
-
- public virtual bool IsThisProvider(string provider)
- {
- // XXX: This might need to be more sophisticated. Currently just a convention
- return GetType().Name.ToLower().StartsWith(provider.ToLower());
- }
-
- public virtual void RemoveAllForeignKeys(string tableName, string columnName)
- { }
-
- public virtual void AddTable(string table, string engine, string columns)
- {
- table = _dialect.TableNameNeedsQuote ? _dialect.Quote(table) : table;
- string sqlCreate = String.Format("CREATE TABLE {0} ({1})", table, columns);
- ExecuteNonQuery(sqlCreate);
- }
-
- public virtual List GetPrimaryKeys(IEnumerable columns)
- {
- var pks = new List();
- foreach (Column col in columns)
- {
- if (col.IsPrimaryKey)
- pks.Add(col.Name);
- }
- return pks;
- }
-
- public virtual void AddColumnDefaultValue(string table, string column, object defaultValue)
- {
- table = QuoteTableNameIfRequired(table);
- column = this.QuoteColumnNameIfRequired(column);
- var def = Dialect.Default(defaultValue);
- ExecuteNonQuery(String.Format("ALTER TABLE {0} ADD DEFAULT('{1}') FOR {2}", table, def, column));
- }
-
- public virtual void AddColumn(string table, string sqlColumn)
- {
- table = QuoteTableNameIfRequired(table);
- ExecuteNonQuery(String.Format("ALTER TABLE {0} ADD COLUMN {1}", table, sqlColumn));
- }
-
- public virtual void ChangeColumn(string table, string sqlColumn)
- {
- table = QuoteTableNameIfRequired(table);
- ExecuteNonQuery(String.Format("ALTER TABLE {0} ALTER COLUMN {1}", table, sqlColumn));
- }
-
- protected virtual string JoinColumnsAndIndexes(IEnumerable columns)
- {
- string indexes = JoinIndexes(columns);
- string columnsAndIndexes = JoinColumns(columns) + (indexes != null ? "," + indexes : String.Empty);
- return columnsAndIndexes;
- }
-
- protected virtual string JoinIndexes(IEnumerable columns)
- {
- var indexes = new List();
- foreach (ColumnPropertiesMapper column in columns)
- {
- string indexSql = column.IndexSql;
- if (indexSql != null)
- indexes.Add(indexSql);
- }
-
- if (indexes.Count == 0)
- return null;
-
- return String.Join(", ", indexes.ToArray());
- }
-
- protected virtual string JoinColumns(IEnumerable columns)
- {
- var columnStrings = new List();
- foreach (ColumnPropertiesMapper column in columns)
- columnStrings.Add(column.ColumnSql);
- return String.Join(", ", columnStrings.ToArray());
- }
-
- protected IDbCommand BuildCommand(string sql)
- {
- EnsureHasConnection();
- IDbCommand cmd = _connection.CreateCommand();
- cmd.CommandText = sql;
- cmd.CommandType = CommandType.Text;
- if (_transaction != null)
- {
- cmd.Transaction = _transaction;
- }
- return cmd;
- }
-
- public virtual int Delete(string table)
- {
- return Delete(table, null, (string[])null);
- }
-
- protected void EnsureHasConnection()
- {
- if (_connection.State != ConnectionState.Open)
- {
- _connection.Open();
- }
- }
-
- protected virtual void CreateSchemaInfoTable()
- {
- EnsureHasConnection();
- if (!TableExists(_schemaInfotable))
- {
- AddTable(_schemaInfotable,
- new Column("Version", DbType.Int64, ColumnProperty.NotNull | ColumnProperty.PrimaryKey),
- new Column("Scope", DbType.String, 50, ColumnProperty.NotNull | ColumnProperty.PrimaryKey, "default"),
- new Column("TimeStamp", DbType.DateTime));
- }
- else
- {
- if (!ColumnExists(_schemaInfotable, "Scope"))
- {
- AddColumn(_schemaInfotable, "Scope", DbType.String, 50, ColumnProperty.NotNull, "default");
- RemoveAllConstraints(_schemaInfotable);
- AddPrimaryKey("PK_SchemaInfo", _schemaInfotable, new[] { "Version", "Scope" });
- }
-
- if (!ColumnExists(_schemaInfotable, "TimeStamp"))
- {
- AddColumn(_schemaInfotable, "TimeStamp", DbType.DateTime);
- }
- }
- }
-
- public virtual string QuoteValues(string values)
- {
- return QuoteValues(new[] { values })[0];
- }
-
- public virtual string[] QuoteValues(string[] values)
- {
- return Array.ConvertAll(values,
- delegate(string val)
- {
- if (null == val)
- return "null";
- else
- return String.Format("'{0}'", val.Replace("'", "''"));
- });
- }
-
- public virtual string JoinColumnsAndValues(string[] columns, string[] values)
- {
- string[] quotedValues = QuoteValues(values);
- var namesAndValues = new string[columns.Length];
- for (int i = 0; i < columns.Length; i++)
- {
- namesAndValues[i] = String.Format("{0}={1}", columns[i], quotedValues[i]);
- }
-
- return String.Join(", ", namesAndValues);
- }
-
- public virtual string GenerateParameterName(int index)
- {
- return "@p" + index;
- }
-
- protected virtual void ConfigureParameterWithValue(IDbDataParameter parameter, int index, object value)
- {
- if (value == null || value == DBNull.Value)
- {
- parameter.Value = DBNull.Value;
- }
- else if (value is Guid || value is Guid?)
- {
- parameter.DbType = DbType.Guid;
- parameter.Value = (Guid)value;
- }
- else if (value is Int16)
- {
- parameter.DbType = DbType.Int16;
- parameter.Value = value;
- }
- else if (value is Int32)
- {
- parameter.DbType = DbType.Int32;
- parameter.Value = value;
- }
- else if (value is Int64)
- {
- parameter.DbType = DbType.Int64;
- parameter.Value = value;
- }
- else if (value is UInt16)
- {
- parameter.DbType = DbType.UInt16;
- parameter.Value = value;
- }
- else if (value is UInt32)
- {
- parameter.DbType = DbType.UInt32;
- parameter.Value = value;
- }
- else if (value is UInt64)
- {
- parameter.DbType = DbType.UInt64;
- parameter.Value = value;
- }
- else if (value is Double)
- {
- parameter.DbType = DbType.Double;
- parameter.Value = value;
- }
- else if (value is Decimal)
- {
- parameter.DbType = DbType.Decimal;
- parameter.Value = value;
- }
- else if (value is String)
- {
- parameter.DbType = DbType.String;
- parameter.Value = value;
- }
- else if (value is DateTime || value is DateTime?)
- {
- parameter.DbType = DbType.DateTime;
- parameter.Value = value;
- }
- else if (value is Boolean || value is Boolean?)
- {
- parameter.DbType = DbType.Boolean;
- parameter.Value = value;
- }
- else
- {
- throw new NotSupportedException(string.Format("TransformationProvider does not support value: {0} of type: {1}", value, value.GetType()));
- }
- }
-
- string FormatValue(object value)
- {
- if (value == null) return null;
- if (value is DateTime) return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss:fff");
- return value.ToString();
- }
-
- void QuoteColumnNames(string[] primaryColumns)
- {
- for (int i = 0; i < primaryColumns.Length; i++)
- {
- primaryColumns[i] = QuoteColumnNameIfRequired(primaryColumns[i]);
- }
- }
-
- public virtual void RemoveIndex(string table, string name)
- {
- if (TableExists(table) && IndexExists(table, name))
- {
- name = QuoteConstraintNameIfRequired(name);
- ExecuteNonQuery(String.Format("DROP INDEX {0}", name));
- }
- }
-
- public virtual void AddIndex(string table, Index index)
- {
- AddIndex(index.Name, table, index.KeyColumns);
- }
-
- public virtual void AddIndex(string name, string table, params string[] columns)
- {
- if (IndexExists(table, name))
- {
- Logger.Warn("Index {0} already exists", name);
- return;
- }
-
- name = QuoteConstraintNameIfRequired(name);
-
- table = QuoteTableNameIfRequired(table);
-
- columns = QuoteColumnNamesIfRequired(columns);
-
- ExecuteNonQuery(String.Format("CREATE INDEX {0} ON {1} ({2}) ", name, table, string.Join(", ", columns)));
- }
-
- protected string QuoteConstraintNameIfRequired(string name)
- {
- return _dialect.ConstraintNameNeedsQuote ? _dialect.Quote(name) : name;
- }
-
- public abstract bool IndexExists(string table, string name);
-
- protected virtual string GetPrimaryKeyConstraintName(string table)
- {
- return null;
- }
-
- public virtual void RemovePrimaryKey(string table)
- {
- if (!TableExists(table)) return;
-
- var primaryKeyConstraintName = GetPrimaryKeyConstraintName(table);
-
- if (primaryKeyConstraintName == null || !ConstraintExists(table, primaryKeyConstraintName)) return;
-
- RemoveConstraint(table, primaryKeyConstraintName);
- }
-
- public virtual void RemoveAllIndexes(string table)
- {
- if (!TableExists(table)) return;
-
- var indexes = GetIndexes(table);
-
- foreach (var index in indexes)
- {
- if (index.Name == null || !IndexExists(table, index.Name)) continue;
-
- if (index.PrimaryKey || index.Clustered || index.Unique)
- RemoveConstraint(table, index.Name);
- else
- RemoveIndex(table, index.Name);
- }
- }
-
- public virtual string Concatenate(params string[] strings)
- {
- return string.Join(" || ", strings);
- }
-
- public IDbConnection Connection
- {
- get { return _connection; }
- }
-
- public IEnumerable GetTables(string schema)
- {
- var tableRestrictions = new string[4];
- tableRestrictions[1] = schema;
-
- var c = _connection as DbConnection;
- var tables = c.GetSchema("Tables", tableRestrictions);
- return from DataRow row in tables.Rows select row.Field("TABLE_NAME");
- }
-
- public IEnumerable GetColumns(string schema, string table)
- {
- var tableRestrictions = new string[4];
- tableRestrictions[1] = schema;
- tableRestrictions[2] = table;
-
- var c = _connection as DbConnection;
- var tables = c.GetSchema("Columns", tableRestrictions);
- return from DataRow row in tables.Rows select row.Field("TABLE_NAME");
- }
- }
-}
diff --git a/src/Migrator.Providers/TypeNames.cs b/src/Migrator.Providers/TypeNames.cs
deleted file mode 100644
index a697ceb5..00000000
--- a/src/Migrator.Providers/TypeNames.cs
+++ /dev/null
@@ -1,141 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Linq;
-
-using Migrator.Framework;
-
-namespace Migrator.Providers
-{
- ///
- /// This class maps a DbType to names.
- ///
- ///
- /// Associations may be marked with a capacity. Calling the Get()
- /// method with a type and actual size n will return the associated
- /// name with smallest capacity >= n, if available and an unmarked
- /// default type otherwise.
- /// Eg, setting
- ///
- /// Names.Put(DbType, "TEXT" );
- /// Names.Put(DbType, 255, "VARCHAR($l)" );
- /// Names.Put(DbType, 65534, "LONGVARCHAR($l)" );
- ///
- /// will give you back the following:
- ///
- /// Names.Get(DbType) // --> "TEXT" (default)
- /// Names.Get(DbType,100) // --> "VARCHAR(100)" (100 is in [0:255])
- /// Names.Get(DbType,1000) // --> "LONGVARCHAR(1000)" (100 is in [256:65534])
- /// Names.Get(DbType,100000) // --> "TEXT" (default)
- ///
- /// On the other hand, simply putting
- ///
- /// Names.Put(DbType, "VARCHAR($l)" );
- ///
- /// would result in
- ///
- /// Names.Get(DbType) // --> "VARCHAR($l)" (will cause trouble)
- /// Names.Get(DbType,100) // --> "VARCHAR(100)"
- /// Names.Get(DbType,1000) // --> "VARCHAR(1000)"
- /// Names.Get(DbType,10000) // --> "VARCHAR(10000)"
- ///
- ///
- public class TypeNames
- {
- public const string LengthPlaceHolder = "$l";
- public const string PrecisionPlaceHolder = "$p";
- public const string ScalePlaceHolder = "$s";
-
- readonly Dictionary defaults = new Dictionary();
-
- readonly Dictionary> weighted =
- new Dictionary>();
-
- public DbType GetDbType(string type)
- {
- type = type.Trim().ToLower();
- var retval = defaults.Where(x => x.Value.Trim().ToLower().StartsWith(type)).Select(x => x.Key);
- if (retval.Any())
- return retval.First();
- return weighted.Where(x => x.Value.Where(y => y.Value.Trim().ToLower().StartsWith(type)).Any()).Select(x => x.Key).FirstOrDefault();
- }
-
- ///
- /// Get default type name for specified type
- ///
- /// the type key
- /// the default type name associated with the specified key
- public string Get(DbType typecode)
- {
- string result;
- if (!defaults.TryGetValue(typecode, out result))
- {
- throw new ArgumentException("Dialect does not support DbType." + typecode, "typecode");
- }
- return result;
- }
-
- ///
- /// Get the type name specified type and size
- ///
- /// the type key
- /// the SQL length
- /// the SQL scale
- /// the SQL precision
- ///
- /// The associated name with smallest capacity >= size if available and the
- /// default type name otherwise
- ///
- public string Get(DbType typecode, int size, int precision, int scale)
- {
- SortedList map;
- weighted.TryGetValue(typecode, out map);
- if (map != null && map.Count > 0)
- {
- foreach (var entry in map)
- {
- if (size <= entry.Key)
- {
- return Replace(entry.Value, size, precision, scale);
- }
- }
- }
- //Could not find a specific type for the size, using the default
- return Get(typecode);
- }
-
- static string Replace(string type, int size, int precision, int scale)
- {
- type = StringUtils.ReplaceOnce(type, LengthPlaceHolder, size.ToString());
- type = StringUtils.ReplaceOnce(type, ScalePlaceHolder, scale.ToString());
- return StringUtils.ReplaceOnce(type, PrecisionPlaceHolder, precision.ToString());
- }
-
- ///
- /// Set a type name for specified type key and capacity
- ///
- /// the type key
- /// the (maximum) type size/length
- /// The associated name
- public void Put(DbType typecode, int capacity, string value)
- {
- SortedList map;
- if (!weighted.TryGetValue(typecode, out map))
- {
- // add new ordered map
- weighted[typecode] = map = new SortedList();
- }
- map[capacity] = value;
- }
-
- ///
- ///
- ///
- ///
- ///
- public void Put(DbType typecode, string value)
- {
- defaults[typecode] = value;
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Utility/MySqlServerUtility.cs b/src/Migrator.Providers/Utility/MySqlServerUtility.cs
deleted file mode 100644
index 17b3de1b..00000000
--- a/src/Migrator.Providers/Utility/MySqlServerUtility.cs
+++ /dev/null
@@ -1,70 +0,0 @@
-using System;
-using System.Data;
-//using MySql.Data.MySqlClient;
-
-namespace Migrator.Providers.Utility
-{
-// public static class MySqlServerUtility
-// {
-// public static void RemoveAllTablesFromDefaultDatabase(string connectionString)
-// {
-// using (var connection = new MySqlConnection(connectionString))
-// {
-// connection.Open();
-
-// string dropAllTablesSql = null;
-
-// do
-// {
-// dropAllTablesSql = GetDropAllTablesSql(connection);
-
-// if (dropAllTablesSql == null) continue;
-
-// DisableForeignKeys(connection);
-
-// ExecuteDropCommand(connection, dropAllTablesSql);
-// } while (dropAllTablesSql != null);
-// }
-// }
-
-// static void ExecuteDropCommand(MySqlConnection connection, string dropAllTablesSql)
-// {
-// using (var dropCmd = new MySqlCommand(dropAllTablesSql, connection))
-// {
-// dropCmd.ExecuteNonQuery();
-// }
-// }
-
-// public static void DisableForeignKeys(MySqlConnection connection)
-// {
-// using (var command = new MySqlCommand("Set foreign_key_checks=off;", connection))
-// {
-// command.ExecuteNonQuery();
-// }
-// }
-
-// public static string GetDropAllTablesSql(MySqlConnection connection)
-// {
-// const string query =
-// @"set group_concat_max_len=10240;
-//SELECT concat('DROP TABLE IF EXISTS ', group_concat(table_name)) drop_statement
-//FROM information_schema.tables
-//WHERE table_schema=database();";
-
-// using (var getDropAllTablesCommand = new MySqlCommand(query, connection))
-// {
-// getDropAllTablesCommand.CommandType = CommandType.Text;
-
-// using (MySqlDataReader reader = getDropAllTablesCommand.ExecuteReader())
-// {
-// if (reader.Read() && (reader[0] != null && !Convert.IsDBNull(reader[0])))
-// {
-// return reader[0].ToString();
-// }
-// }
-// }
-
-// return null;
-// }
-// }
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Utility/OracleServerUtility.cs b/src/Migrator.Providers/Utility/OracleServerUtility.cs
deleted file mode 100644
index c56e42d6..00000000
--- a/src/Migrator.Providers/Utility/OracleServerUtility.cs
+++ /dev/null
@@ -1,97 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Linq;
-//using Oracle.DataAccess.Client;
-
-namespace Migrator.Providers.Utility
-{
- //public static class OracleServerUtility
- //{
- // static readonly string[] _specialTableNames = new[]
- // {
- // "DEF$_AQCALL",
- // "DEF$_AQERROR",
- // "SQLPLUS_PRODUCT_PROFILE",
- // "HELP",
- // "MVIEW$_ADV_INDEX",
- // "MVIEW$_ADV_PARTITION"
- // };
-
- // public static void RemoveAllTablesFromDefaultDatabase(string connectionString)
- // {
- // using (var connection = new OracleConnection(connectionString))
- // {
- // connection.Open();
-
- // string[] allTablesToDrop = GetTablesToDrop(connection).ToArray();
-
- // foreach (string table in allTablesToDrop)
- // {
- // string statement = string.Format("drop table \"{0}\" cascade constraints", table);
-
- // ExecuteDropCommand(connection, statement);
- // }
- // }
- // }
-
- // static void ExecuteDropCommand(OracleConnection connection, string statement)
- // {
- // using (var dropCmd = new OracleCommand(statement, connection))
- // {
- // dropCmd.ExecuteNonQuery();
- // }
- // }
-
- // public static int GetTableCount(string connectionString)
- // {
- // using (var connection = new OracleConnection(connectionString))
- // {
- // connection.Open();
-
- // return GetTablesToDrop(connection).Count();
- // }
- // }
-
- // static string ExtractUserIDFromConnectionString(string connectionString)
- // {
-
- // string[] values = connectionString.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
-
- // var match = values.FirstOrDefault(v => v.StartsWith("User ID=", StringComparison.InvariantCultureIgnoreCase));
-
- // if (match != null)
- // {
- // string userName = match.Split(new[] { "=" }, StringSplitOptions.None)[1];
- // return userName;
- // }
-
- // return null;
- // }
-
- // public static IEnumerable GetTablesToDrop(OracleConnection connection)
- // {
- // var schema = ExtractUserIDFromConnectionString(connection.ConnectionString);
-
- // string query = string.Format(@"select * from user_tables where TABLESPACE_NAME = '{0}'", schema);
-
- // using (var getDropAllTablesCommand = new OracleCommand(query, connection))
- // {
- // getDropAllTablesCommand.CommandType = CommandType.Text;
-
- // using (OracleDataReader reader = getDropAllTablesCommand.ExecuteReader())
- // {
- // while (reader.Read() && (reader[0] != null && !Convert.IsDBNull(reader[0])))
- // {
- // string tableName = reader[0].ToString();
-
- // if (!_specialTableNames.Contains(tableName))
- // {
- // yield return tableName;
- // }
- // }
- // }
- // }
- // }
- //}
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Utility/PostgreSqlServerUtility.cs b/src/Migrator.Providers/Utility/PostgreSqlServerUtility.cs
deleted file mode 100644
index 1e0dc477..00000000
--- a/src/Migrator.Providers/Utility/PostgreSqlServerUtility.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-using System.Collections.Generic;
-using System.Data;
-using System.Linq;
-//using Npgsql;
-
-namespace Migrator.Providers.Utility
-{
- //public static class PostgreSqlServerUtility
- //{
- // public static void RemoveAllTablesFromDefaultDatabase(string connectionString)
- // {
- // using (var connection = new NpgsqlConnection(connectionString))
- // {
- // connection.Open();
-
- // List tableNames = GetAllTableNames(connection).ToList();
-
- // foreach (string table in tableNames)
- // {
- // using (var command = new NpgsqlCommand(string.Format("DROP TABLE IF EXISTS {0} CASCADE", table), connection))
- // {
- // command.ExecuteNonQuery();
- // }
- // }
-
- // connection.Close();
- // }
- // }
-
- // static IEnumerable GetAllTableNames(NpgsqlConnection connection)
- // {
- // using (var command = new NpgsqlCommand("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'", connection))
- // {
- // using (IDataReader reader = command.ExecuteReader(CommandBehavior.Default))
- // {
- // while (reader.Read())
- // {
- // yield return (string) reader[0];
- // }
- // }
- // }
- // }
- //}
-}
\ No newline at end of file
diff --git a/src/Migrator.Providers/Utility/SqlServerUtility.cs b/src/Migrator.Providers/Utility/SqlServerUtility.cs
deleted file mode 100644
index 54a06213..00000000
--- a/src/Migrator.Providers/Utility/SqlServerUtility.cs
+++ /dev/null
@@ -1,69 +0,0 @@
-using System.Data;
-using System.Data.SqlClient;
-
-namespace Migrator.Providers.Utility
-{
- public static class SqlServerUtility
- {
- public static void RemoveAllTablesFromDefaultDatabase(string connectionString)
- {
- using (var connection = new SqlConnection(connectionString))
- {
- connection.Open();
- RemoveAllForeignKeys(connection);
- DropAllTables(connection);
- connection.Close();
- }
- }
-
- static void DropAllTables(SqlConnection connection)
- {
- ExecuteForEachTable(connection, "DROP TABLE ?");
- }
-
- static void RemoveAllForeignKeys(SqlConnection connection)
- {
- using (
- var dropConstraintsCommand =
- new SqlCommand(
- @"DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR
-
-SET @Cursor = CURSOR FAST_FORWARD FOR
-
-SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
-
-FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
-
-LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
-
-OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql
-
-WHILE (@@FETCH_STATUS = 0)
-
-BEGIN
-
-Exec sys.sp_executesql @Sql
-
-FETCH NEXT FROM @Cursor INTO @Sql
-
-END
-
-CLOSE @Cursor DEALLOCATE @Cursor",
- connection))
- {
- dropConstraintsCommand.CommandType = CommandType.Text;
- dropConstraintsCommand.ExecuteNonQuery();
- }
- }
-
- static void ExecuteForEachTable(SqlConnection connection, string command)
- {
- using (var forEachCommand = new SqlCommand("sp_MSforeachtable", connection))
- {
- forEachCommand.CommandType = CommandType.StoredProcedure;
- forEachCommand.Parameters.AddWithValue("@command1", command);
- forEachCommand.ExecuteNonQuery();
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/Migrator.Tests/ColumnPropertyMapperTest.cs b/src/Migrator.Tests/ColumnPropertyMapperTest.cs
index 143a7c55..3add18d0 100644
--- a/src/Migrator.Tests/ColumnPropertyMapperTest.cs
+++ b/src/Migrator.Tests/ColumnPropertyMapperTest.cs
@@ -1,122 +1,121 @@
using System.Data;
-using Migrator.Framework;
-using Migrator.Providers;
-using Migrator.Providers.Oracle;
-using Migrator.Providers.PostgreSQL;
-using Migrator.Providers.SQLite;
-using Migrator.Providers.SqlServer;
+using DotNetProjects.Migrator.Framework;
+using DotNetProjects.Migrator.Providers;
+using DotNetProjects.Migrator.Providers.Impl.Oracle;
+using DotNetProjects.Migrator.Providers.Impl.PostgreSQL;
+using DotNetProjects.Migrator.Providers.Impl.SQLite;
+using DotNetProjects.Migrator.Providers.Impl.SqlServer;
using NUnit.Framework;
-namespace Migrator.Tests
+namespace Migrator.Tests;
+
+[TestFixture]
+public class ColumnPropertyMapperTest
{
- [TestFixture]
- public class ColumnPropertyMapperTest
- {
- [Test]
- public void OracleCreatesNotNullSql()
- {
- var mapper = new ColumnPropertiesMapper(new OracleDialect(), "varchar(30)");
- mapper.MapColumnProperties(new Column("foo", DbType.String, ColumnProperty.NotNull));
- Assert.AreEqual("foo varchar(30) NOT NULL", mapper.ColumnSql);
- }
+ [Test]
+ public void OracleCreatesNotNullSql()
+ {
+ var mapper = new ColumnPropertiesMapper(new OracleDialect(), "varchar(30)");
+ mapper.MapColumnProperties(new Column("foo", DbType.String, ColumnProperty.NotNull));
+ Assert.That("foo varchar(30) NOT NULL", Is.EqualTo(mapper.ColumnSql));
+ }
- [Test]
- public void OracleCreatesSql()
- {
- var mapper = new ColumnPropertiesMapper(new OracleDialect(), "varchar(30)");
- mapper.MapColumnProperties(new Column("foo", DbType.String, 0));
- Assert.AreEqual("foo varchar(30)", mapper.ColumnSql);
- }
+ [Test]
+ public void OracleCreatesSql()
+ {
+ var mapper = new ColumnPropertiesMapper(new OracleDialect(), "varchar(30)");
+ mapper.MapColumnProperties(new Column("foo", DbType.String, 0));
+ Assert.That("foo varchar(30)", Is.EqualTo(mapper.ColumnSql));
+ }
- [Test]
- public void OracleIndexSqlIsNoNullWhenIndexed()
- {
- var mapper = new ColumnPropertiesMapper(new OracleDialect(), "char(1)");
- mapper.MapColumnProperties(new Column("foo", DbType.StringFixedLength, 1, ColumnProperty.Indexed));
- Assert.IsNotNull(mapper.IndexSql);
- }
+ [Test]
+ public void OracleIndexSqlIsNoNullWhenIndexed()
+ {
+ var mapper = new ColumnPropertiesMapper(new OracleDialect(), "char(1)");
+ mapper.MapColumnProperties(new Column("foo", DbType.StringFixedLength, 1, ColumnProperty.Indexed));
+ Assert.That(mapper.IndexSql, Is.Not.Null);
+ }
- [Test]
- public void OracleIndexSqlIsNullWhenIndexedFalse()
- {
- var mapper = new ColumnPropertiesMapper(new OracleDialect(), "char(1)");
- mapper.MapColumnProperties(new Column("foo", DbType.StringFixedLength, 1, 0));
- Assert.IsNull(mapper.IndexSql);
- }
+ [Test]
+ public void OracleIndexSqlIsNullWhenIndexedFalse()
+ {
+ var mapper = new ColumnPropertiesMapper(new OracleDialect(), "char(1)");
+ mapper.MapColumnProperties(new Column("foo", DbType.StringFixedLength, 1, 0));
+ Assert.That(mapper.IndexSql, Is.Null);
+ }
- [Test]
- public void PostgresIndexSqlIsNoNullWhenIndexed()
- {
- var mapper = new ColumnPropertiesMapper(new PostgreSQLDialect(), "char(1)");
- mapper.MapColumnProperties(new Column("foo", DbType.StringFixedLength, 1, ColumnProperty.Indexed));
- Assert.IsNotNull(mapper.IndexSql);
- }
+ [Test]
+ public void PostgresIndexSqlIsNoNullWhenIndexed()
+ {
+ var mapper = new ColumnPropertiesMapper(new PostgreSQLDialect(), "char(1)");
+ mapper.MapColumnProperties(new Column("foo", DbType.StringFixedLength, 1, ColumnProperty.Indexed));
+ Assert.That(mapper.IndexSql, Is.Not.Null);
+ }
- [Test]
- public void PostgresIndexSqlIsNullWhenIndexedFalse()
- {
- var mapper = new ColumnPropertiesMapper(new PostgreSQLDialect(), "char(1)");
- mapper.MapColumnProperties(new Column("foo", DbType.StringFixedLength, 1, 0));
- Assert.IsNull(mapper.IndexSql);
- }
+ [Test]
+ public void PostgresIndexSqlIsNullWhenIndexedFalse()
+ {
+ var mapper = new ColumnPropertiesMapper(new PostgreSQLDialect(), "char(1)");
+ mapper.MapColumnProperties(new Column("foo", DbType.StringFixedLength, 1, 0));
+ Assert.That(mapper.IndexSql, Is.Null);
+ }
- [Test]
- public void SqlServerCreatesNotNullSql()
- {
- var mapper = new ColumnPropertiesMapper(new SqlServerDialect(), "varchar(30)");
- mapper.MapColumnProperties(new Column("foo", DbType.String, ColumnProperty.NotNull));
- Assert.AreEqual("[foo] varchar(30) NOT NULL", mapper.ColumnSql);
- }
+ [Test]
+ public void SqlServerCreatesNotNullSql()
+ {
+ var mapper = new ColumnPropertiesMapper(new SqlServerDialect(), "varchar(30)");
+ mapper.MapColumnProperties(new Column("foo", DbType.String, ColumnProperty.NotNull));
+ Assert.That("[foo] varchar(30) NOT NULL", Is.EqualTo(mapper.ColumnSql));
+ }
- [Test]
- public void SqlServerCreatesSqWithBooleanDefault()
- {
- var mapper = new ColumnPropertiesMapper(new SqlServerDialect(), "bit");
- mapper.MapColumnProperties(new Column("foo", DbType.Boolean, 0, false));
- Assert.AreEqual("[foo] bit DEFAULT 0", mapper.ColumnSql);
+ [Test]
+ public void SqlServerCreatesSqWithBooleanDefault()
+ {
+ var mapper = new ColumnPropertiesMapper(new SqlServerDialect(), "bit");
+ mapper.MapColumnProperties(new Column("foo", DbType.Boolean, 0, false));
+ Assert.That("[foo] bit DEFAULT 0", Is.EqualTo(mapper.ColumnSql));
- mapper.MapColumnProperties(new Column("bar", DbType.Boolean, 0, true));
- Assert.AreEqual("[bar] bit DEFAULT 1", mapper.ColumnSql);
- }
+ mapper.MapColumnProperties(new Column("bar", DbType.Boolean, 0, true));
+ Assert.That("[bar] bit DEFAULT 1", Is.EqualTo(mapper.ColumnSql));
+ }
- [Test]
- public void SqlServerCreatesSqWithDefault()
- {
- var mapper = new ColumnPropertiesMapper(new SqlServerDialect(), "varchar(30)");
- mapper.MapColumnProperties(new Column("foo", DbType.String, 0, "'NEW'"));
- Assert.AreEqual("[foo] varchar(30) DEFAULT '''NEW'''", mapper.ColumnSql);
- }
+ [Test]
+ public void SqlServerCreatesSqWithDefault()
+ {
+ var mapper = new ColumnPropertiesMapper(new SqlServerDialect(), "varchar(30)");
+ mapper.MapColumnProperties(new Column("foo", DbType.String, 0, "'NEW'"));
+ Assert.That("[foo] varchar(30) DEFAULT '''NEW'''", Is.EqualTo(mapper.ColumnSql));
+ }
- [Test]
- public void SqlServerCreatesSqWithNullDefault()
- {
- var mapper = new ColumnPropertiesMapper(new SqlServerDialect(), "varchar(30)");
- mapper.MapColumnProperties(new Column("foo", DbType.String, 0, "NULL"));
- Assert.AreEqual("[foo] varchar(30) DEFAULT 'NULL'", mapper.ColumnSql);
- }
+ [Test]
+ public void SqlServerCreatesSqWithNullDefault()
+ {
+ var mapper = new ColumnPropertiesMapper(new SqlServerDialect(), "varchar(30)");
+ mapper.MapColumnProperties(new Column("foo", DbType.String, 0, "NULL"));
+ Assert.That("[foo] varchar(30) DEFAULT 'NULL'", Is.EqualTo(mapper.ColumnSql));
+ }
- [Test]
- public void SqlServerCreatesSql()
- {
- var mapper = new ColumnPropertiesMapper(new SqlServerDialect(), "varchar(30)");
- mapper.MapColumnProperties(new Column("foo", DbType.String, 0));
- Assert.AreEqual("[foo] varchar(30)", mapper.ColumnSql);
- }
+ [Test]
+ public void SqlServerCreatesSql()
+ {
+ var mapper = new ColumnPropertiesMapper(new SqlServerDialect(), "varchar(30)");
+ mapper.MapColumnProperties(new Column("foo", DbType.String, 0));
+ Assert.That("[foo] varchar(30)", Is.EqualTo(mapper.ColumnSql));
+ }
- [Test]
- public void SqlServerIndexSqlIsNoNullWhenIndexed()
- {
- var mapper = new ColumnPropertiesMapper(new SqlServerDialect(), "char(1)");
- mapper.MapColumnProperties(new Column("foo", DbType.StringFixedLength, 1, ColumnProperty.Indexed));
- Assert.IsNull(mapper.IndexSql);
- }
+ [Test]
+ public void SqlServerIndexSqlIsNoNullWhenIndexed()
+ {
+ var mapper = new ColumnPropertiesMapper(new SqlServerDialect(), "char(1)");
+ mapper.MapColumnProperties(new Column("foo", DbType.StringFixedLength, 1, ColumnProperty.Indexed));
+ Assert.That(mapper.IndexSql, Is.Null);
+ }
- [Test]
- public void SQLiteIndexSqlWithEmptyStringDefault()
- {
- var mapper = new ColumnPropertiesMapper(new SQLiteDialect(), "varchar(30)");
- mapper.MapColumnProperties(new Column("foo", DbType.String, 1, ColumnProperty.NotNull, string.Empty));
- Assert.AreEqual("foo varchar(30) NOT NULL DEFAULT ''", mapper.ColumnSql);
- }
- }
+ [Test]
+ public void SQLiteIndexSqlWithEmptyStringDefault()
+ {
+ var mapper = new ColumnPropertiesMapper(new SQLiteDialect(), "varchar(30)");
+ mapper.MapColumnProperties(new Column("foo", DbType.String, 1, ColumnProperty.NotNull, string.Empty));
+ Assert.That("foo varchar(30) NOT NULL DEFAULT ''", Is.EqualTo(mapper.ColumnSql));
+ }
}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Data/TestMigrations.cs b/src/Migrator.Tests/Data/TestMigrations.cs
index 7a3efcfb..a6541559 100644
--- a/src/Migrator.Tests/Data/TestMigrations.cs
+++ b/src/Migrator.Tests/Data/TestMigrations.cs
@@ -1,67 +1,66 @@
-using Migrator.Framework;
+using DotNetProjects.Migrator.Framework;
-namespace Migrator.Tests.Data
+namespace Migrator.Tests.Data;
+
+[Migration(1)]
+public class FirstTestMigration : Migration
{
- [Migration(1)]
- public class FirstTestMigration : Migration
- {
- public override void Up()
- {
- }
+ public override void Up()
+ {
+ }
- public override void Down()
- {
- }
- }
+ public override void Down()
+ {
+ }
+}
- [Migration(2)]
- public class SecondTestMigration : IMigration
- {
- public string Name
- {
- get { return StringUtils.ToHumanName(GetType().Name); }
- }
+[Migration(2)]
+public class SecondTestMigration : IMigration
+{
+ public string Name
+ {
+ get { return StringUtils.ToHumanName(GetType().Name); }
+ }
- ///
- /// Defines tranformations to port the database to the current version.
- ///
- public void Up()
- {
- }
+ ///
+ /// Defines tranformations to port the database to the current version.
+ ///
+ public void Up()
+ {
+ }
- ///
- /// This is run after the Up transaction has been committed
- ///
- public virtual void AfterUp()
- {
- }
+ ///
+ /// This is run after the Up transaction has been committed
+ ///
+ public virtual void AfterUp()
+ {
+ }
- ///
- /// Defines transformations to revert things done in Up.
- ///
- public void Down()
- {
- }
+ ///
+ /// Defines transformations to revert things done in Up.
+ ///
+ public void Down()
+ {
+ }
- ///
- /// This is run after the Down transaction has been committed
- ///
- public virtual void AfterDown()
- {
- }
+ ///
+ /// This is run after the Down transaction has been committed
+ ///
+ public virtual void AfterDown()
+ {
+ }
- ///
- /// Represents the database.
- /// .
- ///
- /// Migration.Framework.ITransformationProvider
- public ITransformationProvider Database { get; set; }
+ ///
+ /// Represents the database.
+ /// .
+ ///
+ /// Migration.Framework.ITransformationProvider
+ public ITransformationProvider Database { get; set; }
- ///
- /// This gets called once on the first migration object.
- ///
- public virtual void InitializeOnce(string[] args)
- {
- }
- }
-}
\ No newline at end of file
+ ///
+ /// This gets called once on the first migration object.
+ ///
+ public virtual void InitializeOnce(string[] args)
+ {
+ }
+}
diff --git a/src/Migrator.Tests/Database/Data/Common/EntityConfiguration.cs b/src/Migrator.Tests/Database/Data/Common/EntityConfiguration.cs
new file mode 100644
index 00000000..2b3a5f18
--- /dev/null
+++ b/src/Migrator.Tests/Database/Data/Common/EntityConfiguration.cs
@@ -0,0 +1,15 @@
+using LinqToDB.Mapping;
+using Migrator.Tests.Database.Data.Common.Interfaces;
+
+namespace Migrator.Tests.Database.Data.Common;
+
+public abstract class EntityConfiguration(FluentMappingBuilder fluentMappingBuilder) : IEntityConfiguration where T : class
+{
+ protected EntityMappingBuilder _EntityMappingBuilder = fluentMappingBuilder.Entity();
+ protected FluentMappingBuilder _FluentMappingBuilder = fluentMappingBuilder;
+
+ ///
+ /// Configures the entity in the fluent migrator of Linq2db
+ ///
+ public abstract void ConfigureEntity();
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/Data/Common/Interfaces/IEntityConfiguration.cs b/src/Migrator.Tests/Database/Data/Common/Interfaces/IEntityConfiguration.cs
new file mode 100644
index 00000000..7ada7a23
--- /dev/null
+++ b/src/Migrator.Tests/Database/Data/Common/Interfaces/IEntityConfiguration.cs
@@ -0,0 +1,9 @@
+namespace Migrator.Tests.Database.Data.Common.Interfaces;
+
+public interface IEntityConfiguration
+{
+ ///
+ /// Configure the entity mapping.
+ ///
+ void ConfigureEntity();
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/Data/Common/Interfaces/IMappingSchemaFactory.cs b/src/Migrator.Tests/Database/Data/Common/Interfaces/IMappingSchemaFactory.cs
new file mode 100644
index 00000000..7fb68e3b
--- /dev/null
+++ b/src/Migrator.Tests/Database/Data/Common/Interfaces/IMappingSchemaFactory.cs
@@ -0,0 +1,8 @@
+using LinqToDB.Mapping;
+
+namespace Migrator.Tests.Database.Data.Common.Interfaces;
+
+public interface IMappingSchemaFactory
+{
+ MappingSchema CreateOracleMappingSchema();
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/Data/Common/MappingSchemaFactory.cs b/src/Migrator.Tests/Database/Data/Common/MappingSchemaFactory.cs
new file mode 100644
index 00000000..e044f899
--- /dev/null
+++ b/src/Migrator.Tests/Database/Data/Common/MappingSchemaFactory.cs
@@ -0,0 +1,39 @@
+using System.Collections.Generic;
+using LinqToDB.Mapping;
+using Migrator.Tests.Database.Data.Common.Interfaces;
+using Migrator.Tests.Database.Data.Mappings.Oracle;
+
+namespace DotNetProjects.Migrator.Framework.Data.Common;
+
+public class MappingSchemaFactory() : IMappingSchemaFactory
+{
+ public MappingSchema CreateOracleMappingSchema()
+ {
+ var fluentMappingBuilder = new FluentMappingBuilder();
+
+ var configs = new List
+ {
+ new OracleAllConsColumnsConfiguration(fluentMappingBuilder),
+ new OracleAllConstraintsConfiguration(fluentMappingBuilder),
+ new OracleAllTabColumnsConfiguration(fluentMappingBuilder),
+ new OracleAllTabColumnsConfiguration(fluentMappingBuilder),
+ new OracleAllUsersConfiguration(fluentMappingBuilder),
+ new OracleDBADataFilesConfiguration(fluentMappingBuilder),
+ new OracleVSessionConfiguration(fluentMappingBuilder),
+ };
+
+ return Configure(fluentMappingBuilder, configs);
+ }
+
+ private static MappingSchema Configure(FluentMappingBuilder fluentMappingBuilder, IEnumerable entityConfigurations)
+ {
+ foreach (var config in entityConfigurations)
+ {
+ config.ConfigureEntity();
+ }
+
+ fluentMappingBuilder.Build();
+
+ return fluentMappingBuilder.MappingSchema;
+ }
+}
diff --git a/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleAllConsColumnsConfiguration.cs b/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleAllConsColumnsConfiguration.cs
new file mode 100644
index 00000000..ea016267
--- /dev/null
+++ b/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleAllConsColumnsConfiguration.cs
@@ -0,0 +1,29 @@
+using DotNetProjects.Migrator.Framework.Data.Models.Oracle;
+using LinqToDB.Mapping;
+using Migrator.Tests.Database.Data.Common;
+
+namespace Migrator.Tests.Database.Data.Mappings.Oracle;
+
+public class OracleAllConsColumnsConfiguration(FluentMappingBuilder fluentMappingBuilder)
+ : EntityConfiguration(fluentMappingBuilder)
+{
+ public override void ConfigureEntity()
+ {
+ _EntityMappingBuilder!.HasTableName("ALL_CONS_COLUMNS");
+
+ _EntityMappingBuilder.Property(x => x.ColumnName)
+ .HasColumnName("COLUMN_NAME");
+
+ _EntityMappingBuilder.Property(x => x.ConstraintName)
+ .HasColumnName("CONSTRAINT_NAME");
+
+ _EntityMappingBuilder.Property(x => x.Owner)
+ .HasColumnName("OWNER");
+
+ _EntityMappingBuilder.Property(x => x.Position)
+ .HasColumnName("POSITION");
+
+ _EntityMappingBuilder.Property(x => x.TableName)
+ .HasColumnName("TABLE_NAME");
+ }
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleAllConstraintsConfiguration.cs b/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleAllConstraintsConfiguration.cs
new file mode 100644
index 00000000..88c22e53
--- /dev/null
+++ b/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleAllConstraintsConfiguration.cs
@@ -0,0 +1,35 @@
+using DotNetProjects.Migrator.Framework.Data.Models.Oracle;
+using LinqToDB.Mapping;
+using Migrator.Tests.Database.Data.Common;
+
+namespace Migrator.Tests.Database.Data.Mappings.Oracle;
+
+public class OracleAllConstraintsConfiguration(FluentMappingBuilder fluentMappingBuilder)
+ : EntityConfiguration(fluentMappingBuilder)
+{
+ public override void ConfigureEntity()
+ {
+ _EntityMappingBuilder!.HasTableName("ALL_CONSTRAINTS");
+
+ _EntityMappingBuilder.Property(x => x.ConstraintName)
+ .HasColumnName("CONSTRAINT_NAME");
+
+ _EntityMappingBuilder.Property(x => x.RConstraintName)
+ .HasColumnName("R_CONSTRAINT_NAME");
+
+ _EntityMappingBuilder.Property(x => x.ROwner)
+ .HasColumnName("R_OWNER");
+
+ _EntityMappingBuilder.Property(x => x.ConstraintType)
+ .HasColumnName("CONSTRAINT_TYPE");
+
+ _EntityMappingBuilder.Property(x => x.Owner)
+ .HasColumnName("OWNER");
+
+ _EntityMappingBuilder.Property(x => x.Status)
+ .HasColumnName("STATUS");
+
+ _EntityMappingBuilder.Property(x => x.TableName)
+ .HasColumnName("TABLE_NAME");
+ }
+}
diff --git a/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleAllTabColumnsConfiguration.cs b/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleAllTabColumnsConfiguration.cs
new file mode 100644
index 00000000..da72fa1a
--- /dev/null
+++ b/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleAllTabColumnsConfiguration.cs
@@ -0,0 +1,38 @@
+using DotNetProjects.Migrator.Framework.Data.Models.Oracle;
+using LinqToDB.Mapping;
+using Migrator.Tests.Database.Data.Common;
+
+namespace Migrator.Tests.Database.Data.Mappings.Oracle;
+
+public class OracleAllTabColumnsConfiguration(FluentMappingBuilder fluentMappingBuilder)
+ : EntityConfiguration(fluentMappingBuilder)
+{
+ public override void ConfigureEntity()
+ {
+ _EntityMappingBuilder!.HasTableName("ALL_TAB_COLUMNS");
+
+ _EntityMappingBuilder.Property(x => x.ColumnName)
+ .HasColumnName("COLUMN_NAME");
+
+ _EntityMappingBuilder.Property(x => x.DataDefault)
+ .HasColumnName("DATA_DEFAULT");
+
+ _EntityMappingBuilder.Property(x => x.DataLength)
+ .HasColumnName("DATA_LENGTH");
+
+ _EntityMappingBuilder.Property(x => x.DataType)
+ .HasColumnName("DATA_TYPE");
+
+ _EntityMappingBuilder.Property(x => x.IdentityColumn)
+ .HasColumnName("IDENTITY_COLUMN");
+
+ _EntityMappingBuilder.Property(x => x.Nullable)
+ .HasColumnName("NULLABLE");
+
+ _EntityMappingBuilder.Property(x => x.Owner)
+ .HasColumnName("OWNER");
+
+ _EntityMappingBuilder.Property(x => x.TableName)
+ .HasColumnName("TABLE_NAME");
+ }
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleAllUsersConfiguration.cs b/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleAllUsersConfiguration.cs
new file mode 100644
index 00000000..acdb6c69
--- /dev/null
+++ b/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleAllUsersConfiguration.cs
@@ -0,0 +1,17 @@
+using DotNetProjects.Migrator.Framework.Data.Models.Oracle;
+using LinqToDB.Mapping;
+using Migrator.Tests.Database.Data.Common;
+
+namespace Migrator.Tests.Database.Data.Mappings.Oracle;
+
+public class OracleAllUsersConfiguration(FluentMappingBuilder fluentMappingBuilder)
+ : EntityConfiguration(fluentMappingBuilder)
+{
+ public override void ConfigureEntity()
+ {
+ _EntityMappingBuilder!.HasTableName("ALL_USERS");
+
+ _EntityMappingBuilder.Property(x => x.UserName)
+ .HasColumnName("USERNAME");
+ }
+}
diff --git a/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleDBADataFilesConfiguration.cs b/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleDBADataFilesConfiguration.cs
new file mode 100644
index 00000000..f7e5b767
--- /dev/null
+++ b/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleDBADataFilesConfiguration.cs
@@ -0,0 +1,20 @@
+using DotNetProjects.Migrator.Framework.Data.Models.Oracle;
+using LinqToDB.Mapping;
+using Migrator.Tests.Database.Data.Common;
+
+namespace Migrator.Tests.Database.Data.Mappings.Oracle;
+
+public class OracleDBADataFilesConfiguration(FluentMappingBuilder fluentMappingBuilder)
+ : EntityConfiguration(fluentMappingBuilder)
+{
+ public override void ConfigureEntity()
+ {
+ _EntityMappingBuilder!.HasTableName("DBA_DATA_FILES");
+
+ _EntityMappingBuilder.Property(x => x.FileName)
+ .HasColumnName("FILE_NAME");
+
+ _EntityMappingBuilder.Property(x => x.TablespaceName)
+ .HasColumnName("TABLESPACE_NAME");
+ }
+}
diff --git a/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleVSessionConfiguration.cs b/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleVSessionConfiguration.cs
new file mode 100644
index 00000000..a5a08343
--- /dev/null
+++ b/src/Migrator.Tests/Database/Data/Mappings/Oracle/OracleVSessionConfiguration.cs
@@ -0,0 +1,23 @@
+using DotNetProjects.Migrator.Framework.Data.Models.Oracle;
+using LinqToDB.Mapping;
+using Migrator.Tests.Database.Data.Common;
+
+namespace Migrator.Tests.Database.Data.Mappings.Oracle;
+
+public class OracleVSessionConfiguration(FluentMappingBuilder fluentMappingBuilder)
+ : EntityConfiguration(fluentMappingBuilder)
+{
+ public override void ConfigureEntity()
+ {
+ _EntityMappingBuilder!.HasTableName("V$SESSION");
+
+ _EntityMappingBuilder.Property(x => x.SerialHashTag)
+ .HasColumnName("SERIAL#");
+
+ _EntityMappingBuilder.Property(x => x.SID)
+ .HasColumnName("SID");
+
+ _EntityMappingBuilder.Property(x => x.UserName)
+ .HasColumnName("USERNAME");
+ }
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/Data/Models/Oracle/AllConsColumns.cs b/src/Migrator.Tests/Database/Data/Models/Oracle/AllConsColumns.cs
new file mode 100644
index 00000000..cd75ffc7
--- /dev/null
+++ b/src/Migrator.Tests/Database/Data/Models/Oracle/AllConsColumns.cs
@@ -0,0 +1,32 @@
+namespace DotNetProjects.Migrator.Framework.Data.Models.Oracle;
+
+///
+/// Represents the Oracle system table ALL_CONS_COLUMNS
+///
+public class AllConsColumns
+{
+ ///
+ /// Gets or sets the column name.
+ ///
+ public string ColumnName { get; set; }
+
+ ///
+ /// Gets or sets the name of the constraint definition.
+ ///
+ public string ConstraintName { get; set; }
+
+ ///
+ /// Gets or sets
+ ///
+ public int Position { get; set; }
+
+ ///
+ /// Gets or sets the name of the table with the constraint definition.
+ ///
+ public string TableName { get; set; }
+
+ ///
+ /// Gets or sets the owner of the constraint definition.
+ ///
+ public string Owner { get; set; }
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/Data/Models/Oracle/AllConstraints.cs b/src/Migrator.Tests/Database/Data/Models/Oracle/AllConstraints.cs
new file mode 100644
index 00000000..cae0f3aa
--- /dev/null
+++ b/src/Migrator.Tests/Database/Data/Models/Oracle/AllConstraints.cs
@@ -0,0 +1,55 @@
+namespace DotNetProjects.Migrator.Framework.Data.Models.Oracle;
+
+///
+/// Represents the Oracle system table ALL_CONSTRAINTS
+///
+public class AllConstraints
+{
+ ///
+ /// Gets or sets the name of the constraint definition.
+ ///
+ public string ConstraintName { get; set; }
+
+ ///
+ /// Gets or sets the name of the unique constraint definition for the referenced table (R_CONSTRAINT_NAME)
+ ///
+ public string RConstraintName { get; set; }
+
+ ///
+ /// Gets or sets the constraint type.
+ ///
+ /// Type of the constraint definition:
+ ///
+ /// C - Check constraint on a table
+ /// P - Primary key
+ /// U - Unique key
+ /// R - Referential integrity
+ /// V - With check option, on a view
+ /// O - With read only, on a view
+ /// H - Hash expression
+ /// F - Constraint that involves a REF column
+ /// S - Supplemental logging
+ ///
+ ///
+ public string ConstraintType { get; set; }
+
+ ///
+ /// Gets or sets the owner of the constraint definition.
+ ///
+ public string Owner { get; set; }
+
+ ///
+ /// Gets or sets the owner of the table referred to in a referential constraint (R_OWNER)
+ ///
+ public string ROwner { get; set; }
+
+ ///
+ /// Gets or set the status. Enforcement status of the constraint: ENABLED / DISABLED
+ ///
+ public string Status { get; set; }
+
+ ///
+ /// Gets or sets the name associated with the table (or view) with the constraint definition.
+ ///
+ public string TableName { get; set; }
+}
diff --git a/src/Migrator.Tests/Database/Data/Models/Oracle/AllTabColumns.cs b/src/Migrator.Tests/Database/Data/Models/Oracle/AllTabColumns.cs
new file mode 100644
index 00000000..c9fa72e8
--- /dev/null
+++ b/src/Migrator.Tests/Database/Data/Models/Oracle/AllTabColumns.cs
@@ -0,0 +1,48 @@
+namespace DotNetProjects.Migrator.Framework.Data.Models.Oracle;
+
+///
+/// Represents the Oracle system table ALL_TAB_COLUMNS
+///
+public class AllTabColumns
+{
+ ///
+ /// Gets or sets the column name
+ ///
+ public string ColumnName { get; set; }
+
+ ///
+ /// Gets or sets the DATA_DEFAULT. This returns sth. like "SCHEMA"."ISEQ$$_1234".nextval
+ ///
+ public string DataDefault { get; set; }
+
+ ///
+ /// Gets or sets the length of the column (in bytes)
+ ///
+ public string DataLength { get; set; }
+
+ ///
+ /// Gets or sets the data type of the column
+ ///
+ public string DataType { get; set; }
+
+ ///
+ /// Indicates whether this is an identity column (YES) or not (NO)
+ ///
+ public string IdentityColumn { get; set; }
+
+ ///
+ /// Indicates whether a column allows NULLs. The value is N if there is a NOT NULL constraint on the column or if the column is part of a
+ /// PRIMARY KEY. The constraint should be in an ENABLE VALIDATE state.
+ ///
+ public string Nullable { get; set; }
+
+ ///
+ /// Gets or sets the name of the table, view, or cluster
+ ///
+ public string TableName { get; set; }
+
+ ///
+ /// Gets or sets the owner of the table, view, or cluster
+ ///
+ public string Owner { get; set; }
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/Data/Models/Oracle/AllUsers.cs b/src/Migrator.Tests/Database/Data/Models/Oracle/AllUsers.cs
new file mode 100644
index 00000000..eadf4c6d
--- /dev/null
+++ b/src/Migrator.Tests/Database/Data/Models/Oracle/AllUsers.cs
@@ -0,0 +1,12 @@
+namespace DotNetProjects.Migrator.Framework.Data.Models.Oracle;
+
+///
+/// Represents the Oracle system table ALL_USERS.
+///
+public class AllUsers
+{
+ ///
+ /// Gets or sets the name of the user.
+ ///
+ public string UserName { get; set; }
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/Data/Models/Oracle/DBADataFiles.cs b/src/Migrator.Tests/Database/Data/Models/Oracle/DBADataFiles.cs
new file mode 100644
index 00000000..a7aa3775
--- /dev/null
+++ b/src/Migrator.Tests/Database/Data/Models/Oracle/DBADataFiles.cs
@@ -0,0 +1,17 @@
+namespace DotNetProjects.Migrator.Framework.Data.Models.Oracle;
+
+///
+/// Represents the Oracle system table DBA_DATA_FILES.
+///
+public class DBADataFiles
+{
+ ///
+ /// Gets or sets the file name. (FILE_NAME)
+ ///
+ public string FileName { get; set; }
+
+ ///
+ /// Gets or sets the tablespace name. (TABLESPACE_NAME)
+ ///
+ public string TablespaceName { get; set; }
+}
diff --git a/src/Migrator.Tests/Database/Data/Models/Oracle/VSession.cs b/src/Migrator.Tests/Database/Data/Models/Oracle/VSession.cs
new file mode 100644
index 00000000..a3709d11
--- /dev/null
+++ b/src/Migrator.Tests/Database/Data/Models/Oracle/VSession.cs
@@ -0,0 +1,19 @@
+namespace DotNetProjects.Migrator.Framework.Data.Models.Oracle;
+
+public class VSession
+{
+ ///
+ /// Gets or sets the "serial#"
+ ///
+ public string SerialHashTag { get; set; }
+
+ ///
+ /// Gets or sets the session id (SID).
+ ///
+ public string SID { get; set; }
+
+ ///
+ /// Gets or sets the user name.
+ ///
+ public string UserName { get; set; }
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/DatabaseIntegrationTestServiceBase.cs b/src/Migrator.Tests/Database/DatabaseIntegrationTestServiceBase.cs
new file mode 100644
index 00000000..00450410
--- /dev/null
+++ b/src/Migrator.Tests/Database/DatabaseIntegrationTestServiceBase.cs
@@ -0,0 +1,36 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using Migrator.Tests.Database.DatabaseName.Interfaces;
+using Migrator.Tests.Database.Interfaces;
+using Migrator.Tests.Database.Models;
+using Migrator.Tests.Settings.Models;
+
+namespace Migrator.Tests.Database;
+
+public abstract class DatabaseIntegrationTestServiceBase(IDatabaseNameService databaseNameService) : IDatabaseIntegrationTestService
+{
+ ///
+ /// Deletes all integration test databases older than the given time span.
+ ///
+ // TODO CK time span!
+ protected readonly TimeSpan _MinTimeSpanBeforeDatabaseDeletion = TimeSpan.FromMinutes(1); // TimeSpan.FromMinutes(60);
+
+ protected IDatabaseNameService DatabaseNameService { get; private set; } = databaseNameService;
+
+ abstract public Task CreateTestDatabaseAsync(DatabaseConnectionConfig databaseConnectionConfig, CancellationToken cancellationToken);
+
+ abstract public Task DropDatabaseAsync(DatabaseInfo databaseInfo, CancellationToken cancellationToken);
+
+ protected DateTime ReadTimeStampFromDatabaseName(string name)
+ {
+ var creationDate = DatabaseNameService.ReadTimeStampFromString(name);
+
+ if (!creationDate.HasValue)
+ {
+ throw new Exception("You tried to drop a database that was not created by this service. For safety reasons we deny your request.");
+ }
+
+ return creationDate.Value;
+ }
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/DatabaseIntegrationTestServiceFactory.cs b/src/Migrator.Tests/Database/DatabaseIntegrationTestServiceFactory.cs
new file mode 100644
index 00000000..424f5a27
--- /dev/null
+++ b/src/Migrator.Tests/Database/DatabaseIntegrationTestServiceFactory.cs
@@ -0,0 +1,12 @@
+using DryIoc;
+using Migrator.Tests.Database.Interfaces;
+
+namespace Migrator.Tests.Database;
+
+public class DatabaseIntegrationTestServiceFactory(IResolver resolver) : IDatabaseIntegrationTestServiceFactory
+{
+ public IDatabaseIntegrationTestService Create(DatabaseProviderType providerType)
+ {
+ return resolver.Resolve(serviceKey: providerType);
+ }
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/DatabaseIntegrationTestServiceRegistry.cs b/src/Migrator.Tests/Database/DatabaseIntegrationTestServiceRegistry.cs
new file mode 100644
index 00000000..268fd50a
--- /dev/null
+++ b/src/Migrator.Tests/Database/DatabaseIntegrationTestServiceRegistry.cs
@@ -0,0 +1,28 @@
+using Migrator.Tests.Database.DatabaseName.Interfaces;
+using Migrator.Tests.Database.GuidServices.Interfaces;
+using Migrator.Tests.Database.GuidServices;
+using Migrator.Tests.Database.Interfaces;
+using Migrator.Tests.Database.DerivedDatabaseIntegrationTestServices;
+using System;
+using DryIoc;
+using Migrator.Test.Shared.Database;
+using Migrator.Tests.Settings.Interfaces;
+using Migrator.Tests.Settings;
+
+namespace Migrator.Tests.Database;
+
+public static class DatabaseCreationServiceRegistry
+{
+ public static void RegisterDatabaseIntegrationTestService(this IRegistrator container)
+ {
+ container.Register(reuse: Reuse.Transient);
+ container.Register(reuse: Reuse.Transient);
+ container.RegisterInstance(TimeProvider.System, ifAlreadyRegistered: IfAlreadyRegistered.Keep);
+ container.Register(reuse: Reuse.Transient, ifAlreadyRegistered: IfAlreadyRegistered.Keep);
+ container.Register(serviceKey: DatabaseProviderType.Oracle);
+ container.Register(serviceKey: DatabaseProviderType.SQLite);
+ container.Register(serviceKey: DatabaseProviderType.Postgres);
+ container.Register(serviceKey: DatabaseProviderType.SQLServer);
+ container.Register(reuse: Reuse.Singleton, ifAlreadyRegistered: IfAlreadyRegistered.Keep);
+ }
+}
diff --git a/src/Migrator.Tests/Database/DatabaseName/DatabaseNameService.cs b/src/Migrator.Tests/Database/DatabaseName/DatabaseNameService.cs
new file mode 100644
index 00000000..505e396c
--- /dev/null
+++ b/src/Migrator.Tests/Database/DatabaseName/DatabaseNameService.cs
@@ -0,0 +1,56 @@
+using System;
+using System.Globalization;
+using System.IO;
+using System.Security.Cryptography;
+using System.Text.RegularExpressions;
+using Migrator.Tests.Database.DatabaseName.Interfaces;
+
+namespace Migrator.Test.Shared.Database;
+
+public partial class DatabaseNameService(TimeProvider timeProvider) : IDatabaseNameService
+{
+ private const string TestDatabaseString = "T";
+ private const string TimeStampPattern = "yyyyMMddHHmmssfff";
+
+ public DateTime? ReadTimeStampFromString(string name)
+ {
+ name = Path.GetFileNameWithoutExtension(name);
+
+ var regex = DateTimeRegex();
+ var match = regex.Match(name);
+
+ if (match.Success && DateTime.TryParseExact(match.Value, TimeStampPattern, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var res))
+ {
+ return res;
+ }
+
+ return null;
+ }
+
+ public string CreateDatabaseName()
+ {
+ var dateTimePattern = timeProvider.GetUtcNow()
+ .ToString(TimeStampPattern);
+
+ var randomString = CreateRandomChars(7);
+
+ return $"{dateTimePattern}{TestDatabaseString}{randomString}";
+ }
+
+ private string CreateRandomChars(int length)
+ {
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
+ var stringChars = new char[length];
+
+ for (var i = 0; i < length; i++)
+ {
+ var index = RandomNumberGenerator.GetInt32(chars.Length);
+ stringChars[i] = chars[index];
+ }
+
+ return new string(stringChars);
+ }
+
+ [GeneratedRegex(@"^([\d]+)(?=T.{7}$)")]
+ private static partial Regex DateTimeRegex();
+}
diff --git a/src/Migrator.Tests/Database/DatabaseName/Interfaces/IDatabaseNameService.cs b/src/Migrator.Tests/Database/DatabaseName/Interfaces/IDatabaseNameService.cs
new file mode 100644
index 00000000..c5be42e6
--- /dev/null
+++ b/src/Migrator.Tests/Database/DatabaseName/Interfaces/IDatabaseNameService.cs
@@ -0,0 +1,22 @@
+using System;
+
+namespace Migrator.Tests.Database.DatabaseName.Interfaces;
+
+///
+/// Used for integration tests. During integration tests we need to create unique database names for parallel testing.
+///
+public interface IDatabaseNameService
+{
+ ///
+ /// Reads the date time from the date part of the database or user name (in Oracle we use the user name/schema name).
+ ///
+ ///
+ ///
+ DateTime? ReadTimeStampFromString(string name);
+
+ ///
+ /// Creates a database name
+ ///
+ ///
+ string CreateDatabaseName();
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/DatabaseProviderType.cs b/src/Migrator.Tests/Database/DatabaseProviderType.cs
new file mode 100644
index 00000000..e477f508
--- /dev/null
+++ b/src/Migrator.Tests/Database/DatabaseProviderType.cs
@@ -0,0 +1,21 @@
+namespace Migrator.Tests.Database;
+
+public enum DatabaseProviderType
+{
+ // Do not use in any case not even as default
+ None = 0,
+
+ Unknown,
+
+ // Postgre SQL
+ Postgres,
+
+ // SQL Server
+ SQLServer,
+
+ // SQLite
+ SQLite,
+
+ // Oracle
+ Oracle
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/DerivedDatabaseIntegrationTestServices/OracleDatabaseIntegrationTestService.cs b/src/Migrator.Tests/Database/DerivedDatabaseIntegrationTestServices/OracleDatabaseIntegrationTestService.cs
new file mode 100644
index 00000000..6d41ace4
--- /dev/null
+++ b/src/Migrator.Tests/Database/DerivedDatabaseIntegrationTestServices/OracleDatabaseIntegrationTestService.cs
@@ -0,0 +1,210 @@
+using System;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using DotNetProjects.Migrator.Framework.Data.Common;
+using DotNetProjects.Migrator.Framework.Data.Models.Oracle;
+using LinqToDB;
+using LinqToDB.Async;
+using LinqToDB.Data;
+using LinqToDB.Mapping;
+using Mapster;
+using Migrator.Tests.Database.DatabaseName.Interfaces;
+using Migrator.Tests.Database.Interfaces;
+using Migrator.Tests.Database.Models;
+using Migrator.Tests.Settings.Models;
+using Oracle.ManagedDataAccess.Client;
+
+namespace Migrator.Tests.Database.DerivedDatabaseIntegrationTestServices;
+
+
+///
+/// We use the tablespace users since the server container is recreated before the test runs (once per github workflow run)
+///
+///
+///
+public class OracleDatabaseIntegrationTestService(
+ TimeProvider timeProvider,
+ IDatabaseNameService databaseNameService)
+ : DatabaseIntegrationTestServiceBase(databaseNameService), IDatabaseIntegrationTestService
+{
+ private const string UserStringKey = "User Id";
+ private const string PasswordStringKey = "Password";
+ private const string ReplaceString = "RandomStringThatIsNotQuotedByTheBuilderDoNotChange";
+ private readonly MappingSchema _mappingSchema = new MappingSchemaFactory().CreateOracleMappingSchema();
+
+ ///
+ /// Creates an oracle database for test purposes.
+ ///
+ ///
+ /// For the creation of the Oracle user used in this method follow these steps:
+ ///
+ /// Use a SYSDBA user, connect or switch to the default PDB.
+ /// On the free docker container the name of the default PDB is "FREEPDB1" use it as the service name or alternatively switch containers. For installations other than the "FREE" Oracle
+ /// Docker image find out the (default) PDB and switch to it then create grant privileges listed below. Having all set you can create a connection string using the newly created user
+ /// and password and add it to appsettings.Development (for dev environment)
+ ///
+ /// ALTER SESSION SET CONTAINER = FREEPDB1
+ /// CREATE USER myuser IDENTIFIED BY mypassword
+ /// GRANT CREATE USER TO myuser
+ /// GRANT DROP USER TO myuser
+ /// GRANT CREATE SESSION TO myuser WITH ADMIN OPTION
+ /// GRANT RESOURCE TO myuser WITH ADMIN OPTION
+ /// GRANT CONNECT TO myuser WITH ADMIN OPTION
+ /// GRANT UNLIMITED TABLESPACE TO myuser with ADMIN OPTION
+ /// GRANT SELECT ON V_$SESSION TO myuser with GRANT OPTION
+ /// GRANT ALTER SYSTEM TO myuser
+ ///
+ /// Having all set you can create a connection string using the newly created user and password and add it into appsettings.development
+ ///
+ ///
+ ///
+ ///
+ ///
+ public override async Task CreateTestDatabaseAsync(DatabaseConnectionConfig databaseConnectionConfig, CancellationToken cancellationToken)
+ {
+ var tempDatabaseConnectionConfig = databaseConnectionConfig.Adapt();
+
+ var connectionStringBuilder = new OracleConnectionStringBuilder()
+ {
+ ConnectionString = tempDatabaseConnectionConfig.ConnectionString
+ };
+
+ if (!connectionStringBuilder.TryGetValue(UserStringKey, out var user))
+ {
+ throw new Exception($"Cannot find key '{UserStringKey}'");
+ }
+
+ if (!connectionStringBuilder.TryGetValue(PasswordStringKey, out var password))
+ {
+ throw new Exception($"Cannot find key '{PasswordStringKey}'");
+ }
+
+ var tempUserName = DatabaseNameService.CreateDatabaseName();
+
+ var dataOptions = new DataOptions().UseOracle(databaseConnectionConfig.ConnectionString)
+ .UseMappingSchema(_mappingSchema);
+
+ using var context = new DataConnection(dataOptions);
+
+ var userNames = await context.GetTable().Select(x => x.UserName).ToListAsync(cancellationToken);
+
+ var toBeDeletedUsers = userNames.Where(x =>
+ {
+ var creationDate = DatabaseNameService.ReadTimeStampFromString(x);
+
+ return creationDate.HasValue && creationDate.Value < timeProvider.GetUtcNow().Subtract(_MinTimeSpanBeforeDatabaseDeletion);
+ }).ToList();
+
+ await Parallel.ForEachAsync(
+ toBeDeletedUsers,
+ new ParallelOptions { MaxDegreeOfParallelism = 3, CancellationToken = cancellationToken },
+ async (x, cancellationTokenInner) =>
+ {
+ var databaseInfoToBeDeleted = new DatabaseInfo
+ {
+ DatabaseConnectionConfig = databaseConnectionConfig.Adapt(),
+ DatabaseConnectionConfigMaster = databaseConnectionConfig.Adapt(),
+ SchemaName = x
+ };
+
+ await DropDatabaseAsync(databaseInfoToBeDeleted, cancellationTokenInner);
+ });
+
+ var stringBuilder = new StringBuilder();
+ stringBuilder.Append($"CREATE USER \"{tempUserName}\" IDENTIFIED BY \"{tempUserName}\"");
+ stringBuilder.AppendLine($"DEFAULT TABLESPACE users");
+ stringBuilder.AppendLine($"TEMPORARY TABLESPACE TEMP");
+ stringBuilder.AppendLine($"QUOTA UNLIMITED ON users");
+
+ await context.ExecuteAsync(stringBuilder.ToString(), cancellationToken);
+
+ var privileges = new[]
+ {
+ "CONNECT",
+ "CREATE SESSION",
+ "RESOURCE",
+ "UNLIMITED TABLESPACE"
+ };
+
+ await context.ExecuteAsync($"GRANT {string.Join(", ", privileges)} TO \"{tempUserName}\"", cancellationToken);
+ await context.ExecuteAsync($"GRANT SELECT ON SYS.GV_$SESSION TO \"{tempUserName}\"", cancellationToken);
+
+ connectionStringBuilder.Add(UserStringKey, ReplaceString);
+ connectionStringBuilder.Add(PasswordStringKey, ReplaceString);
+
+ tempDatabaseConnectionConfig.ConnectionString = connectionStringBuilder.ConnectionString;
+ tempDatabaseConnectionConfig.ConnectionString = tempDatabaseConnectionConfig.ConnectionString.Replace(ReplaceString, $"\"{tempUserName}\"");
+ tempDatabaseConnectionConfig.Schema = tempUserName;
+
+ var databaseInfo = new DatabaseInfo
+ {
+ DatabaseConnectionConfigMaster = databaseConnectionConfig.Adapt(),
+ DatabaseConnectionConfig = tempDatabaseConnectionConfig,
+ SchemaName = tempUserName,
+ };
+
+ return databaseInfo;
+ }
+
+ public override async Task DropDatabaseAsync(DatabaseInfo databaseInfo, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(databaseInfo);
+
+ var creationDate = ReadTimeStampFromDatabaseName(databaseInfo.SchemaName);
+
+ var dataOptions = new DataOptions().UseOracle(databaseInfo.DatabaseConnectionConfigMaster.ConnectionString)
+ .UseMappingSchema(_mappingSchema);
+
+ using var context = new DataConnection(dataOptions);
+
+ var maxAttempts = 4;
+ var delayBetweenAttempts = TimeSpan.FromSeconds(1);
+
+ for (var i = 0; i < maxAttempts; i++)
+ {
+ try
+ {
+ var vSessions = await context.GetTable()
+ .Where(x => x.UserName == databaseInfo.SchemaName)
+ .ToListAsync(cancellationToken);
+
+ foreach (var session in vSessions)
+ {
+ var killStatement = $"ALTER SYSTEM KILL SESSION '{session.SID},{session.SerialHashTag}' IMMEDIATE";
+ await context.ExecuteAsync(killStatement, cancellationToken);
+ }
+
+ var userExists = context.GetTable().Any(x => x.UserName == databaseInfo.SchemaName);
+
+ if (!userExists)
+ {
+ break;
+ }
+
+ await context.ExecuteAsync($"DROP USER \"{databaseInfo.SchemaName}\" CASCADE", cancellationToken);
+ }
+ catch
+ {
+ if (i + 1 == maxAttempts)
+ {
+ throw;
+ }
+
+ var userExists = await context.GetTable().AnyAsync(x => x.UserName == databaseInfo.SchemaName, token: cancellationToken);
+
+ if (!userExists)
+ {
+ break;
+ }
+
+ await Task.Delay(delayBetweenAttempts, cancellationToken);
+
+ delayBetweenAttempts = delayBetweenAttempts.Add(TimeSpan.FromSeconds(1));
+ }
+ }
+
+ await context.ExecuteAsync($"PURGE RECYCLEBIN", cancellationToken);
+ }
+}
diff --git a/src/Migrator.Tests/Database/DerivedDatabaseIntegrationTestServices/PostgreSqlDatabaseIntegrationTestService.cs b/src/Migrator.Tests/Database/DerivedDatabaseIntegrationTestServices/PostgreSqlDatabaseIntegrationTestService.cs
new file mode 100644
index 00000000..72847417
--- /dev/null
+++ b/src/Migrator.Tests/Database/DerivedDatabaseIntegrationTestServices/PostgreSqlDatabaseIntegrationTestService.cs
@@ -0,0 +1,114 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using LinqToDB;
+using LinqToDB.Data;
+using Mapster;
+using Migrator.Tests.Database.DatabaseName.Interfaces;
+using Migrator.Tests.Database.Interfaces;
+using Migrator.Tests.Database.Models;
+using Migrator.Tests.Settings.Models;
+using Npgsql;
+
+namespace Migrator.Tests.Database.DerivedDatabaseIntegrationTestServices;
+
+public class PostgreSqlDatabaseIntegrationTestService(TimeProvider timeProvider, IDatabaseNameService databaseNameService)
+ : DatabaseIntegrationTestServiceBase(databaseNameService), IDatabaseIntegrationTestService
+{
+ public override async Task CreateTestDatabaseAsync(DatabaseConnectionConfig databaseConnectionConfig, CancellationToken cancellationToken)
+ {
+ var clonedDatabaseConnectionConfig = databaseConnectionConfig.Adapt();
+
+ var builder = new NpgsqlConnectionStringBuilder
+ {
+ ConnectionString = clonedDatabaseConnectionConfig.ConnectionString,
+ Database = "postgres"
+ };
+
+ List databaseNames;
+
+ using (var context = new DataConnection(new DataOptions().UsePostgreSQL(builder.ConnectionString)))
+ {
+ databaseNames = await context.QueryToListAsync("SELECT datname from pg_database WHERE datistemplate = false", cancellationToken);
+ }
+
+ var toBeDeletedDatabaseNames = databaseNames.Where(x =>
+ {
+ var creationDate = DatabaseNameService.ReadTimeStampFromString(x);
+
+ return creationDate.HasValue && creationDate.Value < timeProvider.GetUtcNow().Subtract(_MinTimeSpanBeforeDatabaseDeletion);
+ }).ToList();
+
+ foreach (var databaseName in toBeDeletedDatabaseNames)
+ {
+ var databaseInfoToBeDeleted = new DatabaseInfo { DatabaseConnectionConfig = databaseConnectionConfig, DatabaseName = databaseName };
+ await DropDatabaseAsync(databaseInfoToBeDeleted, cancellationToken);
+ }
+
+ var newDatabaseName = DatabaseNameService.CreateDatabaseName();
+ using (var context = new DataConnection(new DataOptions().UsePostgreSQL(builder.ConnectionString)))
+ {
+ await context.ExecuteAsync($"CREATE DATABASE \"{newDatabaseName}\"", cancellationToken);
+ }
+
+ var connectionStringBuilder2 = new NpgsqlConnectionStringBuilder(clonedDatabaseConnectionConfig.ConnectionString)
+ {
+ Database = newDatabaseName
+ };
+
+ clonedDatabaseConnectionConfig.ConnectionString = connectionStringBuilder2.ConnectionString;
+
+ var databaseInfo = new DatabaseInfo
+ {
+ DatabaseConnectionConfig = clonedDatabaseConnectionConfig,
+ DatabaseName = newDatabaseName
+ };
+
+ return databaseInfo;
+ }
+
+ public override async Task DropDatabaseAsync(DatabaseInfo databaseInfo, CancellationToken cancellationToken)
+ {
+ var creationDate = DatabaseNameService.ReadTimeStampFromString(databaseInfo.DatabaseName);
+
+ if (!creationDate.HasValue)
+ {
+ throw new Exception("You tried to drop a database that was not created by this service. For safety reasons we deny your request.");
+ }
+
+ var builder = new NpgsqlConnectionStringBuilder(databaseInfo.DatabaseConnectionConfig.ConnectionString)
+ {
+ Database = "postgres"
+ };
+
+ var dataOptions = new DataOptions().UsePostgreSQL(builder.ConnectionString);
+
+ using (var context = new DataConnection(dataOptions))
+ {
+
+ try
+ {
+ await context.ExecuteAsync($"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '{databaseInfo.DatabaseName}'", cancellationToken);
+ await context.ExecuteAsync($"DROP DATABASE \"{databaseInfo.DatabaseName}\"", cancellationToken);
+ }
+ catch
+ {
+ await Task.Delay(2000, cancellationToken);
+
+ var count = await context.ExecuteAsync($"SELECT COUNT(*) from pg_database WHERE datistemplate = false AND datname = '{databaseInfo.DatabaseName}'", cancellationToken);
+
+ if (count == 1)
+ {
+ throw;
+ }
+ else
+ {
+ // The database was removed by another asynchronously running test that kicked in earlier.
+ // That's ok for us as we have achieved our objective.
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/DerivedDatabaseIntegrationTestServices/SQLiteDatabaseIntegrationTestService.cs b/src/Migrator.Tests/Database/DerivedDatabaseIntegrationTestServices/SQLiteDatabaseIntegrationTestService.cs
new file mode 100644
index 00000000..7b25159f
--- /dev/null
+++ b/src/Migrator.Tests/Database/DerivedDatabaseIntegrationTestServices/SQLiteDatabaseIntegrationTestService.cs
@@ -0,0 +1,134 @@
+using System;
+using System.Collections.Generic;
+using System.Data.Common;
+using System.Data.SQLite;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using LinqToDB;
+using LinqToDB.Data;
+using Mapster;
+using System.Linq;
+using Microsoft.Data.Sqlite;
+using Migrator.Tests.Database.DatabaseName.Interfaces;
+using Migrator.Tests.Database.Interfaces;
+using Migrator.Tests.Settings.Models;
+using Migrator.Tests.Database.Models;
+
+namespace Migrator.Tests.Database.DerivedDatabaseIntegrationTestServices;
+
+public class SQLiteDatabaseIntegrationTestService(TimeProvider timeProvider, IDatabaseNameService databaseNameService)
+ : DatabaseIntegrationTestServiceBase(databaseNameService), IDatabaseIntegrationTestService
+{
+ private const string SqliteDataSourceName = "data source";
+ private static readonly string[] _sqliteFileExtensions = ["*.sqlite", "*.db", "*.sqlite3", "*.db3", "*.sqlitedb", "*.*wal", "*.*shm", "*.*journal"];
+
+ public override async Task CreateTestDatabaseAsync(DatabaseConnectionConfig databaseConnectionConfig, CancellationToken cancellationToken)
+ {
+ var builder = new SQLiteConnectionStringBuilder { ConnectionString = databaseConnectionConfig.ConnectionString };
+
+ if (!builder.TryGetValue(SqliteDataSourceName, out var dataSource))
+ {
+ throw new Exception($@"No {SqliteDataSourceName} given in your SQLite connection string. Use a fully qualified path, e.g. Data Source=C:\bla\bla.db");
+ }
+
+ var dataSourceString = (string)dataSource;
+
+ if (dataSourceString.Contains("memory", StringComparison.InvariantCultureIgnoreCase))
+ {
+ throw new Exception("You are using an 'in memory' SQLite database connection string.");
+ }
+
+ if (!Path.IsPathFullyQualified(dataSourceString))
+ {
+ throw new Exception("You need to use a fully qualified path in your SQLite connection string.");
+ }
+
+ var directory = Path.GetDirectoryName(dataSourceString);
+
+ var filePaths = _sqliteFileExtensions.Select(x => Directory.EnumerateFiles(directory, x, SearchOption.TopDirectoryOnly))
+ .SelectMany(x => x)
+ .ToList();
+
+ List toBeDeletedDatabases = [];
+
+ foreach (var filePath in filePaths)
+ {
+ var fileName = Path.GetFileName(filePath);
+
+ var creationDate = DatabaseNameService.ReadTimeStampFromString(fileName);
+
+ if (creationDate.HasValue && creationDate.Value < timeProvider.GetUtcNow().Subtract(_MinTimeSpanBeforeDatabaseDeletion))
+ {
+ var builderExistingFile = new SqliteConnectionStringBuilder { DataSource = filePath };
+ var dataConnectionConfigExistingFile = databaseConnectionConfig.Adapt();
+ dataConnectionConfigExistingFile.ConnectionString = builderExistingFile.ConnectionString;
+
+ var databaseInfo = new DatabaseInfo
+ {
+ DatabaseConnectionConfig = dataConnectionConfigExistingFile,
+ DatabaseName = fileName
+ };
+
+ toBeDeletedDatabases.Add(databaseInfo);
+ }
+ }
+
+ foreach (var toBeDeletedDatabase in toBeDeletedDatabases)
+ {
+ await DropDatabaseAsync(toBeDeletedDatabase, cancellationToken);
+ }
+
+ builder.Remove(SqliteDataSourceName);
+
+ var newSqliteDatabaseName = $"{DatabaseNameService.CreateDatabaseName()}.db";
+ var fullSqliteDatabaseName = Path.Combine(directory, newSqliteDatabaseName);
+
+ builder.Add(SqliteDataSourceName, fullSqliteDatabaseName);
+
+ var newDatabaseConnectionConfig = databaseConnectionConfig.Adapt();
+ newDatabaseConnectionConfig.ConnectionString = builder.ConnectionString;
+
+ // Create the database file physically
+ using var context = new DataConnection(new DataOptions().UseSQLite(newDatabaseConnectionConfig.ConnectionString));
+
+ var databaseInfoNew = new DatabaseInfo
+ {
+ DatabaseConnectionConfig = newDatabaseConnectionConfig,
+ DatabaseConnectionConfigMaster = databaseConnectionConfig.Adapt(),
+ DatabaseName = newSqliteDatabaseName,
+ };
+
+ return databaseInfoNew;
+ }
+
+ public override async Task DropDatabaseAsync(DatabaseInfo databaseInfo, CancellationToken cancellationToken)
+ {
+ var builder = new DbConnectionStringBuilder { ConnectionString = databaseInfo.DatabaseConnectionConfig.ConnectionString };
+
+ if (!builder.TryGetValue(SqliteDataSourceName, out var dataSource))
+ {
+ throw new Exception();
+ }
+
+ var dataSourceString = (string)dataSource;
+
+ if (!Path.IsPathFullyQualified(dataSourceString))
+ {
+ throw new Exception("Path is not fully qualified.");
+ }
+
+ var fileName = Path.GetFileName(dataSourceString);
+
+ var creationDate = DatabaseNameService.ReadTimeStampFromString(fileName);
+
+ if (!creationDate.HasValue)
+ {
+ throw new Exception("You tried to drop a database that was not created by this service. For safety reasons we deny your request.");
+ }
+
+ File.Delete(dataSourceString);
+
+ await Task.CompletedTask;
+ }
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/DerivedDatabaseIntegrationTestServices/SqlServerDatabaseIntegrationTestService.cs b/src/Migrator.Tests/Database/DerivedDatabaseIntegrationTestServices/SqlServerDatabaseIntegrationTestService.cs
new file mode 100644
index 00000000..29aaaf6a
--- /dev/null
+++ b/src/Migrator.Tests/Database/DerivedDatabaseIntegrationTestServices/SqlServerDatabaseIntegrationTestService.cs
@@ -0,0 +1,111 @@
+using System;
+using System.Data.Common;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using LinqToDB;
+using LinqToDB.Data;
+using Mapster;
+using Microsoft.Data.SqlClient;
+using Migrator.Tests.Database.DatabaseName.Interfaces;
+using Migrator.Tests.Database.Interfaces;
+using Migrator.Tests.Database.Models;
+using Migrator.Tests.Settings.Models;
+
+namespace Migrator.Tests.Database.DerivedDatabaseIntegrationTestServices;
+
+public class SqlServerDatabaseIntegrationTestService(TimeProvider timeProvider, IDatabaseNameService databaseNameService)
+ : DatabaseIntegrationTestServiceBase(databaseNameService), IDatabaseIntegrationTestService
+{
+ private const string SqlServerInitialCatalogString = "Initial Catalog";
+
+ public override async Task CreateTestDatabaseAsync(DatabaseConnectionConfig databaseConnectionConfig, CancellationToken cancellationToken)
+ {
+ using var context = new DataConnection(new DataOptions().UseSqlServer(databaseConnectionConfig.ConnectionString));
+ await context.ExecuteAsync("use master", cancellationToken);
+
+ var databaseNames = context.Query($"SELECT name FROM sys.databases WHERE name NOT IN ('master', 'model', 'msdb', 'tempdb')").ToList();
+
+ var toBeDeletedDatabaseNames = databaseNames.Where(x =>
+ {
+ var creationDate = DatabaseNameService.ReadTimeStampFromString(x);
+ return creationDate.HasValue && creationDate.Value < timeProvider.GetUtcNow().Subtract(_MinTimeSpanBeforeDatabaseDeletion);
+ }).ToList();
+
+ foreach (var databaseName in toBeDeletedDatabaseNames)
+ {
+ var databaseInfoToBeDeleted = new DatabaseInfo { DatabaseConnectionConfig = databaseConnectionConfig, DatabaseName = databaseName };
+ await DropDatabaseAsync(databaseInfoToBeDeleted, cancellationToken);
+ }
+
+ var newDatabaseName = DatabaseNameService.CreateDatabaseName();
+
+ await context.ExecuteAsync($"CREATE DATABASE [{newDatabaseName}]", cancellationToken);
+
+ var clonedDatabaseConnectionConfig = databaseConnectionConfig.Adapt();
+
+ var builder = new DbConnectionStringBuilder
+ {
+ ConnectionString = clonedDatabaseConnectionConfig.ConnectionString
+ };
+
+ if (builder.TryGetValue(SqlServerInitialCatalogString, out var value))
+ {
+ builder.Remove(SqlServerInitialCatalogString);
+ builder.Add(SqlServerInitialCatalogString, newDatabaseName);
+ }
+
+ clonedDatabaseConnectionConfig.ConnectionString = builder.ConnectionString;
+
+ var databaseInfo = new DatabaseInfo
+ {
+ DatabaseConnectionConfig = clonedDatabaseConnectionConfig,
+ DatabaseName = newDatabaseName
+ };
+
+ return databaseInfo;
+ }
+
+ public override async Task DropDatabaseAsync(DatabaseInfo databaseInfo, CancellationToken cancellationToken)
+ {
+ var creationDate = DatabaseNameService.ReadTimeStampFromString(databaseInfo.DatabaseName);
+
+ if (!creationDate.HasValue)
+ {
+ throw new Exception("You tried to drop a database that was not created by this service. For safety reasons we deny your request.");
+ }
+
+ using var context = new DataConnection(new DataOptions().UseSqlServer(databaseInfo.DatabaseConnectionConfig.ConnectionString));
+ await context.ExecuteAsync("use master", cancellationToken);
+
+ try
+ {
+ await context.ExecuteAsync($"ALTER DATABASE [{databaseInfo.DatabaseName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE", cancellationToken);
+ await context.ExecuteAsync($"DROP DATABASE [{databaseInfo.DatabaseName}]", cancellationToken);
+ }
+ catch (SqlException ex)
+ {
+ // 3701: "Cannot drop the database because it does not exist or you do not have permission"
+ if (ex.Errors.Count > 0 && ex.Errors.Cast().Any(x => x.Number == 3701))
+ {
+ await Task.Delay(5000, cancellationToken);
+
+ var count = await context.ExecuteAsync($"SELECT COUNT(*) FROM sys.databases WHERE name = '{databaseInfo.DatabaseName}'");
+
+ if (count == 1)
+ {
+ throw new UnauthorizedAccessException($"The database '{databaseInfo.DatabaseName}' cannot be dropped but it still exists so we assume you do not have sufficient privileges to drop databases or this database.", ex);
+ }
+ else
+ {
+ // The database was removed by another (asynchronously) running test that kicked in earlier.
+ // That's ok for us as we have achieved the goal.
+ }
+ }
+ else
+ {
+ throw;
+ }
+ }
+ }
+}
diff --git a/src/Migrator.Tests/Database/GuidServices/GuidService.cs b/src/Migrator.Tests/Database/GuidServices/GuidService.cs
new file mode 100644
index 00000000..12662802
--- /dev/null
+++ b/src/Migrator.Tests/Database/GuidServices/GuidService.cs
@@ -0,0 +1,12 @@
+using System;
+using Migrator.Tests.Database.GuidServices.Interfaces;
+
+namespace Migrator.Tests.Database.GuidServices;
+
+public class GuidService : IGuidService
+{
+ public Guid NewGuid()
+ {
+ return Guid.NewGuid();
+ }
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/GuidServices/Interfaces/IGuidService.cs b/src/Migrator.Tests/Database/GuidServices/Interfaces/IGuidService.cs
new file mode 100644
index 00000000..16b66068
--- /dev/null
+++ b/src/Migrator.Tests/Database/GuidServices/Interfaces/IGuidService.cs
@@ -0,0 +1,13 @@
+using System;
+
+namespace Migrator.Tests.Database.GuidServices.Interfaces;
+
+public interface IGuidService
+{
+ ///
+ /// Creates a new database friendly Guid depending on the given database type.
+ ///
+ ///
+ ///
+ Guid NewGuid();
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/Interfaces/IDatabaseIntegrationTestService.cs b/src/Migrator.Tests/Database/Interfaces/IDatabaseIntegrationTestService.cs
new file mode 100644
index 00000000..cea8aee9
--- /dev/null
+++ b/src/Migrator.Tests/Database/Interfaces/IDatabaseIntegrationTestService.cs
@@ -0,0 +1,27 @@
+using System.Threading;
+using System.Threading.Tasks;
+using Migrator.Tests.Database.Models;
+using Migrator.Tests.Settings.Models;
+
+namespace Migrator.Tests.Database.Interfaces;
+
+public interface IDatabaseIntegrationTestService
+{
+ ///
+ /// Creates a new test database. The database name contains a timestamp and some random alphanumeric chars to increase uniqueness of the name.
+ /// It also removes old databases that could be leftovers from broken unit tests.
+ ///
+ ///
+ ///
+ ///
+ Task CreateTestDatabaseAsync(DatabaseConnectionConfig databaseConnectionConfig, CancellationToken cancellationToken);
+
+ ///
+ /// Drops a test database. The should hold the of the user with elevated privileges and the
+ /// Oracle: Schema should hold the name of the user (in Oracle the schema is equal to user)
+ ///
+ ///
+ ///
+ ///
+ Task DropDatabaseAsync(DatabaseInfo databaseInfo, CancellationToken cancellationToken);
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/Interfaces/IDatabaseIntegrationTestServiceFactory.cs b/src/Migrator.Tests/Database/Interfaces/IDatabaseIntegrationTestServiceFactory.cs
new file mode 100644
index 00000000..cc604348
--- /dev/null
+++ b/src/Migrator.Tests/Database/Interfaces/IDatabaseIntegrationTestServiceFactory.cs
@@ -0,0 +1,13 @@
+
+
+namespace Migrator.Tests.Database.Interfaces;
+
+public interface IDatabaseIntegrationTestServiceFactory
+{
+ ///
+ /// Creates a depending on the provider type (Oracle, PostgreSQL etc.).
+ ///
+ ///
+ ///
+ IDatabaseIntegrationTestService Create(DatabaseProviderType providerType);
+}
diff --git a/src/Migrator.Tests/Database/Models/DatabaseInfo.cs b/src/Migrator.Tests/Database/Models/DatabaseInfo.cs
new file mode 100644
index 00000000..d66c475a
--- /dev/null
+++ b/src/Migrator.Tests/Database/Models/DatabaseInfo.cs
@@ -0,0 +1,26 @@
+using Migrator.Tests.Settings.Models;
+
+namespace Migrator.Tests.Database.Models;
+
+public class DatabaseInfo
+{
+ ///
+ /// Gets or sets the master
+ ///
+ public DatabaseConnectionConfig DatabaseConnectionConfigMaster { get; set; }
+
+ ///
+ /// Cloned with manipulated connection string. The connection string contains the new database name.
+ ///
+ public DatabaseConnectionConfig DatabaseConnectionConfig { get; set; }
+
+ ///
+ /// Gets or sets the name of the created test database.
+ ///
+ public string DatabaseName { get; set; }
+
+ ///
+ /// Gets or sets the schema name. In Oracle the user name is equal to the schema name.
+ ///
+ public string SchemaName { get; set; }
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Database/Parsers/Interfaces/ILinq2DBNameToDatabaseServerTypeParser.cs b/src/Migrator.Tests/Database/Parsers/Interfaces/ILinq2DBNameToDatabaseServerTypeParser.cs
new file mode 100644
index 00000000..48888d9c
--- /dev/null
+++ b/src/Migrator.Tests/Database/Parsers/Interfaces/ILinq2DBNameToDatabaseServerTypeParser.cs
@@ -0,0 +1,11 @@
+namespace Migrator.Tests.Database.Parsers.Interfaces;
+
+public interface ILinq2DBNameToDatabaseServerTypeParser
+{
+ ///
+ /// Parses the Linq2Db provider name to .
+ ///
+ ///
+ ///
+ DatabaseProviderType Parse(string linq2DbName);
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Dialects/PostgreSQLDialectTests.cs b/src/Migrator.Tests/Dialects/PostgreSQLDialectTests.cs
new file mode 100644
index 00000000..11951b71
--- /dev/null
+++ b/src/Migrator.Tests/Dialects/PostgreSQLDialectTests.cs
@@ -0,0 +1,45 @@
+using DotNetProjects.Migrator.Providers.Impl.PostgreSQL;
+using DotNetProjects.Migrator.Providers.Models.Indexes.Enums;
+using NUnit.Framework;
+
+namespace Migrator.Tests.Dialects;
+
+[TestFixture]
+[Category("Postgre")]
+public class PostgreDialectTests
+{
+ private PostgreSQLDialect _postgreSQLDialect;
+
+ [SetUp]
+ public void SetUp()
+ {
+ // Since Dialect is abstract we use PostgreSQLDialect
+ _postgreSQLDialect = new PostgreSQLDialect();
+ }
+
+ [TestCase(FilterType.EqualTo, "=")]
+ [TestCase(FilterType.GreaterThanOrEqualTo, ">=")]
+ [TestCase(FilterType.SmallerThanOrEqualTo, "<=")]
+ [TestCase(FilterType.SmallerThan, "<")]
+ [TestCase(FilterType.GreaterThan, ">")]
+ [TestCase(FilterType.NotEqualTo, "<>")]
+ public void GetComparisonStringByFilterType_Success(FilterType filterType, string expectedString)
+ {
+ var result = _postgreSQLDialect.GetComparisonStringByFilterType(filterType);
+
+ Assert.That(result, Is.EqualTo(expectedString));
+ }
+
+ [TestCase("=", FilterType.EqualTo)]
+ [TestCase(">=", FilterType.GreaterThanOrEqualTo)]
+ [TestCase("<=", FilterType.SmallerThanOrEqualTo)]
+ [TestCase("<", FilterType.SmallerThan)]
+ [TestCase(">", FilterType.GreaterThan)]
+ [TestCase("<>", FilterType.NotEqualTo)]
+ public void GetFilterTypeByComparisonString_Success(string comparisonString, FilterType expectedFilterType)
+ {
+ var result = _postgreSQLDialect.GetFilterTypeByComparisonString(comparisonString);
+
+ Assert.That(result, Is.EqualTo(expectedFilterType));
+ }
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Framework/ColumnProperties/ColumnPropertyExtensionTests.cs b/src/Migrator.Tests/Framework/ColumnProperties/ColumnPropertyExtensionTests.cs
new file mode 100644
index 00000000..d2f822d6
--- /dev/null
+++ b/src/Migrator.Tests/Framework/ColumnProperties/ColumnPropertyExtensionTests.cs
@@ -0,0 +1,90 @@
+using NUnit.Framework;
+using DotNetProjects.Migrator.Framework;
+using System;
+using System.Linq;
+
+namespace Migrator.Tests.Framework.ColumnProperties;
+
+public class ColumnPropertyExtensionsTests
+{
+ [Test]
+ public void Clear()
+ {
+ // Arrange
+ var columnProperty = ColumnProperty.PrimaryKey | ColumnProperty.NotNull;
+
+ // Act
+ columnProperty = columnProperty.Clear(ColumnProperty.PrimaryKey);
+
+ // Assert
+ Assert.That(columnProperty.HasFlag(ColumnProperty.PrimaryKey), Is.False);
+ }
+
+ [Test]
+ public void IsSet()
+ {
+ // Arrange
+ var columnProperty = ColumnProperty.PrimaryKeyWithIdentity | ColumnProperty.NotNull;
+
+ // Act
+ var actualData = GetAllSingleColumnProperties().Select(x => new
+ {
+ ColumnPropertyString = x.ToString(),
+ IsSet = columnProperty.IsSet(x),
+ IsNotSet = columnProperty.IsNotSet(x)
+ })
+ .ToList();
+
+ // Assert
+ string[] expectedSet = [nameof(ColumnProperty.PrimaryKey), nameof(ColumnProperty.NotNull), nameof(ColumnProperty.Identity)];
+ var actualDataShouldBeTrue = actualData.Where(x => expectedSet.Any(y => y == x.ColumnPropertyString)).ToList();
+ var actualDataShouldBeFalse = actualData.Where(x => !expectedSet.Any(y => y == x.ColumnPropertyString)).ToList();
+
+ Assert.That(actualDataShouldBeTrue.Select(x => x.IsSet), Has.All.True);
+ Assert.That(actualDataShouldBeFalse.Select(x => x.IsSet), Has.All.False);
+ }
+
+ [Test]
+ public void IsNotSet()
+ {
+ // Arrange
+ var columnProperty = ColumnProperty.PrimaryKeyWithIdentity | ColumnProperty.NotNull;
+
+ // Act
+ var actualData = GetAllSingleColumnProperties().Select(x => new
+ {
+ ColumnPropertyString = x.ToString(),
+ IsSet = columnProperty.IsNotSet(x),
+ IsNotSet = columnProperty.IsNotSet(x)
+ })
+ .ToList();
+
+ // Assert
+ string[] expectedSet = [nameof(ColumnProperty.PrimaryKey), nameof(ColumnProperty.NotNull), nameof(ColumnProperty.Identity)];
+ var actualDataShouldBeFalse = actualData.Where(x => expectedSet.Any(y => y == x.ColumnPropertyString)).ToList();
+ var actualDataShouldBeTrue = actualData.Where(x => !expectedSet.Any(y => y == x.ColumnPropertyString)).ToList();
+
+ Assert.That(actualDataShouldBeTrue.Select(x => x.IsNotSet), Has.All.True);
+ Assert.That(actualDataShouldBeFalse.Select(x => x.IsNotSet), Has.All.False);
+ }
+
+ [Test]
+ public void Set_Success()
+ {
+ // Arrange
+ var columnProperty = ColumnProperty.NotNull;
+
+ // Act
+ var result = columnProperty.Set(ColumnProperty.PrimaryKeyWithIdentity);
+
+ // Assert
+ var expected = ColumnProperty.NotNull | ColumnProperty.PrimaryKeyWithIdentity;
+
+ Assert.That(result, Is.EqualTo(expected));
+ }
+
+ private ColumnProperty[] GetAllSingleColumnProperties()
+ {
+ return [.. Enum.GetValues().Where(x => x == 0 || (x & (x - 1)) == 0)];
+ }
+}
\ No newline at end of file
diff --git a/src/Migrator.Tests/JoiningTableTransformationProviderExtensionsTests.cs b/src/Migrator.Tests/JoiningTableTransformationProviderExtensionsTests.cs
index f31286ec..dfdaabff 100644
--- a/src/Migrator.Tests/JoiningTableTransformationProviderExtensionsTests.cs
+++ b/src/Migrator.Tests/JoiningTableTransformationProviderExtensionsTests.cs
@@ -1,157 +1,216 @@
-using System.Data;
-using Migrator.Framework;
-using NUnit.Framework;
-using Rhino.Mocks;
-
-namespace Migrator.Tests
-{
- [TestFixture]
- public class JoiningTableTransformationProviderExtensionsTests
- {
- #region Setup/Teardown
-
- [SetUp]
- public void SetUp()
- {
- provider = MockRepository.GenerateStub();
- }
-
- #endregion
-
- ITransformationProvider provider;
-
- [Test]
- public void AddManyToManyJoiningTable_AddsPrimaryKey()
- {
- provider.AddManyToManyJoiningTable("dbo", "TestScenarios", "Id", "Versions", "Id");
-
- object[] args = provider.GetArgumentsForCallsMadeOn(stub => stub.AddPrimaryKey(null, null, null))[0];
-
- Assert.AreEqual("PK_TestScenarioVersions", args[0]);
- Assert.AreEqual("dbo.TestScenarioVersions", args[1]);
-
- var columns = (string[]) args[2];
-
- Assert.Contains("TestScenarioId", columns);
- Assert.Contains("VersionId", columns);
- }
-
- [Test]
- public void AddManyToManyJoiningTable_CreatesLeftHandSideColumn_WithCorrectName()
- {
- provider.AddManyToManyJoiningTable("dbo", "TestScenarios", "Id", "Versions", "Id");
-
- object[] args = provider.GetArgumentsForCallsMadeOn(stub => stub.AddTable(null, (Column[]) null))[0];
-
- Column lhsColumn = ((IDbField[]) args[1])[0] as Column;
-
- Assert.AreEqual(lhsColumn.Name, "TestScenarioId");
- Assert.AreEqual(DbType.Guid, lhsColumn.Type);
- Assert.AreEqual(ColumnProperty.NotNull, lhsColumn.ColumnProperty);
- }
-
- [Test]
- public void AddManyToManyJoiningTable_CreatesLeftHandSideForeignKey_WithCorrectAttributes()
- {
- provider.AddManyToManyJoiningTable("dbo", "TestScenarios", "Id", "Versions", "Id");
-
- object[] args = provider.GetArgumentsForCallsMadeOn(stub => stub.AddForeignKey(null, null, "", null, null, ForeignKeyConstraintType.NoAction))[0];
-
- Assert.AreEqual("dbo.TestScenarioVersions", args[1]);
- Assert.AreEqual("TestScenarioId", args[2]);
- Assert.AreEqual("dbo.TestScenarios", args[3]);
- Assert.AreEqual("Id", args[4]);
- Assert.AreEqual(ForeignKeyConstraintType.NoAction, args[5]);
- }
-
- [Test]
- public void AddManyToManyJoiningTable_CreatesLeftHandSideForeignKey_WithCorrectName()
- {
- provider.AddManyToManyJoiningTable("dbo", "TestScenarios", "Id", "Versions", "Id");
-
- object[] args = provider.GetArgumentsForCallsMadeOn(stub => stub.AddForeignKey(null, null, "", null, null, ForeignKeyConstraintType.NoAction))[0];
-
- Assert.AreEqual("FK_Scenarios_ScenarioVersions", args[0]);
- }
-
- [Test]
- public void AddManyToManyJoiningTable_CreatesRightHandSideColumn_WithCorrectName()
- {
- provider.AddManyToManyJoiningTable("dbo", "TestScenarios", "Id", "Versions", "Id");
-
- object[] args = provider.GetArgumentsForCallsMadeOn(stub => stub.AddTable(null, (Column[]) null))[0];
-
- Column rhsColumn = ((IDbField[]) args[1])[1] as Column;
-
- Assert.AreEqual(rhsColumn.Name, "VersionId");
- Assert.AreEqual(DbType.Guid, rhsColumn.Type);
- Assert.AreEqual(ColumnProperty.NotNull, rhsColumn.ColumnProperty);
- }
-
- [Test]
- public void AddManyToManyJoiningTable_CreatesRightHandSideForeignKey_WithCorrectAttributes()
- {
- provider.AddManyToManyJoiningTable("dbo", "TestScenarios", "Id", "Versions", "Id");
-
- object[] args = provider.GetArgumentsForCallsMadeOn(stub => stub.AddForeignKey(null, null, "", null, null, ForeignKeyConstraintType.NoAction))[1];
-
- Assert.AreEqual("dbo.TestScenarioVersions", args[1]);
- Assert.AreEqual("VersionId", args[2]);
- Assert.AreEqual("dbo.Versions", args[3]);
- Assert.AreEqual("Id", args[4]);
- Assert.AreEqual(ForeignKeyConstraintType.NoAction, args[5]);
- }
-
- [Test]
- public void AddManyToManyJoiningTable_CreatesRightHandSideForeignKey_WithCorrectName()
- {
- provider.AddManyToManyJoiningTable("dbo", "TestScenarios", "Id", "Versions", "Id");
-
- object[] args = provider.GetArgumentsForCallsMadeOn(stub => stub.AddForeignKey(null, null, "", null, null, ForeignKeyConstraintType.NoAction))[1];
-
- Assert.AreEqual("FK_Versions_ScenarioVersions", args[0]);
- }
-
- [Test]
- public void AddManyToManyJoiningTable_CreatesTableWithCorrectName()
- {
- provider.AddManyToManyJoiningTable("dbo", "TestScenarios", "Id", "Versions", "Id");
-
- object[] args = provider.GetArgumentsForCallsMadeOn(stub => stub.AddTable(null, (Column[]) null))[0];
-
- Assert.AreEqual("dbo.TestScenarioVersions", args[0]);
- }
-
- [Test]
- public void RemoveManyToManyJoiningTable_RemovesLhsForeignKey()
- {
- provider.RemoveManyToManyJoiningTable("dbo", "TestScenarios", "Versions");
-
- object[] args = provider.GetArgumentsForCallsMadeOn(stub => stub.RemoveForeignKey(null, null))[0];
-
- Assert.AreEqual("dbo.TestScenarioVersions", args[0]);
- Assert.AreEqual("FK_Scenarios_ScenarioVersions", args[1]);
- }
-
- [Test]
- public void RemoveManyToManyJoiningTable_RemovesRhsForeignKey()
- {
- provider.RemoveManyToManyJoiningTable("dbo", "TestScenarios", "Versions");
-
- object[] args = provider.GetArgumentsForCallsMadeOn(stub => stub.RemoveForeignKey(null, null))[1];
-
- Assert.AreEqual("dbo.TestScenarioVersions", args[0]);
- Assert.AreEqual("FK_Versions_ScenarioVersions", args[1]);
- }
-
- [Test]
- public void RemoveManyToManyJoiningTable_RemovesTable()
- {
- provider.RemoveManyToManyJoiningTable("dbo", "TestScenarios", "Versions");
-
- object[] args = provider.GetArgumentsForCallsMadeOn(stub => stub.RemoveTable(null))[0];
-
- Assert.AreEqual("dbo.TestScenarioVersions", args[0]);
- }
- }
-}
\ No newline at end of file
+using System.Data;
+using DotNetProjects.Migrator.Framework;
+using DotNetProjects.Migrator.Framework.Support;
+using NSubstitute;
+using NUnit.Framework;
+
+namespace Migrator.Tests;
+
+[TestFixture]
+public class JoiningTableTransformationProviderExtensionsTests
+{
+ #region Setup/Teardown
+
+ [SetUp]
+ public void SetUp()
+ {
+ _provider = Substitute.For();
+ }
+
+ #endregion
+
+ private ITransformationProvider _provider;
+
+ [Test]
+ public void AddManyToManyJoiningTable_AddsPrimaryKey()
+ {
+ _provider
+ .When(x => x.AddPrimaryKey(Arg.Any(), Arg.Any(), Arg.Any()))
+ .Do(callInfo =>
+ {
+ var capturedName = callInfo[0] as string;
+ var capturedTable = callInfo[1] as string;
+ var columns = callInfo[2] as string[];
+ Assert.That(capturedName, Is.EqualTo("PK_TestScenarioVersions"));
+ Assert.That(capturedTable, Is.EqualTo("dbo.TestScenarioVersions"));
+ Assert.That(columns, Does.Contain("TestScenarioId"));
+ Assert.That(columns, Does.Contain("VersionId"));
+ });
+
+ _provider.AddManyToManyJoiningTable("dbo", "TestScenarios", "Id", "Versions", "Id");
+ }
+
+ [Test]
+ public void AddManyToManyJoiningTable_CreatesLeftHandSideColumn_WithCorrectName()
+ {
+ _provider
+ .When(x => x.AddTable(Arg.Any(), Arg.Any()))
+ .Do(callInfo =>
+ {
+ var lhsColumn = ((IDbField[])callInfo[1])[0] as Column;
+
+ Assert.That(lhsColumn.Name, Is.EqualTo("TestScenarioId"));
+ Assert.That(lhsColumn.Type, Is.EqualTo(DbType.Guid));
+ Assert.That(ColumnProperty.NotNull, Is.EqualTo(lhsColumn.ColumnProperty));
+ });
+
+ _provider.AddManyToManyJoiningTable("dbo", "TestScenarios", "Id", "Versions", "Id");
+ }
+
+ [Test]
+ public void AddManyToManyJoiningTable_CreatesLeftHandSideForeignKey_WithCorrectAttributes()
+ {
+ _provider
+ .When(x => x.AddForeignKey(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()))
+ .Do(callInfo =>
+ {
+ var lhsColumn = ((IDbField[])callInfo[1])[0] as Column;
+
+ Assert.That(callInfo[1] as string, Is.EqualTo("dbo.TestScenarioVersions"));
+ Assert.That(callInfo[2] as string, Is.EqualTo("TestScenarioId"));
+ Assert.That(callInfo[3] as string, Is.EqualTo("dbo.TestScenarios"));
+ Assert.That(callInfo[4] as string, Is.EqualTo("Id"));
+ Assert.That((ForeignKeyConstraintType)callInfo[5], Is.EqualTo(ForeignKeyConstraintType.NoAction));
+ });
+
+ _provider.AddManyToManyJoiningTable("dbo", "TestScenarios", "Id", "Versions", "Id");
+ }
+
+ [Test]
+ public void AddManyToManyJoiningTable_CreatesLeftHandSideForeignKey_WithCorrectName()
+ {
+ _provider
+ .When(x => x.AddForeignKey(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()))
+ .Do(callInfo =>
+ {
+ var lhsColumn = ((IDbField[])callInfo[1])[0] as Column;
+
+ Assert.That(callInfo[0] as string, Is.EqualTo("FK_Scenarios_ScenarioVersions"));
+ });
+
+ _provider.AddManyToManyJoiningTable("dbo", "TestScenarios", "Id", "Versions", "Id");
+ }
+
+ [Test]
+ public void AddManyToManyJoiningTable_CreatesRightHandSideColumn_WithCorrectName()
+ {
+ _provider
+ .When(x => x.AddTable(Arg.Any(), Arg.Any()))
+ .Do(callInfo =>
+ {
+ var rhsColumn = ((IDbField[])callInfo[1])[0] as Column;
+
+ Assert.That(rhsColumn.Name, Is.EqualTo("VersionId"));
+ Assert.That(DbType.Guid, Is.EqualTo(rhsColumn.Type));
+ Assert.That(ColumnProperty.NotNull, Is.EqualTo(rhsColumn.ColumnProperty));
+ });
+
+ _provider.AddManyToManyJoiningTable("dbo", "TestScenarios", "Id", "Versions", "Id");
+ }
+
+ [Test]
+ public void AddManyToManyJoiningTable_CreatesRightHandSideForeignKey_WithCorrectAttributes()
+ {
+ _provider
+ .When(x => x.AddTable(Arg.Any(), Arg.Any()))
+ .Do(callInfo =>
+ {
+ var rhsColumn = ((IDbField[])callInfo[1])[0] as Column;
+
+ Assert.That(rhsColumn.Name, Is.EqualTo("VersionId"));
+ Assert.That(DbType.Guid, Is.EqualTo(rhsColumn.Type));
+ Assert.That(ColumnProperty.NotNull, Is.EqualTo(rhsColumn.ColumnProperty));
+
+ Assert.That(callInfo[1] as string, Is.EqualTo("dbo.TestScenarioVersions"));
+ Assert.That(callInfo[2] as string, Is.EqualTo("VersionId"));
+ Assert.That(callInfo[3] as string, Is.EqualTo("dbo.Versions"));
+ Assert.That(callInfo[4] as string, Is.EqualTo("Id"));
+ Assert.That((ForeignKeyConstraintType)callInfo[5], Is.EqualTo(ForeignKeyConstraintType.NoAction));
+ });
+
+ _provider.AddManyToManyJoiningTable("dbo", "TestScenarios", "Id", "Versions", "Id");
+ }
+
+ [Test]
+ public void AddManyToManyJoiningTable_CreatesRightHandSideForeignKey_WithCorrectName()
+ {
+ _provider
+ .When(x => x.AddForeignKey(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()))
+ .Do(callInfo =>
+ {
+ var lhsColumn = ((IDbField[])callInfo[1])[0] as Column;
+
+ Assert.That(callInfo[0] as string, Is.EqualTo("FK_Scenarios_ScenarioVersions"));
+ });
+
+ _provider.AddManyToManyJoiningTable("dbo", "TestScenarios", "Id", "Versions", "Id");
+ }
+
+ [Test]
+ public void AddManyToManyJoiningTable_CreatesTableWithCorrectName()
+ {
+ _provider
+ .When(x => x.AddTable(Arg.Any(), Arg.Any()))
+ .Do(callInfo =>
+ {
+ var rhsColumn = ((IDbField[])callInfo[1])[0] as Column;
+
+ Assert.That(callInfo[1] as string, Is.EqualTo("dbo.TestScenarioVersions"));
+ });
+
+ _provider.AddManyToManyJoiningTable("dbo", "TestScenarios", "Id", "Versions", "Id");
+ }
+
+ [Test]
+ public void RemoveManyToManyJoiningTable_RemovesLhsForeignKey()
+ {
+ var callCount = 0;
+
+ _provider
+ .When(x => x.RemoveForeignKey(Arg.Any(), Arg.Any()))
+ .Do(callInfo =>
+ {
+ callCount++;
+ if (callCount == 1)
+ {
+ Assert.That(callInfo[0] as string, Is.EqualTo("dbo.TestScenarioVersions"));
+ Assert.That(callInfo[1] as string, Is.EqualTo("FK_Scenarios_ScenarioVersions"));
+ }
+ });
+
+ _provider.RemoveManyToManyJoiningTable("dbo", "TestScenarios", "Versions");
+ }
+
+ [Test]
+ public void RemoveManyToManyJoiningTable_RemovesRhsForeignKey()
+ {
+ var callCount = 0;
+
+ _provider
+ .When(x => x.RemoveForeignKey(Arg.Any(), Arg.Any()))
+ .Do(callInfo =>
+ {
+ callCount++;
+ if (callCount == 2)
+ {
+ Assert.That(callInfo[0] as string, Is.EqualTo("dbo.TestScenarioVersions"));
+ Assert.That(callInfo[1] as string, Is.EqualTo("FK_Versions_ScenarioVersions"));
+ }
+ });
+
+ _provider.RemoveManyToManyJoiningTable("dbo", "TestScenarios", "Versions");
+ }
+
+ [Test]
+ public void RemoveManyToManyJoiningTable_RemovesTable()
+ {
+ _provider
+ .When(x => x.RemoveTable(Arg.Any()))
+ .Do(callInfo =>
+ {
+ Assert.That(callInfo[0] as string, Is.EqualTo("dbo.TestScenarioVersions"));
+ });
+
+ _provider.RemoveManyToManyJoiningTable("dbo", "TestScenarios", "Versions");
+ }
+}
diff --git a/src/Migrator.Tests/MigrationLoaderTest.cs b/src/Migrator.Tests/MigrationLoaderTest.cs
index 01b197f1..fec13989 100644
--- a/src/Migrator.Tests/MigrationLoaderTest.cs
+++ b/src/Migrator.Tests/MigrationLoaderTest.cs
@@ -1,72 +1,80 @@
-using System.Reflection;
-using Migrator.Framework;
-using Migrator.Framework.Loggers;
-using NUnit.Framework;
-using NUnit.Mocks;
-
-namespace Migrator.Tests
-{
- [TestFixture]
- public class MigrationLoaderTest
- {
- #region Setup/Teardown
-
- [SetUp]
- public void SetUp()
- {
- SetUpCurrentVersion(0, false);
- }
-
- #endregion
-
- MigrationLoader _migrationLoader;
-
- void SetUpCurrentVersion(int version, bool assertRollbackIsCalled)
- {
- var providerMock = new DynamicMock(typeof (ITransformationProvider));
-
- providerMock.SetReturnValue("get_CurrentVersion", version);
- providerMock.SetReturnValue("get_Logger", new Logger(false));
- if (assertRollbackIsCalled)
- providerMock.Expect("Rollback");
- else
- providerMock.ExpectNoCall("Rollback");
-
- _migrationLoader = new MigrationLoader((ITransformationProvider) providerMock.MockInstance, Assembly.GetExecutingAssembly(), true);
- _migrationLoader.MigrationsTypes.Add(typeof (MigratorTest.FirstMigration));
- _migrationLoader.MigrationsTypes.Add(typeof (MigratorTest.SecondMigration));
- _migrationLoader.MigrationsTypes.Add(typeof (MigratorTest.ThirdMigration));
- _migrationLoader.MigrationsTypes.Add(typeof (MigratorTest.ForthMigration));
- _migrationLoader.MigrationsTypes.Add(typeof (MigratorTest.BadMigration));
- _migrationLoader.MigrationsTypes.Add(typeof (MigratorTest.SixthMigration));
- _migrationLoader.MigrationsTypes.Add(typeof (MigratorTest.NonIgnoredMigration));
- }
-
- [Test]
- [ExpectedException(typeof (DuplicatedVersionException))]
- public void CheckForDuplicatedVersion()
- {
- _migrationLoader.MigrationsTypes.Add(typeof (MigratorTest.FirstMigration));
- _migrationLoader.CheckForDuplicatedVersion();
- }
-
- [Test]
- public void LastVersion()
- {
- Assert.AreEqual(7, _migrationLoader.LastVersion);
- }
-
- [Test]
- public void NullIfNoMigrationForVersion()
- {
- Assert.IsNull(_migrationLoader.GetMigration(99999999));
- }
-
- [Test]
- public void ZeroIfNoMigrations()
- {
- _migrationLoader.MigrationsTypes.Clear();
- Assert.AreEqual(0, _migrationLoader.LastVersion);
- }
- }
-}
\ No newline at end of file
+using System.Reflection;
+using DotNetProjects.Migrator;
+using DotNetProjects.Migrator.Framework;
+using DotNetProjects.Migrator.Framework.Loggers;
+using NSubstitute;
+using NUnit.Framework;
+
+namespace Migrator.Tests;
+
+[TestFixture]
+public class MigrationLoaderTest
+{
+ #region Setup/Teardown
+
+ [SetUp]
+ public void SetUp()
+ {
+ SetUpCurrentVersion(0, false);
+ }
+
+ #endregion
+
+ private MigrationLoader _migrationLoader;
+
+ private void SetUpCurrentVersion(int version, bool assertRollbackIsCalled)
+ {
+ var providerMock = Substitute.For();
+
+ providerMock.Logger = new Logger(false);
+ providerMock.When(x => x.Dispose()).Do(_ =>
+ {
+ if (assertRollbackIsCalled)
+ {
+ providerMock.Received().Rollback();
+ }
+ else
+ {
+ providerMock.DidNotReceive().Rollback();
+ }
+ });
+
+ _migrationLoader = new MigrationLoader(providerMock, Assembly.GetExecutingAssembly(), true);
+ _migrationLoader.MigrationsTypes.Add(typeof(MigratorTest.FirstMigration));
+ _migrationLoader.MigrationsTypes.Add(typeof(MigratorTest.SecondMigration));
+ _migrationLoader.MigrationsTypes.Add(typeof(MigratorTest.ThirdMigration));
+ _migrationLoader.MigrationsTypes.Add(typeof(MigratorTest.ForthMigration));
+ _migrationLoader.MigrationsTypes.Add(typeof(MigratorTest.BadMigration));
+ _migrationLoader.MigrationsTypes.Add(typeof(MigratorTest.SixthMigration));
+ _migrationLoader.MigrationsTypes.Add(typeof(MigratorTest.NonIgnoredMigration));
+ }
+
+ [Test]
+ public void CheckForDuplicatedVersion()
+ {
+ _migrationLoader.MigrationsTypes.Add(typeof(MigratorTest.FirstMigration));
+ Assert.Throws(() =>
+ {
+ _migrationLoader.CheckForDuplicatedVersion();
+ });
+ }
+
+ [Test]
+ public void LastVersion()
+ {
+ Assert.That(7, Is.EqualTo(_migrationLoader.LastVersion));
+ }
+
+ [Test]
+ public void NullIfNoMigrationForVersion()
+ {
+ Assert.That(_migrationLoader.GetMigration(99999999), Is.Null);
+ }
+
+ [Test]
+ public void ZeroIfNoMigrations()
+ {
+ _migrationLoader.MigrationsTypes.Clear();
+ Assert.That(0, Is.EqualTo(_migrationLoader.LastVersion));
+ }
+}
diff --git a/src/Migrator.Tests/MigrationTestCase.cs b/src/Migrator.Tests/MigrationTestCase.cs
index e1627c8e..106d7cc6 100644
--- a/src/Migrator.Tests/MigrationTestCase.cs
+++ b/src/Migrator.Tests/MigrationTestCase.cs
@@ -12,49 +12,48 @@
#endregion
using System.Reflection;
-using Migrator.Providers;
+using DotNetProjects.Migrator.Providers;
using NUnit.Framework;
-namespace Migrator.Tests
+namespace Migrator.Tests;
+
+///
+/// Extend this classe to test your migrations
+///
+public abstract class MigrationsTestCase
{
- ///
- /// Extend this classe to test your migrations
- ///
- public abstract class MigrationsTestCase
- {
- Migrator _migrator;
-
- protected abstract TransformationProvider TransformationProvider { get; }
- protected abstract string ConnectionString { get; }
- protected abstract Assembly MigrationAssembly { get; }
-
- [SetUp]
- public void SetUp()
- {
- _migrator = new Migrator(TransformationProvider, MigrationAssembly, true);
-
- Assert.IsTrue(_migrator.MigrationsTypes.Count > 0, "No migrations in assembly " + MigrationAssembly.Location);
-
- _migrator.MigrateTo(0);
- }
-
- [TearDown]
- public void TearDown()
- {
- _migrator.MigrateTo(0);
- }
-
- [Test]
- public void Up()
- {
- _migrator.MigrateToLastVersion();
- }
-
- [Test]
- public void Down()
- {
- _migrator.MigrateToLastVersion();
- _migrator.MigrateTo(0);
- }
- }
+ private DotNetProjects.Migrator.Migrator _migrator;
+
+ protected abstract TransformationProvider TransformationProvider { get; }
+ protected abstract string ConnectionString { get; }
+ protected abstract Assembly MigrationAssembly { get; }
+
+ [SetUp]
+ public void SetUp()
+ {
+ _migrator = new DotNetProjects.Migrator.Migrator(TransformationProvider, MigrationAssembly, true);
+
+ Assert.That(_migrator.MigrationsTypes.Count > 0, Is.True, "No migrations in assembly " + MigrationAssembly.Location);
+
+ _migrator.MigrateTo(0);
+ }
+
+ [TearDown]
+ public void TearDown()
+ {
+ _migrator.MigrateTo(0);
+ }
+
+ [Test]
+ public void Up()
+ {
+ _migrator.MigrateToLastVersion();
+ }
+
+ [Test]
+ public void Down()
+ {
+ _migrator.MigrateToLastVersion();
+ _migrator.MigrateTo(0);
+ }
}
\ No newline at end of file
diff --git a/src/Migrator.Tests/MigrationTypeComparerTest.cs b/src/Migrator.Tests/MigrationTypeComparerTest.cs
index ead0f9cb..ae57d1d7 100644
--- a/src/Migrator.Tests/MigrationTypeComparerTest.cs
+++ b/src/Migrator.Tests/MigrationTypeComparerTest.cs
@@ -13,88 +13,88 @@
using System;
using System.Collections.Generic;
-using Migrator.Framework;
+using DotNetProjects.Migrator;
+using DotNetProjects.Migrator.Framework;
using NUnit.Framework;
-namespace Migrator.Tests
+namespace Migrator.Tests;
+
+[TestFixture]
+public class MigrationTypeComparerTest
{
- [TestFixture]
- public class MigrationTypeComparerTest
- {
- readonly Type[] _types = {
- typeof (Migration1),
- typeof (Migration2),
- typeof (Migration3)
- };
-
- [Migration(1, Ignore = true)]
- internal class Migration1 : Migration
- {
- public override void Up()
- {
- }
-
- public override void Down()
- {
- }
- }
-
- [Migration(2, Ignore = true)]
- internal class Migration2 : Migration
- {
- public override void Up()
- {
- }
-
- public override void Down()
- {
- }
- }
-
- [Migration(3, Ignore = true)]
- internal class Migration3 : Migration
- {
- public override void Up()
- {
- }
-
- public override void Down()
- {
- }
- }
-
- [Test]
- public void SortAscending()
- {
- var list = new List();
-
- list.Add(_types[1]);
- list.Add(_types[0]);
- list.Add(_types[2]);
-
- list.Sort(new MigrationTypeComparer(true));
-
- for (int i = 0; i < 3; i++)
- {
- Assert.AreSame(_types[i], list[i]);
- }
- }
-
- [Test]
- public void SortDescending()
- {
- var list = new List();
-
- list.Add(_types[1]);
- list.Add(_types[0]);
- list.Add(_types[2]);
-
- list.Sort(new MigrationTypeComparer(false));
-
- for (int i = 0; i < 3; i++)
- {
- Assert.AreSame(_types[2 - i], list[i]);
- }
- }
- }
+ private readonly Type[] _types = [
+ typeof (Migration1),
+ typeof (Migration2),
+ typeof (Migration3)
+ ];
+
+ [Migration(1, Ignore = true)]
+ internal class Migration1 : Migration
+ {
+ public override void Up()
+ {
+ }
+
+ public override void Down()
+ {
+ }
+ }
+
+ [Migration(2, Ignore = true)]
+ internal class Migration2 : Migration
+ {
+ public override void Up()
+ {
+ }
+
+ public override void Down()
+ {
+ }
+ }
+
+ [Migration(3, Ignore = true)]
+ internal class Migration3 : Migration
+ {
+ public override void Up()
+ {
+ }
+
+ public override void Down()
+ {
+ }
+ }
+
+ [Test]
+ public void SortAscending()
+ {
+ var list = new List();
+
+ list.Add(_types[1]);
+ list.Add(_types[0]);
+ list.Add(_types[2]);
+
+ list.Sort(new MigrationTypeComparer(true));
+
+ for (var i = 0; i < 3; i++)
+ {
+ Assert.That(_types[i], Is.SameAs(list[i]));
+ }
+ }
+
+ [Test]
+ public void SortDescending()
+ {
+ var list = new List();
+
+ list.Add(_types[1]);
+ list.Add(_types[0]);
+ list.Add(_types[2]);
+
+ list.Sort(new MigrationTypeComparer(false));
+
+ for (var i = 0; i < 3; i++)
+ {
+ Assert.That(_types[2 - i], Is.SameAs(list[i]));
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Migrator.Tests/Migrator.Tests-vs2008.csproj b/src/Migrator.Tests/Migrator.Tests-vs2008.csproj
deleted file mode 100644
index bf400ca3..00000000
--- a/src/Migrator.Tests/Migrator.Tests-vs2008.csproj
+++ /dev/null
@@ -1,141 +0,0 @@
-
-
- Debug
- AnyCPU
- 9.0.21022
- 2.0
- {882B6A93-67B8-45BF-8636-5796B1B1CBF8}
- Library
- Properties
- Migrator.Tests
- Migrator.Tests
-
-
- 2.0
-
-
- publish\
- true
- Disk
- false
- Foreground
- 7
- Days
- false
- false
- true
- 0
- 1.0.0.%2a
- false
- false
- true
-
-
- true
- full
- false
- bin\Migrator.Tests\Debug\
- TRACE;DEBUG;DOTNET2
- prompt
- 4
-
-
- pdbonly
- true
- bin\Migrator.Tests\Release\
- TRACE;DOTNET2
- prompt
- 4
-
-
-
- False
- ..\..\lib\NUnit\nunit.framework.dll
-
-
- False
- ..\..\lib\NUnit\nunit.mocks.dll
-
-
-
-
-
- ..\..\lib\System.Data.SqlServerCe.dll
- False
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {1FEE70A4-AAD7-4C60-BE60-3F7DC03A8C4D}
- Migrator-vs2008
-
-
- {5270F048-E580-486C-B14C-E5B9F6E539D4}
- Migrator.Framework-vs2008
-
-
- {D58C68E4-D789-40F7-9078-C9F587D4363C}
- Migrator.Providers-vs2008
-
-
-
-
- app.config
-
-
-
-
- False
- .NET Framework Client Profile
- false
-
-
- False
- .NET Framework 2.0 %28x86%29
- true
-
-
- False
- .NET Framework 3.0 %28x86%29
- false
-
-
- False
- .NET Framework 3.5
- false
-
-
- False
- .NET Framework 3.5 SP1
- false
-
-
-
-
\ No newline at end of file
diff --git a/src/Migrator.Tests/Migrator.Tests-vs2010.csproj b/src/Migrator.Tests/Migrator.Tests-vs2010.csproj
deleted file mode 100644
index 901836c6..00000000
--- a/src/Migrator.Tests/Migrator.Tests-vs2010.csproj
+++ /dev/null
@@ -1,185 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 9.0.21022
- 2.0
- {882B6A93-67B8-45BF-8636-5796B1B1CBF8}
- Library
- Properties
- Migrator.Tests
- Migrator.Tests
-
-
- 3.5
-
-
- false
- v4.0
- publish\
- true
- Disk
- false
- Foreground
- 7
- Days
- false
- false
- true
- 0
- 1.0.0.%2a
- false
- true
-
-
-
-
-
- true
- full
- false
- bin\Migrator.Tests\Debug\
- TRACE;DEBUG;DOTNET2
- prompt
- 4
- AllRules.ruleset
-
-
- pdbonly
- true
- bin\Migrator.Tests\Release\
- TRACE;DOTNET2
- prompt
- 4
- AllRules.ruleset
-
-
-
- ..\..\packages\FirebirdSql.Data.FirebirdClient.4.7.0.0\lib\net40-client\FirebirdSql.Data.FirebirdClient.dll
- True
-
-
- ..\..\packages\Npgsql.2.2.5\lib\net40\Mono.Security.dll
- True
-
-
- ..\..\packages\MySql.Data.6.9.7\lib\net40\MySql.Data.dll
- True
-
-
- ..\..\packages\Npgsql.2.2.5\lib\net40\Npgsql.dll
- True
-
-
- ..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll
- True
-
-
- ..\..\packages\NUnit.Mocks.2.6.4\lib\nunit.mocks.dll
- True
-
-
- ..\..\lib\Oracle.DataAccess.dll
-
-
- ..\..\packages\RhinoMocks.3.6.1\lib\net\Rhino.Mocks.dll
- True
-
-
-
-
-
- ..\..\packages\System.Data.SQLite.Core.1.0.97.0\lib\net40\System.Data.SQLite.dll
- True
-
-
- ..\..\lib\System.Data.SqlServerCe.dll
- False
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {1FEE70A4-AAD7-4C60-BE60-3F7DC03A8C4D}
- DotNetProjects.Migrator
-
-
- {5270F048-E580-486C-B14C-E5B9F6E539D4}
- DotNetProjects.Migrator.Framework
-
-
- {D58C68E4-D789-40F7-9078-C9F587D4363C}
- DotNetProjects.Migrator.Providers
-
-
-
-
- app.config
- Designer
-
-
-
-
-
- False
- .NET Framework 3.5 SP1 Client Profile
- false
-
-
- False
- .NET Framework 2.0 %28x86%29
- true
-
-
- False
- .NET Framework 3.0 %28x86%29
- false
-
-
- False
- .NET Framework 3.5
- false
-
-
- False
- .NET Framework 3.5 SP1
- false
-
-
-
-
-
-
- This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.
-
-
-
-
\ No newline at end of file
diff --git a/src/Migrator.Tests/Migrator.Tests.csproj b/src/Migrator.Tests/Migrator.Tests.csproj
new file mode 100644
index 00000000..456eae07
--- /dev/null
+++ b/src/Migrator.Tests/Migrator.Tests.csproj
@@ -0,0 +1,44 @@
+
+
+
+ net9.0
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/Migrator.Tests/MigratorTest.cs b/src/Migrator.Tests/MigratorTest.cs
index b883bf83..881cd519 100644
--- a/src/Migrator.Tests/MigratorTest.cs
+++ b/src/Migrator.Tests/MigratorTest.cs
@@ -1,250 +1,248 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
using System;
using System.Collections.Generic;
using System.Reflection;
-using Migrator.Framework;
-using Migrator.Framework.Loggers;
+using DotNetProjects.Migrator;
+using DotNetProjects.Migrator.Framework;
+using DotNetProjects.Migrator.Framework.Loggers;
+using NSubstitute;
using NUnit.Framework;
-using NUnit.Mocks;
-namespace Migrator.Tests
+namespace Migrator.Tests;
+
+[TestFixture]
+public class MigratorTest
{
- [TestFixture]
- public class MigratorTest
- {
- #region Setup/Teardown
-
- [SetUp]
- public void SetUp()
- {
- SetUpCurrentVersion(0);
- }
-
- #endregion
-
- Migrator _migrator;
-
- // Collections that contain the version that are called migrating up and down
- static readonly List _upCalled = new List();
- static readonly List _downCalled = new List();
-
- void SetUpCurrentVersion(long version)
- {
- SetUpCurrentVersion(version, false);
- }
-
- void SetUpCurrentVersion(long version, bool assertRollbackIsCalled)
- {
- SetUpCurrentVersion(version, assertRollbackIsCalled, true);
- }
-
- void SetUpCurrentVersion(long version, bool assertRollbackIsCalled, bool includeBad)
- {
- var providerMock = new DynamicMock(typeof (ITransformationProvider));
-
- var appliedVersions = new List();
- for (long i = 1; i <= version; i++)
- {
- appliedVersions.Add(i);
- }
- providerMock.SetReturnValue("get_AppliedMigrations", appliedVersions);
- providerMock.SetReturnValue("get_Logger", new Logger(false));
- if (assertRollbackIsCalled)
- providerMock.Expect("Rollback");
- else
- providerMock.ExpectNoCall("Rollback");
-
- _migrator = new Migrator((ITransformationProvider) providerMock.MockInstance, Assembly.GetExecutingAssembly(), false);
-
- // Enlève toutes les migrations trouvée automatiquement
- _migrator.MigrationsTypes.Clear();
- _upCalled.Clear();
- _downCalled.Clear();
-
- _migrator.MigrationsTypes.Add(typeof (FirstMigration));
- _migrator.MigrationsTypes.Add(typeof (SecondMigration));
- _migrator.MigrationsTypes.Add(typeof (ThirdMigration));
- _migrator.MigrationsTypes.Add(typeof (ForthMigration));
- _migrator.MigrationsTypes.Add(typeof (SixthMigration));
-
- if (includeBad)
- _migrator.MigrationsTypes.Add(typeof (BadMigration));
- }
-
- public class AbstractTestMigration : Migration
- {
- public override void Up()
- {
- _upCalled.Add(MigrationLoader.GetMigrationVersion(GetType()));
- }
-
- public override void Down()
- {
- _downCalled.Add(MigrationLoader.GetMigrationVersion(GetType()));
- }
- }
-
- [Migration(1, Ignore = true)]
- public class FirstMigration : AbstractTestMigration
- {
- }
-
- [Migration(2, Ignore = true)]
- public class SecondMigration : AbstractTestMigration
- {
- }
-
- [Migration(3, Ignore = true)]
- public class ThirdMigration : AbstractTestMigration
- {
- }
-
- [Migration(4, Ignore = true)]
- public class ForthMigration : AbstractTestMigration
- {
- }
-
- [Migration(5, Ignore = true)]
- public class BadMigration : AbstractTestMigration
- {
- public override void Up()
- {
- throw new Exception("oh uh!");
- }
-
- public override void Down()
- {
- throw new Exception("oh uh!");
- }
- }
-
- [Migration(6, Ignore = true)]
- public class SixthMigration : AbstractTestMigration
- {
- }
-
- [Migration(7)]
- public class NonIgnoredMigration : AbstractTestMigration
- {
- }
-
- [Test]
- public void MigrateBackward()
- {
- SetUpCurrentVersion(3);
- _migrator.MigrateTo(1);
-
- Assert.AreEqual(0, _upCalled.Count);
- Assert.AreEqual(2, _downCalled.Count);
-
- Assert.AreEqual(3, _downCalled[0]);
- Assert.AreEqual(2, _downCalled[1]);
- }
-
- [Test]
- public void MigrateDownwardWithRollback()
- {
- SetUpCurrentVersion(6, true);
-
- try
- {
- _migrator.MigrateTo(3);
- Assert.Fail("La migration 5 devrait lancer une exception");
- }
- catch (Exception)
- {
- }
-
- Assert.AreEqual(0, _upCalled.Count);
- Assert.AreEqual(1, _downCalled.Count);
-
- Assert.AreEqual(6, _downCalled[0]);
- }
-
- [Test]
- public void MigrateToCurrentVersion()
- {
- SetUpCurrentVersion(3);
-
- _migrator.MigrateTo(3);
-
- Assert.AreEqual(0, _upCalled.Count);
- Assert.AreEqual(0, _downCalled.Count);
- }
-
- [Test]
- public void MigrateToLastVersion()
- {
- SetUpCurrentVersion(3, false, false);
-
- _migrator.MigrateToLastVersion();
-
- Assert.AreEqual(2, _upCalled.Count);
- Assert.AreEqual(0, _downCalled.Count);
- }
-
- [Test]
- public void MigrateUpward()
- {
- SetUpCurrentVersion(1);
- _migrator.MigrateTo(3);
-
- Assert.AreEqual(2, _upCalled.Count);
- Assert.AreEqual(0, _downCalled.Count);
-
- Assert.AreEqual(2, _upCalled[0]);
- Assert.AreEqual(3, _upCalled[1]);
- }
-
- [Test]
- public void MigrateUpwardFrom0()
- {
- _migrator.MigrateTo(3);
-
- Assert.AreEqual(3, _upCalled.Count);
- Assert.AreEqual(0, _downCalled.Count);
-
- Assert.AreEqual(1, _upCalled[0]);
- Assert.AreEqual(2, _upCalled[1]);
- Assert.AreEqual(3, _upCalled[2]);
- }
-
- [Test]
- public void MigrateUpwardWithRollback()
- {
- SetUpCurrentVersion(3, true);
-
- try
- {
- _migrator.MigrateTo(6);
- Assert.Fail("La migration 5 devrait lancer une exception");
- }
- catch (Exception)
- {
- }
-
- Assert.AreEqual(1, _upCalled.Count);
- Assert.AreEqual(0, _downCalled.Count);
-
- Assert.AreEqual(4, _upCalled[0]);
- }
-
- [Test]
- public void ToHumanName()
- {
- Assert.AreEqual("Create a table", StringUtils.ToHumanName("CreateATable"));
- }
- }
-}
\ No newline at end of file
+ #region Setup/Teardown
+
+ [SetUp]
+ public void SetUp()
+ {
+ SetUpCurrentVersion(0);
+ }
+
+ #endregion
+
+ private DotNetProjects.Migrator.Migrator _migrator;
+
+ // Collections that contain the version that are called migrating up and down
+ private static readonly List _upCalled = new List();
+ private static readonly List _downCalled = new List();
+
+ private void SetUpCurrentVersion(long version)
+ {
+ SetUpCurrentVersion(version, false);
+ }
+
+ private void SetUpCurrentVersion(long version, bool assertRollbackIsCalled)
+ {
+ SetUpCurrentVersion(version, assertRollbackIsCalled, true);
+ }
+
+ private void SetUpCurrentVersion(long version, bool assertRollbackIsCalled, bool includeBad)
+ {
+ var providerMock = Substitute.For();
+
+ var appliedVersions = new List();
+
+ for (long i = 1; i <= version; i++)
+ {
+ appliedVersions.Add(i);
+ }
+
+ providerMock.AppliedMigrations.Returns(appliedVersions);
+ providerMock.Logger.Returns(new Logger(false));
+
+ providerMock.When(x => x.Dispose()).Do(_ =>
+ {
+ if (assertRollbackIsCalled)
+ {
+ providerMock.Received().Rollback();
+ }
+ else
+ {
+ providerMock.DidNotReceive().Rollback();
+ }
+ });
+
+ _migrator = new DotNetProjects.Migrator.Migrator((ITransformationProvider)providerMock, Assembly.GetExecutingAssembly(), false);
+
+ _migrator.MigrationsTypes.Clear();
+ _upCalled.Clear();
+ _downCalled.Clear();
+
+ _migrator.MigrationsTypes.Add(typeof(FirstMigration));
+ _migrator.MigrationsTypes.Add(typeof(SecondMigration));
+ _migrator.MigrationsTypes.Add(typeof(ThirdMigration));
+ _migrator.MigrationsTypes.Add(typeof(ForthMigration));
+ _migrator.MigrationsTypes.Add(typeof(SixthMigration));
+
+ if (includeBad)
+ {
+ _migrator.MigrationsTypes.Add(typeof(BadMigration));
+ }
+ }
+
+ public class AbstractTestMigration : Migration
+ {
+ public override void Up()
+ {
+ _upCalled.Add(MigrationLoader.GetMigrationVersion(GetType()));
+ }
+
+ public override void Down()
+ {
+ _downCalled.Add(MigrationLoader.GetMigrationVersion(GetType()));
+ }
+ }
+
+ [Migration(1, Ignore = true)]
+ public class FirstMigration : AbstractTestMigration
+ {
+ }
+
+ [Migration(2, Ignore = true)]
+ public class SecondMigration : AbstractTestMigration
+ {
+ }
+
+ [Migration(3, Ignore = true)]
+ public class ThirdMigration : AbstractTestMigration
+ {
+ }
+
+ [Migration(4, Ignore = true)]
+ public class ForthMigration : AbstractTestMigration
+ {
+ }
+
+ [Migration(5, Ignore = true)]
+ public class BadMigration : AbstractTestMigration
+ {
+ public override void Up()
+ {
+ throw new Exception("oh uh!");
+ }
+
+ public override void Down()
+ {
+ throw new Exception("oh uh!");
+ }
+ }
+
+ [Migration(6, Ignore = true)]
+ public class SixthMigration : AbstractTestMigration
+ {
+ }
+
+ [Migration(7)]
+ public class NonIgnoredMigration : AbstractTestMigration
+ {
+ }
+
+ [Test]
+ public void MigrateBackward()
+ {
+ SetUpCurrentVersion(3);
+ _migrator.MigrateTo(1);
+
+ Assert.That(0, Is.EqualTo(_upCalled.Count));
+ Assert.That(2, Is.EqualTo(_downCalled.Count));
+
+ Assert.That(3, Is.EqualTo(_downCalled[0]));
+ Assert.That(2, Is.EqualTo(_downCalled[1]));
+ }
+
+ [Test]
+ public void MigrateDownwardWithRollback()
+ {
+ SetUpCurrentVersion(6, true);
+
+ try
+ {
+ _migrator.MigrateTo(3);
+ Assert.Fail("La migration 5 devrait lancer une exception");
+ }
+ catch (Exception)
+ {
+ }
+
+ Assert.That(0, Is.EqualTo(_upCalled.Count));
+ Assert.That(1, Is.EqualTo(_downCalled.Count));
+
+ Assert.That(6, Is.EqualTo(_downCalled[0]));
+ }
+
+ [Test]
+ public void MigrateToCurrentVersion()
+ {
+ SetUpCurrentVersion(3);
+
+ _migrator.MigrateTo(3);
+
+ Assert.That(0, Is.EqualTo(_upCalled.Count));
+ Assert.That(0, Is.EqualTo(_downCalled.Count));
+ }
+
+ [Test]
+ public void MigrateToLastVersion()
+ {
+ SetUpCurrentVersion(3, false, false);
+
+ _migrator.MigrateToLastVersion();
+
+ Assert.That(2, Is.EqualTo(_upCalled.Count));
+ Assert.That(0, Is.EqualTo(_downCalled.Count));
+ }
+
+ [Test]
+ public void MigrateUpward()
+ {
+ SetUpCurrentVersion(1);
+ _migrator.MigrateTo(3);
+
+ Assert.That(2, Is.EqualTo(_upCalled.Count));
+ Assert.That(0, Is.EqualTo(_downCalled.Count));
+
+ Assert.That(2, Is.EqualTo(_upCalled[0]));
+ Assert.That(3, Is.EqualTo(_upCalled[1]));
+ }
+
+ [Test]
+ public void MigrateUpwardFrom0()
+ {
+ _migrator.MigrateTo(3);
+
+ Assert.That(3, Is.EqualTo(_upCalled.Count));
+ Assert.That(0, Is.EqualTo(_downCalled.Count));
+
+ Assert.That(1, Is.EqualTo(_upCalled[0]));
+ Assert.That(2, Is.EqualTo(_upCalled[1]));
+ Assert.That(3, Is.EqualTo(_upCalled[2]));
+ }
+
+ [Test]
+ public void MigrateUpwardWithRollback()
+ {
+ SetUpCurrentVersion(3, true);
+
+ try
+ {
+ _migrator.MigrateTo(6);
+ Assert.Fail("La migration 5 devrait lancer une exception");
+ }
+ catch (Exception)
+ {
+ }
+
+ Assert.That(1, Is.EqualTo(_upCalled.Count));
+ Assert.That(0, Is.EqualTo(_downCalled.Count));
+
+ Assert.That(4, Is.EqualTo(_upCalled[0]));
+ }
+
+ [Test]
+ public void ToHumanName()
+ {
+ Assert.That("Create a table", Is.EqualTo(StringUtils.ToHumanName("CreateATable")));
+ }
+}
diff --git a/src/Migrator.Tests/MigratorTestDates.cs b/src/Migrator.Tests/MigratorTestDates.cs
index edda6314..0065ef3f 100644
--- a/src/Migrator.Tests/MigratorTestDates.cs
+++ b/src/Migrator.Tests/MigratorTestDates.cs
@@ -1,312 +1,305 @@
-#region License
-
-//The contents of this file are subject to the Mozilla Public License
-//Version 1.1 (the "License"); you may not use this file except in
-//compliance with the License. You may obtain a copy of the License at
-//http://www.mozilla.org/MPL/
-//Software distributed under the License is distributed on an "AS IS"
-//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-//License for the specific language governing rights and limitations
-//under the License.
-
-#endregion
-
using System;
using System.Collections.Generic;
using System.Reflection;
-using Migrator.Framework;
-using Migrator.Framework.Loggers;
+using DotNetProjects.Migrator;
+using DotNetProjects.Migrator.Framework;
+using DotNetProjects.Migrator.Framework.Loggers;
+using NSubstitute;
using NUnit.Framework;
-using NUnit.Mocks;
-namespace Migrator.Tests
+namespace Migrator.Tests;
+
+[TestFixture]
+public class MigratorTestDates
{
- [TestFixture]
- public class MigratorTestDates
- {
- #region Setup/Teardown
-
- [SetUp]
- public void SetUp()
- {
- SetUpCurrentVersion(0);
- }
-
- #endregion
-
- Migrator _migrator;
-
- // Collections that contain the version that are called migrating up and down
- static readonly List _upCalled = new List();
- static readonly List _downCalled = new List();
-
- void SetUpCurrentVersion(long version)
- {
- SetUpCurrentVersion(version, false);
- }
-
- void SetUpCurrentVersion(long version, bool assertRollbackIsCalled)
- {
- SetUpCurrentVersion(version, assertRollbackIsCalled, true);
- }
-
- void SetUpCurrentVersion(long version, bool assertRollbackIsCalled, bool includeBad)
- {
- var appliedVersions = new List();
- for (long i = 2008010195; i <= version; i += 10000)
- {
- appliedVersions.Add(i);
- }
- SetUpCurrentVersion(version, appliedVersions, assertRollbackIsCalled, includeBad);
- }
-
- void SetUpCurrentVersion(long version, List appliedVersions, bool assertRollbackIsCalled, bool includeBad)
- {
- var providerMock = new DynamicMock(typeof (ITransformationProvider));
-
- providerMock.SetReturnValue("get_MaxVersion", version);
- providerMock.SetReturnValue("get_AppliedMigrations", appliedVersions);
- providerMock.SetReturnValue("get_Logger", new Logger(false));
- if (assertRollbackIsCalled)
- providerMock.Expect("Rollback");
- else
- providerMock.ExpectNoCall("Rollback");
-
- _migrator = new Migrator((ITransformationProvider) providerMock.MockInstance, Assembly.GetExecutingAssembly(), false);
-
- // Enlève toutes les migrations trouvée automatiquement
- _migrator.MigrationsTypes.Clear();
- _upCalled.Clear();
- _downCalled.Clear();
-
- _migrator.MigrationsTypes.Add(typeof (FirstMigration));
- _migrator.MigrationsTypes.Add(typeof (SecondMigration));
- _migrator.MigrationsTypes.Add(typeof (ThirdMigration));
- _migrator.MigrationsTypes.Add(typeof (FourthMigration));
- _migrator.MigrationsTypes.Add(typeof (SixthMigration));
-
- if (includeBad)
- _migrator.MigrationsTypes.Add(typeof (BadMigration));
- }
-
- public class AbstractTestMigration : Migration
- {
- public override void Up()
- {
- _upCalled.Add(MigrationLoader.GetMigrationVersion(GetType()));
- }
-
- public override void Down()
- {
- _downCalled.Add(MigrationLoader.GetMigrationVersion(GetType()));
- }
- }
-
- [Migration(2008010195, Ignore = true)]
- public class FirstMigration : AbstractTestMigration
- {
- }
-
- [Migration(2008020195, Ignore = true)]
- public class SecondMigration : AbstractTestMigration
- {
- }
-
- [Migration(2008030195, Ignore = true)]
- public class ThirdMigration : AbstractTestMigration
- {
- }
-
- [Migration(2008040195, Ignore = true)]
- public class FourthMigration : AbstractTestMigration
- {
- }
-
- [Migration(2008050195, Ignore = true)]
- public class BadMigration : AbstractTestMigration
- {
- public override void Up()
- {
- throw new Exception("oh uh!");
- }
-
- public override void Down()
- {
- throw new Exception("oh uh!");
- }
- }
-
- [Migration(2008060195, Ignore = true)]
- public class SixthMigration : AbstractTestMigration
- {
- }
-
- [Migration(2008070195)]
- public class NonIgnoredMigration : AbstractTestMigration
- {
- }
-
- [Test]
- public void MigrateBackward()
- {
- SetUpCurrentVersion(2008030195);
- _migrator.MigrateTo(2008010195);
-
- Assert.AreEqual(0, _upCalled.Count);
- Assert.AreEqual(2, _downCalled.Count);
-
- Assert.AreEqual(2008030195, _downCalled[0]);
- Assert.AreEqual(2008020195, _downCalled[1]);
- }
-
- [Test]
- public void MigrateDownWithHoles()
- {
- var migs = new List