PostgreSQL error when run migration Lumen/Laravel - php

I recently changed the way my application connects to my PostgreSQL database to add the read/write principle. Since then, when I launch a migration I get the following error:
In Connection.php line 463:
[PDOException (42601)]
SQLSTATE[42601]: Syntax error: 7 ERROR: zero-length delimited identifier at or near """"
LINE 1: create table "" ("id" serial primary key not null, "migratio...
^
when I delete the database.php file, my migrations work correctly.
My .env
DB_CONNECTION=pgsql
DB_HOST=192.168.1.1
DB_PORT=5432
DB_DATABASE=database
DB_USERNAME=user
DB_PASSWORD=password
DB_USERNAME_READ=user
DB_PASSWORD_READ=password
My database.php
<?php
return [
'default' => env('DB_CONNECTION', 'pgsql'),
'connections' => [
'pgsql' => [
'read' => [
'username' => env('DB_USERNAME_READ'),
'password' => env('DB_PASSWORD_READ'),
],
'write' => [
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
],
'sticky' => true,
'driver' => 'pgsql',
'host' => env('DB_HOST'),
'database' => env('DB_DATABASE'),
],
],
];
and one of my migrations:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateGameUserTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('game_user', function (Blueprint $table) {
$table->bigInteger('game_id');
$table->bigInteger('user_id');
$table->foreign('game_id')->references('id')->on('games');
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('game_user');
}
}
PHP 7.3.13
Lumen 6.3.3
PostegreSQL 9.6.2

Lumen doesn't come with a config/database.php file by default. You can either copy a default Laravel file, or create your own with your own settings.
If you've already added your own custom file, it looks like you need to specify the migrations table name.
Default entry for Laravel is 'migrations' => 'migrations', but of course you can name it whatever you like.

I got the same problem on a Laravel 7.x project.
My solution was to remove the cache of my application then to update my dependencies via composer:
php artisan cache:clear
composer update

Related

Laravel Job executed immediately in browser instead of running in a background queue

I'm new to Laravel, and tried to create my first background task.
Used docs: https://laravel.com/docs/master/queues
Job: (ProcessDatabaseImport.php)
<?php
namespace App\Jobs;
use App\Contact;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\File;
class ProcessDatabaseImport implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $file;
/**
* Create a new job instance.
*
* #param String $filePath
* #return void
*/
public function __construct($filePath)
{
// init File object "database/data/contacts.json"
$this->file = base_path($filePath);
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
Log::info('Hello world! file: '.$this->file);
}
/**
* Determine the time at which the job should timeout.
*
* #return \DateTime
*/
public function retryUntil()
{
return now()->addSeconds(30);
}
}
?>
JobController.php:
<?php
namespace App\Http\Controllers;
use App\Jobs\ProcessDatabaseImport;
use Carbon\Carbon;
use Illuminate\Contracts\Queue\Job;
use Illuminate\Support\Facades\Queue;
class JobController extends Controller
{
/**
* Handle Queue Process
*/
public function processQueue()
{
ProcessDatabaseImport::dispatch('database/data/contacts.json')->delay(now()->addMinutes(2));
return view('home');
}
}
Jobs table is created, php artisan queue:work is running.
Now, when i go to the controller action in my browser, the code in "handle()" is exectuted twice, directly:
Log:
[2019-07-14 13:39:17] local.INFO: Hello world! file: B:\hellodialog\sollicitatieopdracht\database/data/contacts.json
[2019-07-14 13:39:18] local.INFO: Hello world! file: B:\hellodialog\sollicitatieopdracht\database/data/contacts.json
The database table for jobs is always empty.
In my .env file:
DB_CONNECTION=mysql
QUEUE_CONNECTION=database
queue.php config file:
return [
'default' => env('QUEUE_CONNECTION', 'database'),
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
'block_for' => 0,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'your-queue-name'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
],
],
'failed' => [
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'failed_jobs',
],
Is something missing?
Update: The job is added to the queue when I changed the default in queue.php
The job is now added twice to the database. I run this script by visiting the URL in my browser.
Sounds like you have two questions.
Running immediately in the browser
As for running immediately, this could happen if Laravel is still using the default sync driver. Check your /config/queue.php file and make sure the env() property is being used. Sync is the default fallback if no queue driver is set in your .env file, but you could also change this if you want.
'default' => env('QUEUE_CONNECTION', 'sync'),
If everything looks okay, try running php artisan config:clear to empty the config cache. It's possible that the default sync driver is still cached.
Alternatively, you can try explicitly defining the connection you wish to use.
ProcessDatabaseImport::dispatch('database/data/contacts.json')
->onConnection('database')
->delay(now()->addMinutes(2));
Running twice
I'm not sure about this, but what happens if you remove the retryUntil() method from the Job?
Also, I found a similar issue in another thread, but I don't know if it's related.
Queued Laravel queued job runs twice after upgrading to Laravel 5.4
If this doesn't help, we might need more information about how you are initiating the job. Are you simply visiting a URL, or is it possible that the mechanism to call this route could be running twice (e.g., via Ajax)?
And you might add the applicable /config/queue.php configuration to your question, as there is some indication from the thread mentioned above that your retry and timeout times may come into play.

Unit testing database: no such table: migrations

Trying to use an in-memory testing database for my unit tests. It seems that it can't even run the migrations, because the migrations table does not exist.
Here is my code:
abstract class TestCase extends BaseTestCase
{
use DatabaseMigrations;
public function setUp()
{
parent::setUp();
// use testing database
$this->setUpDatabase();
}
public function setUpDatabase()
{
$this->app['config']->set('database', [
'default' => 'testing',
'connections' => [
'testing' => [
'driver' => 'sqlite',
'database' => ':memory:',
],
],
]);
}
This gives me the error:
PDOException: SQLSTATE[HY000]: General error: 1 no such table: migrations
Not only that, but it also seems to be running migrations on my main database.

Laravel 5.5 migration error

I am trying to migrate my postgresql table, but when launch the command php artisan migrate it return the follow error:
SQLSTATE[08P01]: <>: 7 ERROR: bind message supplies 1 parameters, but prepared statement "pdo_stmt_00000003" requires 2 (SQL: select * from information_schema.tables
where table_schema = migrations and table_name = ?)
One of my migration:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateSchedulesTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('schedules', function(Blueprint $table)
{
$table->increments('id');
$table->string('schedule_name')->unique();
$table->integer('parent_id')->unsigned()->nullable();
$table->integer('launch_sequence_id')->unsigned();
$table->string('day_of_week', 10)->nullable();
$table->string('command_type', 50);
$table->integer('hours')->unsigned()->nullable();
$table->integer('minutes')->unsigned()->nullable();
$table->integer('dd')->unsigned()->nullable();
$table->integer('mm')->unsigned()->nullable();
$table->integer('yyyy')->unsigned()->nullable();
$table->boolean('enabled')->default(1);
$table->boolean('ascending')->default(0);
$table->dateTime('last_execution')->nullable();
$table->dateTime('last_success')->nullable();
$table->integer('retry')->default(0);
$table->timestamps();
$table->softDeletes();
});
DB::statement('ALTER TABLE schedules ADD CONSTRAINT day_of_week_check CHECK ((day_of_week)::text = ANY (ARRAY[(\'all\'::character varying)::text, (\'monday\'::character varying)::text, (\'tuesday\'::character varying)::text, (\'wednesday\'::character varying)::text, (\'thursday\'::character varying)::text, (\'friday\'::character varying)::text, (\'saturday\'::character varying)::text, (\'sunday\'::character varying)::text]))');
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('schedules');
}
}
And my database configuration:
'default' => env('DB_CONNECTION', 'pgsql'),
'connections' => [
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'schema' => env('DB_SCHEMA', 'public'),
//'sslmode' => 'prefer',
]
],
My .env
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=livion
DB_USERNAME=livion
DB_PASSWORD=secret
DB_SCHEMA=public
I tried to track it down and seems that it doesn't use the correct grammar for the function repositoryExists, it uses the default grammar witch doesn't send the schema parameter.
The other query executed via model or repository works fine, I get this error only for the migration command.
Any suggestion to solve this problem?
I figure out the problem.
I migrated the project from laravel 5.3 to 5.5 and the old project used the module Aejnsn\Postgresify.
It causes my problem on migration.
Remove it and all works again.

Laravel 5.3 migration doesn't create tables

I created some migrations using the command php artisan migrate:make and then filled it and saved it with some fields. This is a fresh installation and the first migration to run.
I ran php artisan migrate and the migration completed successfully. However, while the migrations table IS created, and it has a single row with the filename and batch 1, there is no table.
Here's my migration file code:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFuelLocationsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
//
Schema::create('fuel_locations', function (Blueprint $table) {
$table->increments('id');
$table->string('uid');
$table->string('name');
$table->string('fuel_type');
$table->string('email');
$table->string('street');
$table->string('city');
$table->string('state');
$table->string('zip');
$table->string('phone');
$table->string('service_hours');
$table->string('payment_methods');
$table->string('payment_method_other');
$table->decimal('latitude', 3, 7);
$table->decimal('longitude', 3, 7);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
Schema::dropIfExists('fuel_locations');
}
}
And a few lines from my config/database.php:
'mysql' => [
'driver' => 'mysql',
'database' => 'mydb',
'host' => 'localhost',
'username' => 'root',
'password' => '',
'charset' => env('DB_CHARSET', 'utf8'),
'collation' => env('DB_COLLATION', 'utf8_unicode_ci'),
'prefix' => env('DB_PREFIX', ''),
'timezone' => env('DB_TIMEZONE', '+00:00'),
'strict' => env('DB_STRICT_MODE', false),
],
I did try changing the host to 127.0.0.1 but that wouldn't connect. How can I fix it so that it does create the table like it's supposed to.
The problem is with the following lines:
$table->decimal('latitude', 3, 7);
$table->decimal('longitude', 3, 7);
You should be getting an exception similar to the following
[PDOException] SQLSTATE[42000]: Syntax error or access violation: 1427
For float(M,D), double(M,D) or decimal(M,D), M must be >= D (column
'latitude').
when you do the migration.
Change to the following
$table->decimal('latitude', 10, 7);
$table->decimal('longitude', 10, 7);
and it should work.
Numeric precision refers to the maximum number of digits that are present in the number

Laravel 4 migrate base table not found

I'm trying to make following tutorial: https://medium.com/on-coding/e8d93c9ce0e2
When it comes to run:
php artisan migrate
I get following error:
[Exception]
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel.user' doesn't
exist (SQL: alter table `user` add `id` int unsigned not null auto_increment prim
ary key, add `username` varchar(255) null, add `password` varchar(255) null, add
`email` varchar(255) null, add `created_at` datetime null, add `updated_at` datet
ime null) (Bindings: array (
))
Database connection is working, the migrations table was created successfully. Database name was changed as you can see in the error message.
Whats quite strange to me, is that it tries to alter the table - which doesn't exists - and not to create it.
Here are my other files, like UserModel, Seeder, Migtation and DB Config.
CreateUserTable:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('user', function(Blueprint $table)
{
$table->increments("id");
$table
->string("username")
->nullable()
->default(null);
$table
->string("password")
->nullable()
->default(null);
$table
->string("email")
->nullable()
->default(null);
$table
->dateTime("created_at")
->nullable()
->default(null);
$table
->dateTime("updated_at")
->nullable()
->default(null);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('user', function(Blueprint $table)
{
Schema::dropIfExists("user");
});
}
}
UserModel:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'user';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
UserSeeder:
class UserSeeder extends DatabaseSeeder
{
public function run()
{
$users = [
[
"username" => "ihkawiss",
"password" => Hash::make("123456"),
"email" => "ihkawiss#domain.com"
]
];
foreach ($users as $user)
{
User::create($user);
}
}
}
DatabaseSeeder:
class DatabaseSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Eloquent::unguard();
$this->call('UserSeeder');
}
}
Database Config:
return array(
/*
|--------------------------------------------------------------------------
| PDO Fetch Style
|--------------------------------------------------------------------------
|
| By default, database results will be returned as instances of the PHP
| stdClass object; however, you may desire to retrieve records in an
| array format for simplicity. Here you can tweak the fetch style.
|
*/
'fetch' => PDO::FETCH_CLASS,
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => 'mysql',
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => array(
'sqlite' => array(
'driver' => 'sqlite',
'database' => __DIR__.'/../database/production.sqlite',
'prefix' => '',
),
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'laravel',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
'pgsql' => array(
'driver' => 'pgsql',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
),
'sqlsrv' => array(
'driver' => 'sqlsrv',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => '',
'prefix' => '',
),
),
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk have not actually be run in the databases.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => array(
'cluster' => true,
'default' => array(
'host' => '127.0.0.1',
'port' => 6379,
'database' => 0,
),
),
);
Hope somebody can give me a hint here.
Best regards ihkawiss
In your CreateUserTable migration file, instead of Schema::table you have to use Schema::create.
The Schema::table is used to alter an existing table and the Schema::create is used to create new table.
Check the documentation:
http://laravel.com/docs/schema#creating-and-dropping-tables
http://laravel.com/docs/schema#adding-columns
So your user migration will be:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('user', function(Blueprint $table) {
{
$table->increments("id",true);
$table->string("username")->nullable()->default(null);
$table->string("password")->nullable()->default(null);
$table->string("email")->nullable()->default(null);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists("user");
}
}
The underlying cause of this may be if the syntax used for creating the migration php artisan migrate ... is not quite correct. In this case the --create will not get picked up properly and you will see the Schema::table instead of the expected Schema::create. When a migration file is generated like this you might also be missing some of the other markers for a create migration such as the $table->increments('id'); and $table->timestamps();
For example, these two commands will not create a create table migration file as you might expect:
php artisan migrate:make create_tasks_table --table="tasks" --create
php artisan migrate:make create_tasks2_table --table=tasks2 --create
However, the command will not fail with an error. Instead laravel will create a migration file using Schema::table
I always just use the full syntax when creating a new migration file like this:
php artisan migrate:make create_tasks_table --table=tasks --create=tasks
to avoid any issues like this.
Sometimes it is caused by custom artisan commands. Some of these commands might initiate few classes. And because we did a rollback, the table cannot be found. Check you custom artisan commands. You can comment out the lines which are causing the trigger. Run the php artisan migrate command and then uncomment. This is what I had to do.

Categories