How do i deploy a schema correctly with DBIx::Class? - mysql

i'am new to Databases and to DBIx:Class. So please forgive me if this is a total newbie fault.
I just followed a tutorial and then i tried to deploy the schema to my database. According to the tutorial i split the modules up in several files. After i ran createTable.pl 'mysqlshow bla' shows me a empty database.
Database is up and running. Creating a table via the mysql CREATE TABLE statement does work.
Skript file which should create a table according to the schema ../createTable.pl
#!/usr/bin/env perl
use Modern::Perl;
use MyDatabase::Main;
my ($database, $user) = ('bla', 'flo');
my $schema = MyDatabase::Main->connect("dbi:mysql:dbname=$database", "$user");
$schema->deploy( { auto_drop_tables => 1 } );
Main.pm for loading the namespaces ../MyDatabase/Main.pm
package MyDatabase::Main;
use base qw/ DBIx::Class::Schema /;
__PACKAGE__->load_namespaces();
1;
Schema file for the table ../MyDatabase/Result/Album.pm
package MyDatabase::Main::Result::Album;
use base qw/ DBIx::Class::Core /;
__PACKAGE__->load_components(qw/ Ordered /);
__PACKAGE__->position_column('rank');
__PACKAGE__->table('album');
__PACKAGE__->add_columns(albumid =>
{ accessor => 'album',
data_type => 'integer',
size => 16,
is_nullable => 0,
is_auto_increment => 1,
},
artist =>
{ data_type => 'integer',
size => 16,
is_nullable => 0,
},
title =>
{ data_type => 'varchar',
size => 256,
is_nullable => 0,
},
rank =>
{ data_type => 'integer',
size => 16,
is_nullable => 0,
default_value => 0,
}
);
__PACKAGE__->set_primary_key('albumid');
1;
I already spent some hours on finding help through google but there isn't much related to the deploy() method.
Can anyone explain me what my mistake is?
Thank you

You can find the documentation for all CPAN Perl modules on metacpan.org (newer, full-text indexed) and search.cpan.org.
Read the docs for DBI, you'll find an environment variable called DBI_TRACE that when set will print every SQL statement to STDOUT.
DBIx::Class has a similar called DBIC_TRACE.
The first one should help you to see what the deploy method is doing.
Is no password required for connecting to your database?

Ok today i played again with perl and database stuff and i found out what the mistake was.
First of all i started with DBI_TRACE and DBIC_TRACE, it produced a lot of messages but nothing i could handle, for me it seemed like nothing gave me a hint on the problem.
Then i searched google for a while about this problem and for more examples of the deploy method. At some point i noticed that my folder structure is wrong.
The Schema file for the table should be placed in
../MyDatabase/Main/Result/Album.pm
instead of being placed in
../MyDatabase/Result/Album.pm
After moving the Schema file to the correct folder everything worked well.
Shame on me for this mistake :( But thank you for your help

Related

CakePHP 3: Best Practice for Temporary SQL Tables

Dear CakePHP 3 developers,
I'd like to use SQL's Temporary Tables in a CakePHP 3.4.13 project for a single run through a script. Going through Cake's documentation, there seems no direct way to tell CakePHP my desire. How would I best go about it, then?
I've prepared a Table in src/Model/Table/TempItemsTable.php:
namespace App\Model\Table;
use Cake\ORM\Table;
class TempItemsTable extends Table
{
public $fields = [
'id' => ['type' => 'integer'],
'con' => ['type' => 'string', 'length' => 255, 'null' => false],
'_constraints' => [
'primary' => ['type' => 'primary', 'columns' => ['id']]
]
];
public function initialize(array $config)
{
// $this->setTable(null);
}
}
The idea to use $fields to tell CakePHP the desired table schema comes from a possibly unrelated documentation for Test Fixtures.
But how do I tell CakePHP not to look for an actual table in the database?
The uncommented line $this->setTable(null); was my poor attempt at that, which is supposedly similiar to the right way in earlier versions of CakePHP, but according to version 3.x documentation, setTable() doesn't accept null, while table() does, but it's deprecated as of 3.4 and also didn't change anything.
Finally, of course, I get this exception as soon as I try to access this "table" in a controller via $temp = TableRegistry::get('TempItems');:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mydatabase.temp_items' doesn't exist
Help, I'm stuck. :(
There's no need to tell it to not look for the table, actually that's the opposite of what you want to do, given that you eventually want to access it.
The table class should basically be configured as usual, and you should create the temporary database table before the application causes it to be accessed. You can either write the raw table creation SQL manually, or generate it from a \Cake\Database\Schema\TableSchema instance, which supports temporary tables.
You can either explicitly create the schema object:
$schema = new \Cake\Database\Schema\TableSchema('temp_items');
$schema
->addColumn('id', ['type' => 'integer'])
->addColumn('con', ['type' => 'string', 'length' => 255, 'null' => false])
->addConstraint('primary', ['type' => 'primary', 'columns' => ['id']])
->setTemporary(true);
$TableObject->setSchema($schema);
or let the table object generate it, using your fields definition array:
$TableObject->setSchema($TableObject->fields);
$schema = $TableObject->getSchema()->setTemporary(true);
You can then generate the table creation SQL from the schema object and run it against the database:
$connection = $TableObject->getConnection();
$queries = $schema->createSql($connection);
$connection->transactional(
function (\Cake\Database\Connection $connection) use ($queries) {
foreach ($queries as $query) {
$stmt = $connection->execute($query);
$stmt->closeCursor();
}
}
);
$queries would be an array of SQL commands required to create the table, something along the lines of:
[
'CREATE TEMPORARY TABLE `temp_items` (
`id` INTEGER AUTO_INCREMENT,
`con` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
)'
]
Note that if you do not assign the schema to the table object, you could run into caching problems, as the cached schema wouldn't match anymore when you change the table definition and do not clear the cache.
See also
Cookbook > Database Access & ORM > Schema System
Cookbook > Database Access & ORM > Database Basics

Newly added field to table is completely ignored

I am completely new to Drupal. I inherited a very ugly and incorrect code, unfortunately. In fact I would like to implement a proper login-with-facebook feature, which was totally mis-implemented. It tried to identify users by their email address, however, for some reason, upon login with Facebook, users logged in with the wrong user. I would like to identify the user based on Facebook ID, however, there was no column for that purpose in the database.
As a result, I have implemented a small script, which added a facebook_id and a facebook_token to the table representing the users. However, these new columns are not seen by the drupal_get_schema function in bootstrap.
If I do this:
$schema = drupal_get_schema("users");
echo var_dump($schema["fields"]);
It shows the fields except the two newly created fields. This way a SchemaCache object is initialized. I assumed that the schema might be cached. So I tried something different:
$schema = drupal_get_schema("users", true);
echo var_dump($schema["fields"]);
to make sure that drupal_get_complete_schema(true) will be called. However, the fields are not seen this way either. Is there a way I can tell Drupal to acknowledge the existence of the two newly created columns? If not: what should I do? Should I remove the two columns from the database table and use db_add_field("users", "facebook_id") and db_add_field("users", "facebook_token") respectively? If so, where should I call these?
Sorry if the question is too simple or I am misunderstanding these technologies, but I have tried to solve this for hours and I am at a loss, because this is my first drupal/bootstrap project and the source-code using these does not help me at all.
EDIT:
Since, at the time of this writing I have not received any answers apart from a tool recommendation which did not address my question, I have continued my research in the area. I removed the columns from the database to create them in a Drupal way. I have implemented this function in user.module:
function user_schema_alter() {
db_add_field('users', 'facebook_id', array(
'type' => 'varchar', //was initially a bigint, but Drupal generated a query which always crashed
'length' => 20,
'not null' => TRUE,
'default' => ".", //was initially -1, but Drupal generated a query which always crashed
));
db_add_field('users', 'facebook_token', array(
'type' => 'varchar',
'length' => 300,
'not null' => TRUE,
'default' => 'unavailable',
));
}
and I invoke it from altconnect.module, like this:
$schema = drupal_get_schema("users");
if (!isset($schema["fields"]["facebook_id"])) {
user_schema_alter();
}
It creates the columns, but later the existence of those columns will not be known about and subsequently an error will be thrown as the code will try to re-create them. Besides the fact that I had lost a lot of time until I realized that Drupal is unable to support bigint fields having -1 as their default value I had to conclude that with this solution I am exactly in the same situation as I were initially, with the difference that with this Drupal solution I will always get an exception if the columns already exist, because the schema will not be aware of them and subsequently, the code will always enter that if.
I fail to understand why is this so difficult in Drupal and I totally fail to understand why trying
db_add_field('users', 'facebook_id', array(
'type' => 'bigint',
'length' => 20,
'not null' => TRUE,
'default' => -1,
));
throws an exception due to syntax error. Maybe I should just leave this project and tell anyone who considers using Drupal to reconsider :)
I was able to find out what the answer is, at least for Drupal 6.
In user.install we need to do the following:
//...
function user_schema() {
//...
$schema['users'] = array(
//...
'fields' => array(
//...
'facebook_id' => array(
'type' => 'varchar',
'length' => 20,
'not null' => TRUE,
'default' => ".",
),
'facebook_token' => array(
'type' => 'varchar',
'length' => 300,
'not null' => TRUE,
'default' => 'unavailable',
),
//...
),
//...
}
//...
/**
* Adds two fields (the number is some kind of version number, should be the biggest so far for the module)
*/
function user_update_7919() {
db_add_field('users', 'facebook_id', array(
'type' => 'varchar',
'length' => 20,
'not null' => TRUE,
'default' => ".",
));
db_add_field('users', 'facebook_token', array(
'type' => 'varchar',
'length' => 300,
'not null' => TRUE,
'default' => 'unavailable',
));
}
When this is done, log in with the admin user and go to http://example.com/update.php
There you will see the thing to be updated. Run it. If you wonder why do we have to do all this, why don't we run some scripts directly, then the answer is that this is how Drupal operates. It simplifies your life by making it complicated, but do not worry, while you wait for update.php to do the updates which would take less than a second if it was your script, you can ponder about the meaning of life, quantum-mechanics or you can try to find out the reason this is so over-complicated in Drupal and you can go out for a walk. When you focus again, if you are lucky, update.php has completed its job and the two columns should be in the database.

Yii2 load all models automatically

I don't like to declare every model as
use app\models\Country;
Really it bothers me a lot. I like the approach used in Yii 1.15 when you could load all models using import instruction in config like:
'import' => array(
'application.models.*',
)
Yes, I know it's not good for performance. But I have not more than 50 models and I care much more about my own performance rather than of performance of machine.
I had no luck in figuring out how to do it Yii2.
All I found out is that it should be done via bootstrap option in main config file.
I tried the following:
$config = [
'language' => 'en',
'id' => 'basicUniqueApp',
'basePath' => dirname(__DIR__),
'bootstrap' => [
'log',
'app\models\*'
],
But it's not proper syntax.
Any ideas?
You're trying to break down PHP namespace. That's not a good idea.
If you don't want declare on top model, You can call directly without declare like this:
$country = new \app\models\Country();

Can I create an initial CodeIgniter db migration from .sql?

I have a CodeIgniter application and I just learned about migrations. It sounds very useful and I would like to start using it. However I already have a rather complex database setup. Can someone suggest a reasonable way to create a reliable initial migration from my MYSQL .sql schema file?
It seems excessive to manually recreate the entire db with dbforge, but perhaps that's what I ought to do.
Bit late reply, but I hacked a quick library that should generate the base migration file for you from your current DB. Its still beta, but works on my systems 40 tables+
https://github.com/liaan/codeigniter_migration_base_generation
L:
Visit https://github.com/fastworkx/ci_migrations_generator
You'll get something like this applications/migration/001_create_base.php.
public function up() {
## Create Table sis_customer
$this->dbforge->add_field(array(
'id' => array(
'type' => 'VARCHAR',
'constraint' => 40,
'null' => FALSE,
),
'ip_address' => array(
'type' => 'VARCHAR',
'constraint' => 45,
'null' => FALSE,
),
'timestamp' => array(
'type' => 'INT',
'unsigned' => TRUE,
'null' => FALSE,
'default' => '0',
),
'data' => array(
'type' => 'BLOB',
'null' => FALSE,
),
'`datetime_reg` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ',
));
$this->dbforge->create_table("sessions", TRUE);
$this->db->query('ALTER TABLE `sessions` ENGINE = InnoDB');
));
public function down() {
### Drop table sessions ##
$this->dbforge->drop_table("sessions", TRUE);
}
I was messing around with SQL files manually and then I discovered Jamie Rumbelow's schema library. It makes schema operation a little bit easier to manage then DBForge but still requires manual entry.
https://github.com/jamierumbelow/codeigniter-schema
Someone came up with a mashup of his base model and schema library and it makes prototyping much faster
https://github.com/williamknauss/schema_base_model_magic
this allows you to automate the CRUD model operations & schema

Drupal 7 Mysql query (Insert)

I'm new to Drupal.
So I was wondering if you can help me.
I saw a lot of documents regarding the Drupal API mysql thing-y and It's been bugging me that I have to study once more to finish my work done.
And here's the documentation that I'm applying to my problem
Regarding my problem about the INSERT function, I have this table entitled embed
and here is my data from the table embed.
Then on my basic page I'm trying to insert a query.
$id = db_insert("embed")
->fields(array(
'uid' => 1,
'fbp_id' => 22222,
'prom_stat' => 3333,
'status' => 1,
))
->execute();
Instead of inserting a data to the table, it outputs an error like this.
Anyone knows the solution for this stuff? I'm really confused about this right now.
As #steve has suggested in the comment, the issue is not on drupal side but on MySql side. You need to modify your insert code to
$id = db_insert("embed")
->fields(array(
'uid' => 1,
'fbp_id' => 22222,
'prom_stat' => 3333,
'status' => 1,
'prom_id' => 0,
'sweep_stat' => 0,
'sweep_id' => 0,
'comp_id' => 0,
'comp_stat' => 0,
'polls_stat' => 0,
'polls_id' => 0
))
->execute();
Since i can see that your MySql table already contains value, i assume the earlier inserts where done by explicitly providing all values, instead of relying on default values for the field in MySql configuration.
Whenever you have a PDOException you should read it carefully for clues. These kind of errors are really very verbal and gives lots of pointers to resolve the issues. For example in your case,
'prom_id' doesn't have a default value
explains a lot.