I am trying to connect to sqlite database file with Doctrine DBAL.
<?php
use Doctrine\DBAL\DriverManager;
require_once 'bootstrap.php';
$connectionParams = [
'url' => 'sqlite:///crawls.db',
];
$conn = DriverManager::getConnection($connectionParams);
But when I try to execute sql code it says that table is not exist (of course I checked manually and it is there).
$conn->exec('SELECT * FROM crawl_item');
outputs
PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 1 no such table: crawl_item' in /home/px/Documents/phpcrawler/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:57
Stack trace:...
May be this output can be helpful
var_dump($conn->connect());
var_dump($conn->getDatabase());
bool(true)
NULL
If you look at the AbstractSQLiteDriver::_constructPdoDsn() method you will see that the parameter is 'path':
$connectionParams = [
[
'driver' => 'pdo_sqlite',
'path' => '../products.db'
]
);
$conn = DriverManager::getConnection($connectionParams);
greetings,
thomas
Related
I'm using xampp as server in my laravel project. While creating migrations, I'm facing an error: only one migration table can be created; others are not being created.
This is the error:
**Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
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`))
at C:\xampp\htdocs\lsapp\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
660| // If an exception occurs when attempting to run a query, we'll format the error
661| // message to include the bindings with SQL, which will make this exception a
662| // lot more helpful to the developer instead of just
the database's errors.
663| catch (Exception $e) {
> 664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e 666| );
667| }
668|
Exception trace:
1 PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes")
C:\xampp\htdocs\lsapp\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458
2 PDOStatement::execute()
C:\xampp\htdocs\lsapp\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458**
Update your database.php file in the config folder as show below
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
to
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
and it should work. If it doesn't work then update AppServiceProvider.php in app/Providers/ as shown below.
use Illuminate\Support\Facades\Schema; //Import Schema
function boot()
{
Schema::defaultStringLength(191); //Solved by increasing StringLength
}
You can try this:
AppServiceProvider.php
use Illuminate\Support\Facades\Schema; //Import Schema
function boot()
{
Schema::defaultStringLength(191);
}
Hope that helps.
I want to make a post call with rest api using guzzlehttp in symfony ... I wrote this code but the response
/**
* #Route("/post/")
*/
public function postAction()
{
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', $url, [
'form_params' => [
'username' => 'test',
'password' => 'test',
]
]);
return $this->render('esterne/post.html.twig', array(
'response'=>$response,
));
}
this is the twig file post.html.twig
{{response}}
the result is this:
{"status":"200","data":{"is_auth":true,"userToken":"194b873c004716acb3e0a5fba09fe405"}}
but if I put in html:
return $this->render('esterne/post.html.twig', array(
'response'=>$response->getBody(),
));
it results in error 500 internal server error
[2018-11-14 09:56:35] request.CRITICAL: Uncaught PHP Exception Twig_Error_Runtime: "An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class GuzzleHttp\Psr7\Response could not be converted to string")." at /app/app/Resources/views/esterne/post.html.twig line 1 {"exception":"[object] (Twig_Error_Runtime(code: 0): An exception has been thrown during the rendering of a template (\"Catchable Fatal Error: Object of class GuzzleHttp\Psr7\Response could not be converted to string\"). at /app/app/Resources/views/esterne/post.html.twig:1, ErrorException(code: 0): Catchable Fatal Error: Object of class GuzzleHttp\Psr7\Response could not be converted to string at /app/var/cache/prod/twig/47/478ca9f9b0a5c69caa7b0fed874bf831466230764635f396f057dc2c33868549.php:23)"} []
SOLUTION
use file
{{ response|json_encode()|raw }}
in twig and
return $this->render('esterne/post.html.twig', array(
'response'=>json_decode($response->getBody()->getContents(), FALSE),
));
You could try following response.
return $this->render('esterne/post.html.twig', array(
'response'=>$response->getBody()->getContent(),
));
I'm using this PHP package, firebase-php, to communicate with the REST API.
I want to do very basic data push:
require_once ('utilities/firebase/firebaseLib.php');
$firebase = new Firebase(<my firebase url>, <my firebase token>);
$data = [
'ip' => "123456789",
'session' => "1234",
'sequence' => "12",
'time' => "159159159",
'event' => "Pause",
'data' => "1"
];
$res = $firebase->push(<my firbase path.json>, $data);
After execution I get this error: { "error" : "Invalid path: Invalid token in path" }
Not sure what this error means, no explanation at the docs...
Will be thankful for any help!
The firebase path in the push method ($res = $firebase->push(my-firebase.firebaseio.com/structure/of/json, $data); should be the relative path to the main firebase url.
So instead of 'my-firebase.firebaseio.com/structure/of/json' it should be just 'structure/of/json'.
When running a Symfony app in the dev environment, the web debug toolbar allows me to see how many queries that Doctrine generated. Is there a similar profiler option for Console commands?
As described in the docs, the profiler only collects information for all requests. I believe there is no collector for the console commands. One of the ways to get more insight into the queries executed by Doctrine is to check your log files. For example, you can do something like this on Unix based systems:
tail -f app/logs/dev.log | grep doctrine
Also see: http://symfony.com/doc/current/book/internals.html#profiler
Yeah, --verbose is useful as #manolo mentioned. You can control what gets output in -v -vv -vvv from the monolog handler config
monolog:
handlers:
main:
type: stream
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: debug
console:
type: console
bubble: false
verbosity_levels:
VERBOSITY_VERBOSE: INFO
VERBOSITY_VERY_VERBOSE: DEBUG
channels: ["!doctrine"]
console_very_verbose:
type: console
bubble: false
verbosity_levels:
VERBOSITY_VERBOSE: NOTICE
VERBOSITY_VERY_VERBOSE: NOTICE
VERBOSITY_DEBUG: DEBUG
channels: ["doctrine"]
Notice how you can even disable a channel -v or --verbose will only output non doctrine logs at the specified verbose levels.
First of all, symfony profiler depends on Request. Thats why its cant be used in console commands out of the box and, probably, it will not be fixed. Related symfony issue
But you still can access default DBAL profiling logger. It should be instance of Doctrine\DBAL\Logging\DebugStack
It have public queries property, which hold all executed queries, parameters, execution time etc.
Whenever you will need to debug actual queries - you can do in such a way
/** #var $em Registry */
$em = $this->getContainer()->get('doctrine')->getManager();
$profiler = $this->getContainer()->get('doctrine.dbal.logger.profiling.default');
$shop = $em->getRepository(Shop::class)->find(7);
$sku = $em->getRepository(Sku::class)->find(45);
// clear profiles data, we want to profile Criteria below
$profiler->queries = [];
$shopWares = $shop->getShopWarePagesForSku($sku);
$output->writeln(var_export($profiler->queries));
It would generate output like
array (
3 =>
array (
'sql' => 'SELECT ...... FROM ShopWarePage t0 WHERE (t0.sku_id = ? AND t0.sku_id = ?)',
'params' =>
array (
0 => 45,
1 => 7,
),
'types' =>
array (
0 => 'integer',
1 => 'integer',
),
'executionMS' => 0.00075292587280273438,
),
)
It's possible to run a command from the controller or other services. So all command information will be in the profiler.
There is an example from symfony docs
// src/Controller/DebugTwigController.php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
class DebugTwigController extends AbstractController
{
public function debugTwig(KernelInterface $kernel): Response
{
$application = new Application($kernel);
$application->setAutoExit(false);
$input = new ArrayInput([
'command' => 'debug:twig',
// (optional) define the value of command arguments
'fooArgument' => 'barValue',
// (optional) pass options to the command
'--bar' => 'fooValue',
]);
// You can use NullOutput() if you don't need the output
$output = new BufferedOutput();
$application->run($input, $output);
// return the output, don't use if you used NullOutput()
$content = $output->fetch();
// return new Response(""), if you used NullOutput()
return new Response($content);
}
}
Trying to use sqlite in development environment. It seems to detect the environment correctly but when I try to migrate to development.sqlite I get exception thrown "database does not exist"
artisan command
php artisan migrate --env=development
bootstrap/start.php
$env = $app->detectEnvironment(array(
'development' => array('localhost'),
));
app/config/development/database.php
<?php
return array(
'default' => 'sqlite',
'connections' => array(
'sqlite' => array(
'driver' => 'sqlite',
'database' => __DIR__.'/../database/development.sqlite',
'prefix' => '',
)
)
);
As far as I know laravel is supposed to create the file if it does not exist but since it didn't I tried manually creating the file and still get the exception thrown.
UPDATE: Maybe something not right with the env because the same thing happens if I try ':memory' for the database.
UPDATE 2: I tried running the sample unit test but add to TestCase.php
/**
* Default preparation for each test
*
*/
public function setUp()
{
parent::setUp(); // Don't forget this!
$this->prepareForTests();
}
/**
* Creates the application.
*
* #return Symfony\Component\HttpKernel\HttpKernelInterface
*/
public function createApplication()
{
$unitTesting = true;
$testEnvironment = 'testing';
return require __DIR__.'/../../bootstrap/start.php';
}
/**
* Migrates the database and set the mailer to 'pretend'.
* This will cause the tests to run quickly.
*
*/
private function prepareForTests()
{
Artisan::call('migrate');
Mail::pretend(true);
}
And this too gives the same exception though the testing env is already shipped with laravel. So I'll see if I can find any new issues on that.
Wow, typos and wrong paths.
Copying the sqlite array from config/database.php into config/development/database.php I forgot to change the path to the development.sqlite file from
__DIR__.'/../database/development.sqlite'
to
__DIR__.'/../../database/development.sqlite'
And for the in memory test it should have been
':memory:'
instead of
':memory'
I noticed that my database.php file had the following
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
],
I changed it to read the following, and it worked just fine.
'sqlite' => [
'driver' => 'sqlite',
'database' => database_path('database.sqlite'),
'prefix' => '',
],
One of the problem which I faced was I use "touch storage/database.sqlite" in terminal, so database is created in Storage folder instead of database folder.
in my config/database.php path is database_path('database.sqlite')
'sqlite' => [
'driver' => 'sqlite',
'database' => database_path('database.sqlite'),
'prefix' => '',
],
than I use command "php artisan migrate" which gave me error "Database (/Applications/MAMP/htdocs/FOLDER_NAME/database/database.sqlite) does
not exist."
so it's obvious database file is not in database folder as It was generated in Storage folder, so copy "database.sqlite" from storage folder or run command "touch database/database.sqlite"
Hope that helps.!!
Well, my answer is kinda outdated, but anyway. I faced the same problem, but with Laravel 5, I am using Windows 7 x64. First I manually created SQLite database called 'db' and placed it into storage directory, then fixed my .env file like this:
APP_ENV=local
APP_DEBUG=true
APP_KEY=oBxQMkpqbENPb07bLccw6Xv7opAiG3Jp
DB_HOST=localhost
DB_DATABASE='db'
DB_USERNAME=''
DB_PASSWORD=''
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null`
I thought it would fix my problems, but the command line keeps telling me that database doesn't exist. And then I just checked the path to db in my database.php file and this is why I put database file into storage directory. But nothing changed. And finally I checked db's extension and it was .db, not .sqlite as default extension you see in your sqlite block in database.php. So this is how I reconfigured sqlite piece:
'sqlite' => [
'driver' => 'sqlite',
'database' => storage_path().'/db.db',
'prefix' => '',
],
And of course don't forget to set sqlite as default database in your database.php file. Good luck!
For me it was that path to database had to be '/var/www/html' + location to the database in your project. In my case database was stored in database/db.sqlite so DB_DATABASE='/var/www/html/database/db.sqlite'
I had the same error while running a GitHub action test workflow.
For me the solution was to define the relative path to the database archive into the workflow file:
on:
...
env:
DB_CONNECTION: sqlite
DB_DATABASE: database/database.sqlite
jobs:
laravel-tests:
...
I think that the previous answers reduce the importance of the config and most likely the developers wanted to get the database file like this:
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => database_path(env('DB_DATABASE', 'database').'.sqlite'), // <- like this
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
Tested on Laravel 9.x