I have a migration in my laravel project where I rename fields. This migration works perfectly fine on mysql and most database drivers I've tested (also my local sqlite), for any reason the github ci runner seems to have a problem with the syntax, I believe either caused by an version mismatch or because laravel generates a faulty sql statement. This is my migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('user_weights', function (Blueprint $table) {
$table->renameColumn('weight', 'weight_raw');
});
Schema::table('user_heights', function (Blueprint $table) {
$table->renameColumn('height', 'height_raw');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('user_weights', function (Blueprint $table) {
$table->renameColumn('weight_raw', 'weight');
});
Schema::table('user_heights', function (Blueprint $table) {
$table->renameColumn('height_raw', 'height');
});
}
};
My github workflow looks like this:
on:
push:
branches:
- master
- feature/*
- hotfix/*
pull_request:
branches:
- master
name: CI
jobs:
phpunit:
runs-on: ubuntu-latest
container:
image: kirschbaumdevelopment/laravel-test-runner:8.1
steps:
- uses: actions/checkout#v1
with:
fetch-depth: 1
- name: Install composer dependencies
run: |
composer config "http-basic.nova.laravel.com" "${{ secrets.NOVA_USERNAME }}" "${{ secrets.NOVA_LICENSE }}"
composer install --no-scripts
- name: Prepare .env
run: cp .env.testing .env
- name: Generate key
run: php artisan key:generate
- name: Directory Permissions
run: chmod -R 777 storage bootstrap/cache
- name: Mark app folder as safe directory
run: git config --global --add safe.directory /__w/fitness-backend-neu/fitness-backend-neu
- name: Create Database
run: |
mkdir -p database
touch database/database.sqlite
php artisan migrate
- name: Run Testsuite
run: vendor/bin/phpunit tests/
- name: Run Pint
run: vendor/bin/pint --test
The workflow crashes in the database migration with the following error:
In Connection.php line 759:
SQLSTATE[HY000]: General error: 1 near "0": syntax error (SQL: CREATE TABLE
user_weights (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, user_id VARCH
AR(255) NOT NULL COLLATE BINARY, weight_raw DOUBLE PRECISION NOT NULL, date
DATE NOT NULL, created_at DATETIME DEFAULT NULL, updated_at DATETIME DEFAU
LT NULL, CONSTRAINT 0 FOREIGN KEY (user_id) REFERENCES users (id) ON UPDATE
NO ACTION ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE))
In Connection.php line 538:
SQLSTATE[HY000]: General error: 1 near "0": syntax error
Since the error occurred with the "user_id" relation, I already tried to remove the relation before renaming and recreating the relation right after the rename process. Since sqlite doesn't support removing foreign key constraints, this didn't work.
I also tried reproducing this error using act. Act is a local ci runner which also interprets the GitHub workflow file. With the exact same setup ran by act, I still wasn't able to reproduce this error. Everything is working fine (Act, PHPUnit, Migration on local environment, Migration on production environment) except GitHub Actions.
I just saw, that the exact same migration ran through GitHub action previously and didn't fail. It just started failing after some other commits.
I found a workaround, since laravel seems to generate a faulty sql statement in this case. I added the following code into my migration to catch the sql statement on sqlite connection and run a "sqlite only" query.
if (config('database.default') === 'sqlite') {
DB::statement('ALTER TABLE user_weights RENAME COLUMN weight TO weight_raw;');
DB::statement('ALTER TABLE user_heights RENAME COLUMN height TO height_raw;');
return;
}
I did the same for the reverse migration.
Related
So I'm setting up a Symfony 5 project and running the following commands to generate the database from entity annotations like this:
php bin/console doctrine:schema:validate
php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate
But it's not working as expected, and instead I'm just getting this error:
**[ERROR]** The version "latest" couldn't be reached, there are no registered migrations.
The diff command correctly generates the migration file containing the up() and down() functions however when I subsequently run the migrate command to generate the database it fails with the above error.
I also notice the file /config/packages/doctrine_migrations.yml has changed recently to this:
doctrine_migrations:
migrations_paths:
'App\Migrations': '%kernel.project_dir%/src/Migrations'
However it appears doctrine is looking outside this path for the migrations in the following path:
'%kernel.project_dir%/migrations'
How do you resolve the above error so that the migrate command works as expected and generates the database tables from the generated migration file?
php bin/console debug:config doctrine_migrations
Current configuration for extension with alias "doctrine_migrations"
================================================================= ===
doctrine_migrations:
migrations_paths:
App\Migrations: /var/www/src/Migrations
services: { }
factories: { }
storage:
table_storage:
table_name: null
version_column_name: null
version_column_length: null
executed_at_column_name: null
execution_time_column_name: null
migrations: { }
connection: null
em: null
all_or_nothing: false
check_database_platform: true
custom_template: null
organize_migrations: false
Check the namespace of your migration scripts and the config of the migration bundle. After moving the directory from src/migrations to migrations you have to change the namespace of the files to DoctrineMigrations and change the storage table name to the one, which exists (otherwise the new default migration table name is doctrine_migration_versions).
Here is my proposal:
some migration file in /migrations
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
// ...
Config:
doctrine_migrations:
migrations_paths:
# namespace is arbitrary but should be different from App\Migrations
# as migrations classes should NOT be autoloaded
'DoctrineMigrations': '%kernel.project_dir%/migrations'
storage:
# Default (SQL table) metadata storage configuration
table_storage:
table_name: 'migration_versions'
this helps me to setup the project from scratch with Symfony5 and be backwards compatible with the current running production system.
I think you need to run the command "php bin/console make:migration" before "php bin/console make:migration:migrate"
I hope this is helpful.
I created migration on my Laravel project using command php artisan make:migration migration_name and php artisan make:model ModelName -mcr.
When I run php artisan migrate the output is nothing to migrate.
I check my database, there is only migration table which has no row, even user table that comes from Laravel does not created.
This issue occurs on my laptop and PC
This is the environment that I use to run Laravel using XAMPP
Laravel 7.24 and Laravel 5.8.38
Apache/2.4.39 (Win64)
PHP 7.3.7
MariaDB 10.3.16
Composer 1.10.10
This is the migration code
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
//File name = 2020_08_11_064146_create_category_table.php
//File Path = database/migrations
class CreateCategoryTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('category', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('category');
}
}
I already try these but found no luck :
Run composer dump-autoload
Run php artisan migrate:reset -> nothing to rollback
Run php artisan migrate:fresh-> dropped all table successfully, migration table created successfully ,nothing to migrate
Run php artisan migrate --path="/database/migrations/" -> nothing to migrate
Run php artisan migrate:status -> no migrations found
Run php artisan migrate:install -> Migration table create successfully, but did not solve the problem
TLDR :
What I literally did are :
Download Laravel with composer
Edit .env for connection to database using user root
Create migration using php artisan make:migration create_table_category
Run php artisan migrate
Result = Migration table create successfully, nothing to migrate. Database only have table migrations with no rows
EDIT
Migration can be run if I specify the path completely with file name like php artisan migrate --path="database/migrations/2020_08_11_064146_create_category_table.php"
This answer is not the best solution for such situation, but You can try to define migration path hard in AppServiceProvider:
/**
* Register Custom Migration Paths
*/
$this->loadMigrationsFrom([
database_path().DIRECTORY_SEPARATOR.'migrations'
]);/
I stumbled into this post which described that the problems caused by project path that have character hyphens '-'
My project does not have those characters, but it has 'weird' characters and that is opening and closing square bracket '[ ]', so I thought to change it.
My root project directory path is F:\Indra\Kerja\[1] Personal\Personal profile\web so my migration path is F:\Indra\Kerja\[1] Personal\Personal profile\web\database\migrations
Notice there's folder named [1] Personal, that's the culprit
I renamed my folder to Personal and voila the migration works normally.
I was curious so I try different folder name and I get and interesting result:
[asdasd]Personal -> migration doesn't work for some reason
[1 Personal-> migration work
]1Personal-> migration work
][1 Personal-> migration work
[]Personal -> migration work
So I have to change my folder name
Important Note:
My Operating system is Windows 10 Pro Version 1909 Build 18363.1082
I also tried to give hyphens '-' to my project directory like this F:\Indra\Kerja\my-project-test, and expect that the migration won't work, but the migration works without a problem
i am new to laravel and i ran the auth file to make a register and login etc...
i have 3 migrations file inside the migrations folder: user table reset_password table and user_profile table: the problem is when i ran: php artisan migrate it only create the user table without the 2 other table so i tried these commands:php artisan migrate:rollback, php artisan migrate:refresh, php artisan config:cache php artisan config cache:clear and then i ran :php artisan migrate and only user table was created... any idea? thank you
I am also facing the same issue, while you are running php artisan migrate, the command starts migrating the table and while migrating users table it is throwing some error like:
[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key
was too long; max key length is 767 bytes (SQL: alter table
users add unique users_email_unique(email))
so, only user table is migrated and the process stops with the above error. If this is the issue, then you have to solve it and after that delete the users table and again migrate, every thing will be fine.
To fix the above issue, all you have to do is to edit your app/Providers/AppServiceProvider.php file and add to the boot method a default string length like:
use Illuminate\Support\Facades\Schema;
function boot()
{
Schema::defaultStringLength(191);
}
and again migrate, everything will be fine.
I Found the solution for this
First set this in App/Providers/AppServiceProvider.php
use Illuminate\Support\Facades\Schema;
public function boot()
{
Schema::defaultStringLength(191);
}
Then Migrate Cmd And at Last
php artisan migrate:fresh
after that migration works
I am trying to use Laravel Migration to create SQL tables but it won't let me.
Here is the error:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table
'mytable' already exists
Here is my code:
Schema::create('mytable', function (Blueprint $table) {
$table->increments('id');
$table->foreign('othertable_id')
->references('id')->on('othertable')
->onDelete('cascade');
$table->string('variable');
$table->timestamps();
});
}
{
Schema::drop('mytable');
}
I have also checked if other migrations are called "mytable" but they are not, so I am not sure where this come from.
I tried the following:
First
php artisan migrate:refresh
Which gave me an error
And then I deleted the entire database altogheter and used:
php artisan migrate
And still got the error
In laravel 5.5 and > you can use:
$ php artisan migrate:fresh
// ( not migrate:refresh wich is a different command)
This command first drops all tables and then reruns all migrations
If you have the table in DB and dont want migrate create it, you can ignore it by check Schema::hasTable before create
public function up()
{
if(Schema::hasTable('products')) return; //add this line to migration file
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}
I had neither removed the migration entry nor dropped the table manually from the database
In my case, the solution is open up the tinker from the composer
$ php artisan tinker
>>> Schema::drop('users')
>>> Schema::drop('password_resets')
>>> Schema::drop('orders')
>>> exit
php artisan migrate
Here is the result of the above commands executed
nishanth#localhost:~/Desktop/html/hutch$ php artisan migrate
In Connection.php line 647:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users'
alre ady exists (SQL: create table users (id int unsigned not
null auto_incr ement primary key, name varchar(255) not null,
email varchar(255) not n ull, password varchar(255) not null,
remember_token varchar(100) null, created_at timestamp null,
updated_at timestamp null) default character set utf8mb4
collate utf8mb4_unicode_ci)
In Connection.php line 449:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users'
already exists
nishanth#localhost:~/Desktop/html/hutch$ php artisan migrate:rollback
Nothing to rollback.
nishanth#localhost:~/Desktop/html/hutch$ php artisan tinker
Psy Shell v0.8.17 (PHP 7.1.20-1+ubuntu16.04.1+deb.sury.org+1 — cli) by Justin Hileman
>>> Schema::drop('users')
=> null
>>> Schema::drop('password_resets')
=> null
>>> Schema::drop('orders')
=> null
>>> exit
Exit: Goodbye.
nishanth#localhost:~/Desktop/html/hutch$ php artisan migrate
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrating: 2018_08_18_071213_create_orders_table
Migrated: 2018_08_18_071213_create_orders_table
nishanth#localhost:~/Desktop/html/hutch$
Also define the method down(), if it doesn't exist.
Otherwise, it'll show
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'XYZ.ABC' (SQL: drop table ABC)
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('ABC');
}
Try this,
Add following line :Schema::dropIfExists('mytable'); inside the Up() function at the very beggining exactly before creating schema for the mytable. i.e. before following code. Schema::create('mytable', function (Blueprint $table)
do composer dump, remove the table manually from the database and also remove the migration entry for the the table you want to remove from the migration table and rerun the migration again to see what happens.
The error says that the table mytable does already exist in the DB. You should rollback the migration:
php artisan migrate:rollback
And migrate again:
php artisan migrate
in my case, I need to dump the SQL schema,
run this command:
php artisan schema:dump
then run PHP artisan migrate command again
go to app>Providers>AppServiceProvider.php and copy paste this at the top:
use Illuminate\Support\Facades\Schema;
then go to function inside of it named 'Boot()' and copy paste this one:
Schema::defaultStringLength(191);
now go to your your database and delete your database completely, then go to console:
php artisan cache:clear
php artisan config:cache
then create a new database with same name and go back to consol and write :
php artisan migrate (congrats your database now shows em all)
I'm trying to modify a existing migration. Here is my current migration class:
class CreateLogForUserTable extends Migration
{
public function up()
{
Schema::create('log_for_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('table_name');
$table->string('error_message');
$table->unsignedTinyInteger('error_code');
$table->timestamps();
});
}
public function down()
{
Schema::drop('log_for_user');
}
}
I've executed the php artisan migrate command once. Now I need to add ->nullable() method to the error_message column. So I edited my migration, something like this:
.
.
$table->string('error_message')->nullable();
.
.
But when I execute php artisan migrate again, it says:
Nothing to migrate.
How can I apply the new version of the migration?
You should create a new migration using command:
php artisan make:migration update_error_message_in_log_for_user_table
Then, in that created migration class, add this line, using the change method like this:
class UpdateLogForUserTable extends Migration
{
public function up()
{
Schema::table('log_for_user', function (Blueprint $table) {
$table->string('error_message')->nullable()->change();
});
}
public function down()
{
Schema::table('log_for_user', function (Blueprint $table) {
$table->string('error_message')->change();
});
}
}
To make these changes and run the migration, use the command:
php artisan migrate
and to rollback the changes, use the command:
php artisan migrate:rollback
You may rollback a limited number of migrations by providing the step option to the rollback command. For example, the following command will rollback the last five migrations:
php artisan migrate:rollback --step=5
See more about Modifying columns with Migration
If your app is not in production and you seed your data, the best you can do is to run:
php artisan migrate:refresh --seed
This command will drop all tables and recreate them. Then it will seed the data.
If you will create additional migrations for each change during development, you'll end up with hundreds of migrations classes.
You can use the change method, it allows you to modify some existing column types to a new type or modify the column's attributes.
For example modify a column to be nullable:
Schema::table('log_for_user', function ($table) {
$table->string('error_message')->nullable()->change();
});
But first of all you'll need the doctrine/dbal package
composer require doctrine/dbal
There is one more option. Roll back the migration, edit the file, and run it again.
This is a fairly common thing to do on a local development server while you're working out the bugs in a new piece of code. Using the method from the accepted answer, you might end up with 17 migrations for creating a single table!
php artisan migrate
# realize you've made an error
php artisan migrate:rollback
# edit your migration file
php artisan migrate
The number of steps back to take can be specified on the command line if needed.
# undo the last 3 migrations
php artisan migrate:rollback --step=3
Or you can specify a particular migration that needs undoing.
# undo one specific migration
php artisan migrate:rollback --path=./database/migrations/2014_10_12_100000_create_users_table.php
There are 2 ways to do this:
Run php artisan migrate:refresh. This will rollback all your
migrations and migrate all your migrations. If you run this command,
all the data inserted in your database will be lost.
Run php artisan make:migration enter_your_migration_name_here.
Then insert this in your migration:
$table->string('error_message')->nullable()->change();
Then run php artisan migrate to make your table changes. (Take note that when you do this, you have require composer require doctrine/dbal in your composer)