EF6 MySQL changing all table prefixes - mysql

I have a mysql db on a server where I've bought some space.
Now I want to add a new mvc application to my website to try out some stuff, without buggering up my existing application.
That puts me in a bit of a problem though as I only have one database available, I could just buy a new one, but I don't want to have to buy a new one every time I want to try stuff out.
So I figured, why not just pre-fix all my tables with some unique value for that application, that way I can keep the stored data separate while still using the same db.
That took me on a journey across countless articles both here on stackoverflow and other places on the web.
After about a day I stumbled upon this nugget
<!-- language: c# -->
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Types().Configure(entity => entity.ToTable("pf_" + entity.ClrType.Name));
base.OnModelCreating(modelBuilder);
}
Which does exactly what I want, as long as you either use a mssql database, or you drop your mysql database and create a new one.
However, the database I've been given is not an mssql database, and dropping it is not an option.
When, with an existing mysql db, I try to run
update-database
I get the following error
Can't find file: '.\mytestdb\dbo#002etestitems.frm' (errno: 2 - No such file or directory)
where "mytestdb" is my local db that I'm testing on, "testitems" is the current/previous tablename, .frm is ofcourse the db format, and I have no idea what this "dbo#002e" is, I tried googling it to no avail.
My stack trace can be found here.
http://pastebin.com/yF2dGkm6
Has anyone been in a similar situation, or has ideas as to how I can make it work? =)

dbo#002e stands for "dbo.", looking at your migration file you should discover rows like this one:
RenameTable(name: "dbo.Table", newName: "pf_Table");
Despite everything it's ok with CreateTable with table names prefixed by "dbo.", RenameTable origin the whole "dbo.Name" to be looked for and so the error comes.
My suggestion is to remove manually the "dbo." on the RenameTable's "name:" parameter.
EDIT:
After fixed the problem editing the migration file the best solution is to add this to the Configuration constructor:
public Configuration()
{
AutomaticMigrationsEnabled = false;
....
SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
CodeGenerator = new MySql.Data.Entity.MySqlMigrationCodeGenerator();
....
}
It should work since the .Net Connector version 6.7.4 on.

Related

Prestashop 1.4 - How to execute an initial MySQL query on every request

Kind of old version of Prestashop, I know, but I need to execute an initial MySQL query on every request.
Where do I need to put the logic to be always executed?
Sort of initialization point the application always executes, no matter what URL is requested.
Thanks in advance.
Finally found the solution (and smartly, I think).
And I also think this approach could be applicable to other versions of Prestashop (1.5, 1.6, 1.7...).
In classes/MySQL.php file, within the connect function, I add my query just before returning $this->_link:
public function connect()
{
if (!defined('_PS_DEBUG_SQL_'))
define('_PS_DEBUG_SQL_', false);
if ($this->_link = mysql_connect($this->_server, $this->_user, $this->_password))
{
if (!$this->set_db($this->_database))
die('The database selection cannot be made.');
}
else
die('Link to database cannot be established.');
/* UTF-8 support */
if (!mysql_query('SET NAMES \'utf8\'', $this->_link))
die(Tools::displayError('PrestaShop Fatal error: no utf-8 support. Please check your server configuration.'));
// removed SET GLOBAL SQL_MODE : we can't do that (see PSCFI-1548)
/** MY QUERY IS INSERTED HERE, USING $this->_link BY THE WAY **/
mysql_query('...', $this->_link);
return $this->_link;
}
In this way, 2 advantages arise:
I do not have to maintain a copy of database credentials other than Prestashop's
The query is executed in every request, both shop frontoffice and backoffice user interfaces.
I hope this can help anyone.

Creating classes in pimcore

I'm new to the whole pimcore thing. I am trying to play around and create classes. The issue is, I am not able to create more than 1 class, and in the database it is nameless, so when I try to create another class, it also tries to store it in the database with no name, which ends up showing an SQL error saying that there is a duplicate entry. Any ideas what the reason behind this could be?
I installed pimcore on an nginx server, I am trying to create classes by choosing Settings->Objects->Classes and then "Add Class", creating the first class was ok, I entered a name for the class and it was successfully added, however the name field in the corresponding database entry is empty, as in empty string ' '. So, when I try to add another class and pimcore attempts to store it in the table "classes", it returns an error saying that it would be a duplicate entry since they both are nameless, i.e. the name entered isn't added. The following error is what I managed to find using developer tools, could be helpful.
[WARN] Unable to parse the JSON returned by the server
minified_javascript_core_f5757da….js?_dc=3708:5684 Error: You're trying to decode an invalid JSON String:
Fatal error: Call to a member function hasChilds() on null in /var/www/html/pimproject/pimcore/modules/admin/controllers/DocumentController.php on line 59
at new Ext.Error (http://192.10.0.0/pimcore/static6/js/lib/ext/ext-all.js?_dc=3708:22:27054)
at Function.Ext.apply.raise (http://192.10.0.10/pimcore/static6/js/lib/ext/ext-all.js?_dc=3708:22:27447)
at Object.Ext.raise (http://192.10.0.10/pimcore/static6/js/lib/ext/ext-all.js?_dc=3708:22:27594)
at Object.Ext.JSON.me.decode (http://192.10.0.10/pimcore/static6/js/lib/ext/ext-all.js?_dc=3708:22:385102)
at Ext.define.onProxyLoad (http://192.10.0.10/website/var/tmp/minified_javascript_core_f5757da9fa29d5bf13e6aa5058eff9f7.js?_dc=3708:5641:28)
at Ext.cmd.derive.triggerCallbacks (http://192.10.0.10/pimcore/static6/js/lib/ext/ext-all.js?_dc=3708:22:594533)
at Ext.cmd.derive.setCompleted (http://192.10.0.10/pimcore/static6/js/lib/ext/ext-all.js?_dc=3708:22:594231)
at Ext.cmd.derive.setException (http://192.10.0.10/pimcore/static6/js/lib/ext/ext-all.js?_dc=3708:22:594444)
at Ext.cmd.derive.process (http://192.10.0.10/pimcore/static6/js/lib/ext/ext-all.js?_dc=3708:22:593638)
at Ext.cmd.derive.processResponse (http://192.10.0.10/pimcore/static6/js/lib/ext/ext-all.js?_dc=3708:22:648303)
Just reinstall Pimcore.
It can be some composer or submodules error.
I strongly recommend for the first installation to run Demo project https://github.com/pimcore/demo not Skeleton, especially if you are using Docker. Later, when you will get the feeling of Pimcore, feel free to install Skeleton or any other project.
Pimcore is stable working for years. If you had some problems before -- nowadays, it is stable.

EF and Code First Migrations with MySQL - dbo.tablename does not exist

I have set up entity framework to use MySQL and created a migration.
When I run update-database I get error "table dbname.dbo.tablename' does not exist. Running in -Verbose mode I see the statement that causes the error :
alter table `dbo.Comments` drop foreign key `FK_dbo.Comments_dbo.Comments_Comment_ID`
When I run the query direct in MySQL workbench is throws the same error.
The problem seems to be the dbo. prefix in the migration set. Anything in the form dbo.tablename won't run saying that table does not exist. E.g. select * from dbo.tablename fails but select * from tablename works. The database was generated by Entity Framework and the code first migrations were generated by EF too.
However the migrations generate everything with the dbo. prefix, which does not work.
Does anyone have a solution to this?
I was having this problem just today as well; found my answer here:
MySqlMigrationCodeGenerator
You have to set:
CodeGenerator = new MySqlMigrationCodeGenerator();
In your context's configuration class. This will get rid of the schema gibberish for MySQL. My Configuration class looks like this:
internal sealed class Configuration : DbMigrationsConfiguration<YourContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
SetSqlGenerator("MySql.Data.MySqlClient", new MySqlMigrationSqlGenerator());
SetHistoryContextFactory("MySql.Data.MySqlClient", (conn, schema) => new MySqlHistoryContext(conn, schema));
CodeGenerator = new MySqlMigrationCodeGenerator();
}
}
I have this same issue and I applied the solution posted by Sorio and It generated a lot of problems.
CodeGenerator = new MySqlMigrationCodeGenerator();
This code line can change all the sql that you generate, for example in my case in the sql code to apply to the database all the foreign key constraints disappear.
I am still without a solution because for me this is not acceptable and I recommend you to check the sql generate with the command before use this solution:
update-database -script

EntityFramework on MySql changing connection string does not change results data

I'm working with EntityFramework 5.0 and MySql. I have generated model from database, and my application now have to connect on multiple database with same structred data.
So i have to dynamic change connection string based on some info.
I try to change database name even from config section of connection string, and with EntityConnectionStringBuilder, but i had the same result: my new connection is stored correctly, but data returned are of the first database.
From WebConfig:
add name="dbIncassiEntities" connectionString="metadata=res:///DAL.Modelincassi.csdl|res:///DAL.Modelincassi.ssdl|res://*/DAL.Modelincassi.msl;provider=Devart.Data.MySql;provider connection string="user id=root ... database=dbname2"" providerName="System.Data.EntityClient" />
From code:
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = providerName;
entityBuilder.ProviderConnectionString = "user id=...database=dbname2";
entityBuilder.Metadata = #"res://*/DAL.Modelincassi.csdl|res://*/DAL.Modelincassi.ssdl|res://*/DAL.Modelincassi.msl";
var context = new dbIncassiEntities(entityBuilder.ToString());
My constructor:
public dbIncassiEntities(string conn)
: base(conn)
{
}
What am i missing?
UPDATE
I can see that calling a query directly from SqlQuery, results returned are correct,
while using the generated entities i retrieve wrong data.
var test = context.Database.SqlQuery<string>(
"SELECT cognomenome FROM addetto limit 0,1").ToList();
But calling..
var oAddetto = from c in context.addettoes select c;
So my problem is only on the model itsself, and manually changing the generated schema
<EntitySet Name="addetto" EntityType="dbIncassiModel.Store.addetto" store:Type="Tables" Schema="dbname2" />
..i'll get the right information.
My question now is: how can i change in code these informations??
Any help is really appreciated!!
Thanks, David
Ok, i've found a workaround for now.
I simply clear the shema name on the designer, and now i can call the generated entities succesfully. Hope this can help anyone else.
David
While I could not remove the Schema in the designer, I removed it directly in the .edmx file. Do a full text search for Schema="YourSchema" in an XML editor of your choice and remove the entries. After that, changing the connection string is enough.
Downside is, the Visual Studio designer and mapping explorer won't work properly anymore.
This seems to be more of a dotConnect issue rather than MySQL, since the problem also exists for the Oracle adapter:
http://forums.devart.com/viewtopic.php?t=17427

Best way to integration-test a spring mysql application?

I want to write integration tests for my application, which is using a MySQL db via jdbc.
(FYI: The application has a user database and a wiki so far, so nothing sophisticated really)
I came across a lot of posts, mostly talking about HSQLDB or H2, as well as some exotics or discontinued (like mxj)
Sadly, most of these threads were made years ago and so many things have changed since then.
I'm looking for people with recent experience (or even better having a similiar setup like I got - that means spring and the need to run these tests both locally and on jenkins)!
I understand that the best way to find the answer is to try it myself and see what works best, but maybe someone has recent experience and is willing to share :)
Technologies used:
MySQL
Spring
TestNG
Jenkins
I'd be very thankful if you can share your experience and advices with me.
Try Maven plugin created exactly for this purpose: jcabi-mysql-maven-plugin. It starts a local MySQL server on pre-integration-test phase and shuts it down on post-integration-test.
So I decided to use h2, which gave me some problems with importing MySQL dumbs. The answer is here: Running h2 in MODE=MySQL doesn't support MySQL dumps
Basically, you have to remove quotes around table-names (they seem to work fine for fields nevertheless). You can use back-ticks ( ` ) or not use any ticks/quotes at all.
Another thing that caused a problem was a "AUTO_INCREMENT = 1" at the end of the table definition. Since h2 uses 1 as default after the start, this command is not needed anyways.
Here's an example how to setup the embedded database:
public class InMemoryTest {
#org.testng.annotations.Test // ofc this can be JUnit #Test as well
public void test() throws Exception {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.
getConnection("jdbc:h2:mem:test;MODE=MySQL;IGNORECASE=TRUE;INIT=RUNSCRIPT FROM 'src/test/resources/test.sql'");
Statement stat = conn.createStatement();
stat.execute("INSERT INTO `usr_avatar` (\"usr_avatar_user_id\") VALUES (1)");
}
}
and the test.sql would be:
DROP TABLE IF EXISTS usr_avatar;
CREATE TABLE IF NOT EXISTS usr_avatar (
"usr_avatar_id" int(11) NOT NULL AUTO_INCREMENT,
"usr_avatar_user_id" int(11) NOT NULL
)