Now I can call recursive_update but it still fails and I am not able to find out why.
I got this error:
DBIx::Class::Storage::DBI::_dbh_execute(): DBI Exception: DBD::mysql::st execute failed: Unknown column 'me.key' in 'where clause'
But I don't know why. I want to update a related database, the relationship is defined in the Result and retrieving Data works. But when I try recursive_update the key is unknown?
even if I explicite use it:
my $result = $rs->find_or_create({
a_id => xxx,
# ... other data ....
users => [{ u_id => xxx,}, { u_id => xxx}]
});
$rs->recursive_update($data,
{
fixed_fields => [ 'a_id' ],
}
);
I tried several ways to get the right key (a_id), but I got always the same error message about the "unknown key".
Do I need some special relationship?
Related
I have a command script to import products from csv file.
The code i use to create the product is:
$this->productRepository->create([[
'id' => Uuid::randomHex(),
'name' => 'exampls',
'taxId' => 'b6e10c80b24946a48bb74e742d280c75',
'stock' => 999,
'createdAt' => '2022-01-01T10:17:05+02:00',
'price' => [
[
'currencyId' => 'b7d2554b0ce847cd82f3ac9bd1c0dfca',
'gross' => 99,
'net' => 99,
'linked' => true,
]
],
'productNumber' => $suffix,
'visibilities' => [
[
'salesChannelId' => '5ce47a708e484e4d8c20221f8cdfa08f',
'visibility' => ProductVisibilityDefinition::VISIBILITY_ALL,
],
],
]], Context::createDefaultContext());
I get the following error:
An exception occurred while executing 'INSERT INTO `product` (`id`, `version_id`, `parent_version_id`, `product_manufacturer_versio
n_id`, `tax_id`, `product_media_version_id`, `cms_page_version_id`, `price`, `product_number`, `stock`, `restock_time`, `active`, `
is_closeout`, `purchase_steps`, `min_purchase`, `shipping_free`, `created_at`) VALUES ('���zgL��vc�.�p','���jK¾K��u,4%','���
jK¾K��u,4%','���jK¾K��u,4%','��
��IF���Nt-(
u','���jK¾K��u,4%','���jK¾K��u,4%','{\"cb7d2554b0ce847cd82f3ac9bd1c0dfca\":{\
"currencyId\":\"b7d2554b0ce847cd82f3ac9bd1c0dfca\",\"gross\":99.0,\"net\":99.0,\"linked\":true}}','62e2977934944','999',NULL,'1','0
','1','1','0','2022-01-01 08:17:05.000');':
What could i do to get it working? And if there is another way to approach this, i'm open for suggestions. Just started learning Shopware :)
At first glance this looks to be correct. The error message seems to be incomplete. It should say after the query why it failed, be it a syntax error or a wrong foreign key. The latter would be my best guess at what could fail the moment, have you checked all the uuids to exist in their corresponding tables like tax, currency and sales_channel?
I'm using this plugin as output for my logstash logs.
I need to use the upsert function to check if a row exists then update, if it doesn't exist then simply add.
I'm using PostgreSQL as db and it supports the usage of UPSERT, very good described here. As input, the logs are coming from elasticsearch.
The problem with my configuration is that I correctly add new rows in my table but cannot update an existing one.
Here's my configuration :
jdbc {
driver_jar_path => '/home/vittorio/Downloads/postgresql-42.1.1.jre6.jar'
connection_test => false
connection_string => 'jdbc:postgresql://127.0.0.1:5432/postgres'
statement => ["
INSERT INTO userstate VALUES(?,?,?,?,?) on conflict (username)
do update set (business_name, iban, status, timestamp) = ('%{[resource][response_attributes][business_name]}','%{[resource][response_attributes][iban]}','%{[resource][response_attributes][status]}','%{#timestamp}')
where userstate.username = '%{[request][username]}';", "%{[request][username]}","%{[resource][response_attributes][business_name]}","%{[resource][response_attributes][iban]}","%{[resource][response_attributes][status]}","%{#timestamp}"
]
username => "myuser"
password => "mypass"
}
Am I doing something wrong?
thanks
I manged to make it work by myself and this is what I've done so far :
jdbc {
driver_jar_path => '/home/vittorio/Downloads/postgresql-42.1.1.jre6.jar'
connection_test => false
connection_string => 'jdbc:postgresql://127.0.0.1:5432/postgres'
statement => ["
INSERT INTO userstate VALUES(?,?,?,?,?)
on conflict (username)
do update set (business_name, iban, status, timestamp) = (?,?,?,?)
where userstate.username = ?"
, "%{[request][username]}","%{[resource][response_attributes][business_name]}","%{[resource][response_attributes][iban]}","%{[resource][response_attributes][status]}","%{#timestamp}","%{[resource][response_attributes][business_name]}","%{[resource][response_attributes][iban]}","%{[resource][response_attributes][status]}","%{#timestamp}","%{[request][username]}"
]
username => "myusername"
password => "mypass"
}
Basically,I've changed the where statement using ? instead of %{[request][username]} and then map each ? with the corresponding value from the log. I know, it's pretty long stuff after the coma but this is the only way I found to make it work. If anyone knows a better way to do it please let me know.
Thank you
I'm using Postgres (which I think is related to the problem), and CakePHP 3.
I have the following unit test to just check to make sure that a valid dataset can get saved by the model. When I run the following test, with a standard "bake'd" Model unit test, I get the error below.
I think this is the problem:
We are using fixtures to add some base data. This is the only place that I think might be causing a problem. To add credence to this, while the unit tests were running I ran the following command to get the next auto-incrementing id value and it returned 1, even though it returned the proper number in non-test DB. Select nextval(pg_get_serial_sequence('agencies', 'id')) as new_id;
Unit Test:
public function testValidationDefault()
{
$agencyData = [
'full_name' => 'Agency Full Name',
'mode' => 'transit',
'request_api_class' => 'Rest\Get\Json',
'response_api_class' => 'NextBus\Generic',
'realtime_url_pattern' => 'http://api.example.com',
'routes' => '{"123": {"full_route": "123 Full Route", "route_color": "#123456"}}'
];
$agency = $this->Agencies->newEntity($agencyData);
$saved = $this->Agencies->save($agency);
$this->assertInstanceOf('App\Model\Entity\Agency', $saved);
}
Error:
PDOException: SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "agencies_pkey"
DETAIL: Key (id)=(1) already exists.
Things I've tried
Copied that same code into a controller, and it successfully added the entity in the table.
Adding an id of 200. Same error appears.
Update 1
The fixture for this does have the ID field set each record. Deleting them from the fixture does work, but it breaks other unit tests that rely on some relational data.
I don't like this solution, but adding the following before saving the entity does work.
$this->Agencies->deleteAll('1=1');
[UPDATE: My other answer is the real solution to this problem.! You don't have to do this anymore...]
Here is a less dirty workaround that doesn't require deleting all the records:
use Cake\Datasource\ConnectionManager;
...
$connection = ConnectionManager::get('test');
$results = $connection->execute('ALTER SEQUENCE <tablename>_id_seq RESTART WITH 999999');
//TEST WHICH INSERTS RECORD(s)...
It appears that the auto-incrementing doesn't get properly set/reset during the setUp() or tearDown()... so manually setting it to something really high (greater than the number of existing records) prevents the "duplicate key..." error.
The benefit of this hack (over deleteAll('1=1')) is that you can still subsequently run tests that reference existing DB data.
It might be a problem in your fixture definition. The Cake PHP documentation uses a _constraints field specifying that the id field is a primary key:
'_constraints' => [
'primary' => ['type' => 'primary', 'columns' => ['id']],
]
I believe I've finally figured out the REAL solution to this problem!
I believe this issue stems from a default fixture setting that results from using the bake command to generate fixtures.
When you bake a model it creates the boilerplate for it's fixtures. Notice the autoIncrement for the ID property in the code below? Contrary to what you might think, this should not but true. When I set it to null and remove the ids from the items in the $records array I no longer get uniqueness errors.
public $fields = [
'id' => ['type' => 'integer', 'length' => 10, 'autoIncrement' => true, 'default' => null, 'null' => false, 'comment' => null, 'precision' => null, 'unsigned' => null],
'nickname' => ['type' => 'text', 'length' => null, 'default' => null, 'null' => false, 'comment' => null, 'precision' => null],
...
public $records = [
[
// 'id' => 1,
'nickname' => 'Foo bar',
'width' => 800,
...
The ninja wizards on the CakePHP project are the heroes: source
CakePHP ticket
If id fields are removed from fixture records then they will utilize auto-incrementing when inserted, leaving the table's ID sequence in the right place for inserts that happen during tests. I believe that is why it works for #emersonthis as described above.
That solution has another problem, though: you can't create dependable relationships between fixture records because you don't know what IDs they will get. What do you put in the foreign ID field of a related table? This has led me back to his original solution of just altering the table sequence after records with hard-coded IDs have been inserted. I do it like this in affected TestCases now:
public $fixtures = [
'app.articles',
'app.authors',
];
...
public function setUp()
{
$connection = \Cake\Datasource\ConnectionManager::get('test');
foreach ($this->fixtures as $fixture) {
$tableName = explode('.', $fixture)[1];
$connection->execute("
SELECT setval(
pg_get_serial_sequence('$tableName', 'id'),
(SELECT MAX(id) FROM $tableName)
)");
}
}
This moves the auto-increment sequence to the highest previously-used ID. The next time an ID is generated from the sequence it will be one higher, resolving the problem in all cases.
Including one of these solutions in an upcoming CakePHP release is being discussed here.
I've got this:
$barCode = '5055060927427';
$amazon = new Zend_Service_Amazon($this->AMAZON_API_KEY, 'UK', $this->AMAZON_API_SECRET);
$amazon = null;
$amazonRes = $amazon->itemLookup($barCode,
array(
'SearchIndex' => 'All',
'AssociateTag' => 'NON ASSOCIATE',
'IdType' => 'EAN',
'ResponseGroup' => 'Large,ItemAttributes,Images',
)
);
But this just gives me an error:
Fatal error: Uncaught exception 'Zend_Service_Exception' with message '5055060927427 is not a valid value for ItemId. Please change this value and retry your request. (AWS.InvalidParameterValue)' in C:\wamp\www\easionline\src\Zend\Service\Amazon.php on line 319
The game I am trying to find is: http://www.amazon.com/Asuras-Wrath-Playstation-3/dp/B003O6HLOK/ref=sr_1_1?ie=UTF8&qid=1360139714&sr=8-1&keywords=azuras+wrath
That is the normal response from the API, when the EAN doesn't exist on that locale.
You won't receive this error when you use a ean that does exist.
My problem is as follows.
After deleting multiple rows from table, inserting new record into same table results in error.
Database Error
Error: SQLSTATE[42P01]:
Undefined table: 7 ERROR: relation "order_details_id_seq" does not exist
Table
CREATE TABLE schema.order_details (
id serial NOT NULL,
order_id integer NOT NULL,
field_1 integer,
field_2 real,
field_3 character varying(15),
CONSTRAINT order_details_pkey PRIMARY KEY (id )
)
WITH (
OIDS=FALSE
);
Insert is
INSERT INTO "schema"."order_details" ("order_id", "field_1", "field_2", "field_3")
VALUES (37, 1, 2, 'value');
Sequence "schema"."order_details_id_seq" in used schema exists.
CREATE SEQUENCE schema.order_details_id_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 37
CACHE 1;
Models.
// Model
class Order extends AppModel {
public $useDbConfig = 'other_data';
public $hasMany = array(
'OrderDetail' => array(
'className' => 'OrderDetail',
'foreignKey' => 'order_id',
'dependent' => true,
'order' => array(
'OrderDetail.order_id',
'OrderDetail.field_1'
))
);
class OrderDetail extends AppModel {
public $useDbConfig = 'other_data';
public $belongsTo = array(
'Order' => array(
'className' => 'Order',
'foreignKey' => 'order_id',
'dependent' => true
),
// model Order save code on recreation of order
$this->OrderDetail->deleteAll(array('OrderDetail.order_id' => $this->id));
At this point tried to insert $this->OrderDetail->query('VACUUM FULL ANALYZE order_details'); with no effect
foreach ($details as $d) {
$this->OrderDetail->create();
$this->OrderDetail->save($d /*array(
'order_id' => $this->id,
'field_1' => 1,
'field_2' => 2,
'field_3' => 'value'
)*/);
}
I get error on first foreach loop.
Weirdest thing is that problem appears and disappears after some time randomly.
Any suggestions on what it could be and how to get rid of it?
Currently solved problem using code.
$this->Order->id = $id;
$this->Order->delete();
It fires 2 queries for each row (100 extra in my case!) of delete statements instead of two in case of
$this->OrderDetail->deleteAll(array('OrderDetail.order_id' => $id));
So for this time it has space for improvement.
EDIT: Currently code works as it should with tweaked DboSource.
It seems that cake was looking in public schema for sequence where it is not located.
Fixed it by tweaking to include schema name in last insert getter inf file Model/Datasource/DboSource.php create method with this diff
## -1006,7 +1006,7 ##
if ($this->execute($this->renderStatement('create', $query))) {
if (empty($id)) {
- $id = $this->lastInsertId($this->fullTableName($model, false, false), $model->primaryKey);
+ $id = $this->lastInsertId($this->fullTableName($model, false, true), $model->primaryKey);
}
$model->setInsertID($id);
$model->id = $id;
I know that modifying core is not the way to go, but as long as it is working it is fine with me.
This happened to me because I modified the name of the table, but PostgreSQL did not change the name of the sequences. Knowing this, I changed the name of the sequences that affected this table and it was resolved.
To prevent this error, use this convention to name your sequence when using cakephp: table_name_id_seq. For example:
table name: user
sequence name should be: user_id_seq
If you alredy have sequences, you can rename it in posgres like this
alter sequence user_seq rename to user_id_seq
I'm not a fun of this way to name sequence but it prenvent this kind of errors in my case