How to Alter Blob to Varchar in Laravel Make:Migration - mysql

I need to change a Blob field type to a Varchar(128). The data in the field will fit the target field size, it's text, and shouldn't have a problem with UTF-8.
Sample data, all data is in this format:
{"weight":"0","height":"0","width":"0","length":"0"}
I'm using Laravel Make:migrate to handle the conversion.
How should I write the SQL?
I know how to write a Laravel Migration. I also know how to alter a field. But a Blob isn't a text field nor is a Blob normally converted down to a Varchar. I've done some manual UTF-8 conversion of Blobs in the past and know you can mess up your data if you don't do it right. So my concern here is to not mess up my data with a Laravel Migrate. I don't believe the migrate 'down' method can undo corrupted data.
If my data fits the varchar target size and if the data fits the UTF-8 charset, am I good with a straight forward Alter statement:
DB::query("ALTER TABLE DB1.products CHANGE COLUMN dimensions dimensions varchar(128) DEFAULT NULL;");

You shouldn't use sql for this, just create a migration and use change method
Schema::table('table_name', function ($table) {
$table->string('column_name')->change();
});
https://laravel.com/docs/5.7/migrations#modifying-columns
Considering your comment sql would be
ALTER TABLE tablename MODIFY column_name VARCHAR(128);

Run composer install and then composer update in the console and
drop your table from the database and also delete the migration ,then create a new migration using
php artisan make:migration change_col_datatype --table=table_name
and then make changes as below
Schema::table('your_table_name', function ($table) {
$table->string('your_table_name');
});
public function down()
{
Schema::dropIfExists('tablename');
}

The SQL statment:
\DB::statement('ALTER TABLE products CHANGE COLUMN dimensions dimensions VARCHAR(128) DEFAULT NULL;');
Worked fine.

Related

How to convert/change mysql "->>" syntactic

In my project there is codegen function which produces this type of sql script:
ALTER TABLE `SomeTable`
ADD COLUMN `column_country` JSON GENERATED ALWAYS AS (`col`->>'$[*].country') STORED NOT NULL
As result in database I have following table's DDL
CREATE TABLE `SomeTable`(
`column_country` json GENERATED ALWAYS AS
(json_unquote(json_extract(`col`,'$[*].country'))) STORED NOT NULL,
)
Some how "->>" was converted to (json_unquote(json_extract(...,'...'))).
I need to wrap part "(json_unquote(json_extract(col,'$[*].country')))" to IFNULL function and to have as result:
CREATE TABLE `SomeTable`(
`column_country` json GENERATED ALWAYS AS
(json_unquote(IFNULL(json_extract(`col`,'$[*].country', "[]")))) STORED NOT NULL,
)
But how can I do it with this "->>" syntactic ? At least where I can write about it?

Laravel5.5: migration string to JSON

How to make a migration in Laravel 5.5 that change the datatype of a String to JSON? My column has image links and I want to change it to JSON to store more links.
I thought this was the best way?
change the string value of the column so it corresponds to JSON datatype
change the datatype of the column to JSON
I'm able to do the first step in mysql by:
UPDATE db.vendor_horses SET image= CONCAT('{"images":["', image, '"]}');
Thanks!
You can easily create a new migration with php artisan make:migration migration_name command.
Use the following to change the datatype
Schema::table('vendor_horses', function (Blueprint $table) {
$table->json('image')->change();
});
The change() method allows you to set nullable, modify data length and types. Read more about change()
this just supported mySql version 8 to up
Schema::table('table_name', function (Blueprint $table) {
$table->json('field_name')->change();
});
First, If you use laravel and change your database table field then you install composer require doctrine/dbal Read more about modifying a column in laravel
Simply create a new migration file from php artisan make:migration migration_name and then open newly created migration file
Schema::table('your_table_name',function(Blueprint $table){
$table->json('image')->change();
//make nullable to image field
$table->json('image')->nullable()->change();
//rename image field to other
$table->renameColumn('old_column_name', 'new_column_name');
})
The change() method allow you to set data length , change your column name, and make nullable

Change mysql content type before query laravel

I have a problem, I had this table (Pkb) :
It's basically a date (but in varchar format, YYYYMMDD), I want to select all the date before today using eloquent laravel 5
$todays = Carbon::today();
$filterdate = Pkb::whereDate('rtglb', '<=', $today)->get();
It works on result if used in controller but not with php artisan tinker (so basically it's not working and thrown an error) :
When I put it in handle function in command console, It's not working too because it's rtglb are in varchar table. (I need to put it in command console to create scheduller)
I have access to database, but I can't access the php code cause this table actually old module and I had to create new module that takes data from this table, calculate it using scheduller..
is there anyway to convert the content of rtglb to date before select it? using eloquent or raw mysql? or are there any solution for me?

Cassandra: Cannot parse <col_Name> as hex bytes: MarshallException

I was trying my first 'Helloworld' application in Cassandra. Whenever I try to add any data to my keyspace column family I get this error:
[default#MyKeyspace] set User['ehewitt'] ['fname']='Eben';
org.apache.cassandra.serializers.MarshalException: cannot parse 'fname' as hex bytes
This is despite the fact that I have executed
[default#MyKeyspace] assume Users keys as utf8;
So the above command does not seem to have any effect at all. How do I solve this issue?
Cassandra is assuming the columns as bytes.
Check with
help assume;
assume User keys as ascii;
assume User comparator as ascii;
assume User validator as ascii;
assume User sub_comparator as ascii;
set User['ehewitt']['fname']='Eben';
Value inserted.
Elapsed time: 216 msec(s).
I had similar problem, but the cli told me that the value is what cannot be parsed.
set game_outcome['1']['userId']='123asdasd';
cannot parse '123asdasd' as hex bytes
so I tried to use utf8 function like this :
set game_outcome['1']['userId']=utf8('123asdasd');
cannot parse '123asdasd' as hex bytes
Try
set User['ehewitt'] [utf8('fname')]='Eben'
I tried to use set some assumption like this
assume validator keys as utf8;
validator not found in current keyspace.
But as you can see it did not work as well !
I hope this answer helps.
Starting the CLI
You can start the CLI using the bin/cassandra-cli script in your Cassandra installation (bin\cassandra-cli.bat on windows). If you are evaluating a local cassandra node then be sure that it has been correctly configured and successfully started before starting the CLI.
If successful you will see output similar to this:
Welcome to cassandra CLI.
Type 'help;' or '?' for help. Type 'quit;' or 'exit;' to quit.
You must then specify a system to connect to:
connect localhost/9160;
Creating a Keyspace
We first create a keyspace to run our examples in.
create keyspace Twissandra;
Selecting the keyspace to user
We must then select our example keyspace as our new context before we can run any queries.
use Twissandra;
To Create A Column
We can then create a column to play with.
create column family User with comparator = UTF8Type;
For the later examples to work you must also update the schema using the following command. This will set the return type for the first and last name to make them human readable. It will also add and index for the age field so that you filter your gets using the Users name field.
update column family User with
column_metadata =
[
{column_name: first, validation_class: UTF8Type},
{column_name: last, validation_class: UTF8Type},
{column_name: age, validation_class: UTF8Type, index_type: KEYS}
];
To Add Data
To add data we want to into our new column we must first specify our default key type otherwise we would have to specify it for each key using the format [utf8('keyname')] this is probably advisable if you have mixed key types but makes simple cases harder to read.
So we run the command below, which will last the length of you cli session. On quitting and restarting we must run it again.
assume User keys as utf8;
and then we add our data.
set User['jsmith']['first'] = 'John';
set User['jsmith']['last'] = 'Smith';
set User['jsmith']['age'] = '38';
If you get the error like this cannot parse 'John' as hex bytes, then it likely you either haven't set your default key type or you haven't updated your schema as in the create column example.
To Update Data
If we need to update a value we simply set it again.
set User['jsmith']['first'] = 'Jack';
To Get Data
Now let's read back the jsmith row to see what it contains:
get User['jsmith'];
The get command uses API#get_slice
To Query Data
get User where age = '12';

CakePHP can't find table after creating a table

I create a table directly by a query. I only want to Import some data. Therefor i execute a query which is built dynamicly and i try execute this query in a Component-class. (I use a random existing model to execute this query is there a better why?)
$query= "CREATE TABLE IF NOT EXISTS testerdbs (
'Ü1' varchar(6) COLLATE utf8_swedish_ci DEFAULT NULL,
'Ü2' varchar(6) COLLATE utf8_swedish_ci DEFAULT NULL,
'Ü3' int(3) DEFAULT NULL,
'Ü4' varchar(6) COLLATE utf8_swedish_ci DEFAULT NULL,
'Ü5' date DEFAULT NULL
)"
$data = ClassRegistry::init('import_files');
$data->query($query);
This works fine.
In the same request i want to access the created table in the controller.
App::import('Model', "testerdb");
//$this->loadModel("testerdb");
$newTable = ClassRegistry::init("testerdb");
echo '<pre>', print_r($newTable->getColumnTypes()), '</pre>';
If I try to execute this in same request i always get the error:
Error: Table testerdbs for model testerdb was not found in datasource default.
If I do exactly the same request again, everything works fine...
I google about an hour and it seemed that cake cache the model. If I execute this request again cake cache again all the tables and than cake find my new table. So I hoped to load or import the created Table in the same request, but i don't work.
Is there another way to load the table? Where is my mistake?
Thanks for help!
This might be a bit stale, but I just spent the last week trying to work around the problem and maybe this will help someone.
The root problem is that the cache of table names is initialized before you created the temporary table, so the 'setSource' function returns an error that the temporary table does not exist.
The solution is to overrid the 'setSource' function for the Model that you are creating for 'testerdb' and remove the check on table existence (i.e. everything within the test:
if (method_exists($db, 'listSources'))' )
Your model definition should look something like this:
App::uses('AppModel', 'Model');
class testerdb extends AppModel {
public function setSource($tableName) {
$this->setDataSource($this->useDbConfig);
$db = ConnectionManager::getDataSource($this->useDbConfig);
$this->table = $this->useTable = $tableName;
$this->tableToModel[$this->table] = $this->alias;
$this->schema();
}
}
Many thanks to whomever posted the link below. This has worked with my CakePHP 2.0 instance.
http://web2.0goodies.com/blog/uncategorized/mysql-temporary-tables-and-cakephp-1-3/
Why would you only want to have a temporary table? I would just temporarily store whatever data you are importing in an in-memory model or data-structure.
If the table is not temporary, then just create it statically before you run your program.