PostgreSQL column does not exist when it does - postgresql

I have the following PostgreSQL query...
WITH update_parts (id,id_finish)
AS (VALUES (1,42), (2,42), (3,30), (4,30))
UPDATE parts SET id = up.id, id_metal = up.id_metal
FROM update_parts up WHERE up.id = parts.id;
...and I get the error...
column up.id_metal does not exist LINE 1
I have verified I'm connected to the correct database, to the correct table and that the column exists. I'm only partially certain about permissions which I set via the following...
GRANT ALL(id_metal) ON parts TO public;
...and...
GRANT ALL(id_metal) ON parts TO postgres;
I plan to limit the permissions to SELECT, UPDATE, DELETE and INSERT after I've figured out the problem. For clarification it is the "parts" table and the "id_metal" column.
How do I resolve this error and UPDATE the rows?
After updating the permissions I'm not sure what else to consider?
I used the following query to get information about the column...
SELECT * FROM information_schema.columns
WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
AND column_name='id_finish';
...which returns...
Array (
[table_catalog] => [database name]
[table_schema] => public
[table_name] => parts
[column_name] => id_metal
[ordinal_position] => 7
[column_default] =>
[is_nullable] => YES
[data_type] => bigint
[character_maximum_length] =>
[character_octet_length] =>
[numeric_precision] => 64
[numeric_precision_radix] => 2
[numeric_scale] => 0
[datetime_precision] =>
[interval_type] =>
[interval_precision] =>
[character_set_catalog] =>
[character_set_schema] =>
[character_set_name] =>
[collation_catalog] =>
[collation_schema] =>
[collation_name] =>
[domain_catalog] =>
[domain_schema] =>
[domain_name] =>
[udt_catalog] => [database name]
[udt_schema] => pg_catalog
[udt_name] => int8
[scope_catalog] =>
[scope_schema] =>
[scope_name] =>
[maximum_cardinality] =>
[dtd_identifier] => 7
[is_self_referencing] => NO
[is_identity] => NO
[identity_generation] =>
[identity_start] =>
[identity_increment] =>
[identity_maximum] =>
[identity_minimum] =>
[identity_cycle] =>
[is_generated] => NEVER
[generation_expression] =>
[is_updatable] => YES
)

You are going through a lot of hoops with permissions, but the problem is simple syntax:
WITH update_parts (id, id_finish) AS (
VALUES (1,42), (2,42), (3,30), (4,30)
)
UPDATE parts SET id_metal = up.id_finish
FROM update_parts up WHERE up.id = parts.id;
In your CTE you define the columns id and id_finish so your main query should refer to the same up.id_finish, not the id_metal from the parts table.
Further, it is usless to update parts.id with the value of update_parts.id because they are the same by definition: WHERE up.id = parts.id.

Related

(Salesforce Force.com REST API) How do I determine which products are associated with opportunities?

I'm using the Salesforce Force.com REST API. I need to determine which Products (Product2) are associated with Opportunities (Opportunity). Thus far, I've been unable to make the connection.
In the Salesofrce UI, opportunities can be associated with pricebooks and products. Pricebooks contain products, but it is also possible to associate products with an opportunity directly.
Querying an opportunity via the API yields the following:
Array
(
[0] => Array
(
[attributes] => Array
(
[type] => Opportunity
[url] => /services/data/v33.0/sobjects/Opportunity/xxxxxxxxxxxxxxxx
)
[Id] => xxxxxxxxxxxxxxxx
[IsDeleted] =>
[AccountId] => xxxxxxxxxxxxxxxxx
[Name] => Some Name
[Description] =>
[StageName] => Closed Won
[Amount] => 650
[Probability] => 100
[CloseDate] => 2012-04-12
[Type] => New Business
[NextStep] => A string
[LeadSource] => something
[IsClosed] => 1
[IsWon] => 1
[ForecastCategory] => Closed
[ForecastCategoryName] => Closed
[CampaignId] =>
[HasOpportunityLineItem] => 1
[Pricebook2Id] => xxxxxxxxxxxxxxxxxxxxx
[OwnerId] => xxxxxxxxxxxxxxxxxxx
[CreatedDate] => 2012-12-30T20:17:35.000+0000
[CreatedById] => xxxxxxxxxxxxxxxxxxxxxxxxxxx
[LastModifiedDate] => 2015-05-22T15:20:18.000+0000
[LastModifiedById] => xxxxxxxxxxxxxxxxxxxxxxxx
[SystemModstamp] => 2015-05-22T15:20:18.000+0000
[LastActivityDate] =>
[FiscalQuarter] => 1
[FiscalYear] => 2015
[Fiscal] => 2015 1
[LastViewedDate] => 2015-06-03T14:38:03.000+0000
[LastReferencedDate] => 2015-06-03T14:38:03.000+0000
[SyncedQuoteId] =>
[Type_of_Deal__c] => Monthly Contract Count
[Number_of_Contracts__c] => 999
[Fee_Per_Contract__c] => 999
[Installation_Fee__c] =>
[Roof_Top_Fee__c] =>
[LID__LinkedIn_Company_Id__c] =>
[inclusion_type__c] => inclusion type
[Total_Contract_Term__c] => 999
[Monthly_Value_of_Fee_Per_Contract__c] => 999
[Total_Value_of_Fee_Per_Contract__c] => 999
[Total_Value_of_Roof_Top_Fee__c] => 0
[Monthly_Fidels_Revenue__c] => 999
[Total_Value_of_Deal__c] => 999
[Number_of_Roof_Tops__c] =>
[Monthly_Value_of_Roof_Top_Fee__c] => 0
[Installation_Date__c] => 2012-01-01
[Reason_if_Lost__c] =>
[Total_Monthly_Revenue__c] => 999
[Existing_Agency__c] => Service Group
[Number_of_Contracts_in_Last_Batch__c] => 999
[Agent_Name__c] => John Smith
[Total_Value_of_Agency_Revenue__c] => 9999
[Contract_Start_Date__c] => 2012-01-01
[Batch_Received__c] => Yes
[Administrator__c] =>
[Per_Contract__c] => 999
[Integration_type__c] =>
[Last_Batch_ID__c] =>
[Last_Batch_Date__c] =>
)
)
From which you can see that no Product2 data is available. There is however, a Pricebook2Id. One might assume that querying that specific pricebook would yield information on which products are associated with it. However, querying a specific pricebook yields the following:
Array
(
[0] => Array
(
[attributes] => Array
(
[type] => Pricebook2
[url] => /services/data/v33.0/sobjects/Pricebook2/xxxxxxxxxxxx
)
[Id] => xxxxxxxxxxxxxxxxxxxx
[IsDeleted] =>
[Name] => Company Price Book
[CreatedDate] => 2011-11-14T18:36:23.000+0000
[CreatedById] => xxxxxxxxxxxxxxxxxxx
[LastModifiedDate] => 2011-11-14T18:36:23.000+0000
[LastModifiedById] => xxxxxxxxxxxxxxxxxxxxxxx
[SystemModstamp] => 2011-11-14T18:36:23.000+0000
[LastViewedDate] => 2015-06-04T19:41:20.000+0000
[LastReferencedDate] => 2015-06-04T19:41:20.000+0000
[IsActive] => 1
[Description] =>
[IsStandard] =>
)
)
As you can see, no information about products is available from the pricebook. So my question is:
How do I determine which products are associated with opportunities using the Salesforce Force.com REST API?
There is an object called 'Opportunity Product'. you need to get that object as well and link the proper opportunity to product.
It's a many to many relation and not one to many so more than one product might be related to each opportunity and vise versa.

does CakePHPs Containable-behavior support custom expressions as conditions?

Community,
I'm currently facing an issue with the containable-behavior setting conditions based on the datasources expression-builder. I'm using CakePHP 2.6.2 with a PostgreSQL database.
What works so far:
I wrote a behavior that dynamically adds conditions to find-operations to restrict the results based on a privileges table. Im using subqueries with the buildstatement() and expression() functions provided by cake. I followed this article from the CakeBook:
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
Here is a simplyfied code-snippet, in fact its two OR-statements:
$conditionsSubQueryRecord = array(
'Privilege.objecttable' => $model->table,
'Privilege.objectid = '.$model->alias.'.'.$model->primaryKey,
'Privilege.read' => true,
'Privilege.id' => $this->recordPermissions
);
$dsPrivilege = $this->privilegeModel->getDataSource();
$subQueryRecordPrivs = $dsPrivilege->buildStatement(
array(
'fields' => array('"'.$this->privilegeModel->alias.'"."id"'),
'table' => $dsPrivilege->fullTableName($this->privilegeModel),
'alias' => $this->privilegeModel->alias,
'limit' => null,
'offset' => null,
'joins' => array(),
'conditions' => $conditionsSubQueryRecord,
'order' => null,
'group' => null
),
$this->privilegeModel
);
$subQueryRecordPrivs = ' EXISTS (' . $subQueryRecordPrivs . ') ';
$subQueryRecordPrivsExpression = $dsPrivilege->expression($subQueryRecordPrivs);
I'm adding the statement to my condition array then in my behaviors beforeFind()-hook. This works all very well so far. The condition is added, the results are filtered.
The conditions are ignored for my contained models:
My problem is now to use this condition on contained models. I wrote an recursive algorithm that walks along all the contained modelsand if the model actsAs my behavior I am attaching the same conditions to its conditions-array. But when I execute my search, the condition is ignored on the contained models and only attached to the primary model.
This is the complete condition string I'm executing:
array(
'conditions' => array(
'Requestinstance.id' => (int) 4,
(int) 0 => object(stdClass) {
type => 'expression'
value => ' EXISTS (SELECT "Privilege"."id" FROM "core"."privileges" AS "Privilege" WHERE "Privilege"."objecttable" = 'requestinstances' AND "Privilege"."objectid" = "Requestinstance"."id" AND "Privilege"."read" = 'TRUE' AND "Privilege"."id" = (8)) OR EXISTS (SELECT "Privilege"."id" FROM "core"."privileges" AS "Privilege" WHERE "Privilege"."objecttable" = 'requestinstances' AND "Privilege"."read" = 'TRUE' AND "Privilege"."id" IN (7, 13, 6, 9, 10, 12) AND "Privilege"."objectid" IS NULL) '
}
),
'fields' => null,
'joins' => array(),
'limit' => (int) 1,
'offset' => null,
'order' => array(
(int) 0 => null
),
'page' => (int) 1,
'group' => null,
'callbacks' => true,
'contain' => array(
'Requesttype' => array(
'Steptype' => array(
'order' => array(
(int) 0 => 'RequesttypesSteptype.phase ASC'
),
'conditions' => object(stdClass) {
type => 'expression'
value => ' EXISTS (SELECT "Privilege"."id" FROM "core"."privileges" AS "Privilege" WHERE "Privilege"."objecttable" = 'steptypes' AND "Privilege"."objectid" = "Steptype"."id" AND "Privilege"."read" = 'TRUE' AND "Privilege"."id" = (8)) OR EXISTS (SELECT "Privilege"."id" FROM "core"."privileges" AS "Privilege" WHERE "Privilege"."objecttable" = 'steptypes' AND "Privilege"."read" = 'TRUE' AND "Privilege"."id" IN (7, 13, 6, 9, 10, 12) AND "Privilege"."objectid" IS NULL) '
}
),
(int) 0 => 'RequesttypesSteptype',
'conditions' => object(stdClass) {
type => 'expression'
value => ' EXISTS (SELECT "Privilege"."id" FROM "core"."privileges" AS "Privilege" WHERE "Privilege"."objecttable" = 'requesttypes' AND "Privilege"."objectid" = "Requesttype"."id" AND "Privilege"."read" = 'TRUE' AND "Privilege"."id" = (8)) OR EXISTS (SELECT "Privilege"."id" FROM "core"."privileges" AS "Privilege" WHERE "Privilege"."objecttable" = 'requesttypes' AND "Privilege"."read" = 'TRUE' AND "Privilege"."id" IN (7, 13, 6, 9, 10, 12) AND "Privilege"."objectid" IS NULL) '
}
),
'Stepinstance' => array(
(int) 0 => 'Steptype',
(int) 1 => 'Stepdatainstance',
(int) 2 => 'Sectioninstance'
),
'Requestdatainstance' => array(),
'Taskinstance' => array()
),
'recursive' => (int) 2
)
As you can see, the condition was correctly added to some of the contained models. However, the executed SQL-query, i.e. for the "Steptype"-Model, is generated without the condition:
SELECT "Steptype"."id" AS "Steptype__id", "Steptype"."name" AS "Steptype__name", "Steptype"."description" AS "Steptype__description", "Steptype"."subscribe" AS "Steptype__subscribe", "RequesttypesSteptype"."id" AS "RequesttypesSteptype__id", "RequesttypesSteptype"."phase" AS "RequesttypesSteptype__phase", "RequesttypesSteptype"."endsphase" AS "RequesttypesSteptype__endsphase", "RequesttypesSteptype"."endsrequest" AS "RequesttypesSteptype__endsrequest", "RequesttypesSteptype"."usertype_id" AS "RequesttypesSteptype__usertype_id", "RequesttypesSteptype"."requesttype_id" AS "RequesttypesSteptype__requesttype_id", "RequesttypesSteptype"."steptype_id" AS "RequesttypesSteptype__steptype_id" FROM "core"."steptypes" AS "Steptype" JOIN "core"."requesttypes_steptypes" AS "RequesttypesSteptype" ON ("RequesttypesSteptype"."requesttype_id" = 6 AND "RequesttypesSteptype"."steptype_id" = "Steptype"."id") ORDER BY "RequesttypesSteptype"."phase" ASC
Direct use of the buildStatement does not work either
I also tried to use the statement itself directly, without building an expression from it. This actually creates exactly the SQL-query I want to have, but does not add the quotes of the table alias in the FROM-clause correctly and therefore causes postgreSQL to throw an error:
SELECT "Requestinstance"."id" AS "Requestinstance__id", "Requestinstance"."user_id" AS "Requestinstance__user_id", "Requestinstance"."created" AS "Requestinstance__created", "Requestinstance"."requesttype_id" AS "Requestinstance__requesttype_id", "Requestinstance"."currentphase" AS "Requestinstance__currentphase", "Requestinstance"."selfsolving" AS "Requestinstance__selfsolving", "User"."username" AS "User__username", "User"."id" AS "User__id", "User"."company_id" AS "User__company_id", "User"."usertype_id" AS "User__usertype_id", "Requesttype"."id" AS "Requesttype__id", "Requesttype"."name" AS "Requesttype__name", "Requesttype"."subtitle" AS "Requesttype__subtitle", "Requesttype"."description" AS "Requesttype__description", "Requesttype"."order" AS "Requesttype__order", "Requesttype"."selfsolving" AS "Requesttype__selfsolving" FROM "core"."requestinstances" AS "Requestinstance" LEFT JOIN "core"."users" AS "User" ON ("Requestinstance"."user_id" = "User"."id") LEFT JOIN "core"."requesttypes" AS "Requesttype" ON ("Requestinstance"."requesttype_id" = "Requesttype"."id") WHERE EXISTS (SELECT "Privilege"."id" FROM "core"."privileges" AS Privilege WHERE "Privilege"."objecttable" = 'requestinstances' AND "Privilege"."objectid" = "Requestinstance"."id" AND "Privilege"."read" = 'TRUE' AND "Privilege"."id" = (8)) OR EXISTS (SELECT "Privilege"."id" FROM "core"."privileges" AS Privilege WHERE "Privilege"."objecttable" = 'requestinstances' AND "Privilege"."read" = 'TRUE' AND "Privilege"."id" IN (7, 13, 6, 9, 10, 12) AND "Privilege"."objectid" IS NULL) LIMIT 1
Adding the quotes manually to the alias-string while building the statement does not help either, since the framework strips the quotes.
So finally my question(s):
Does anybody know, if the containable-behavior supports expressions at all? I already digged into the DboSource, PdoSource and Postgresql-datasource but could not find anything wrong here. The Containable behavior looks pretty straight forward as well. Am I doing something wrong here?
Or is there another way I could acchieve what I want?
I'm glad for any help in this matter!
Thanks in advance!
I finally figured it out!
To formally answer the question:
Yes, the containable behavior does support expression-syntax!
My problem was with the processing order: The framework processes the behaviors the configured order, I accidently loaded the containable before my custom behavior, thats why it never received my modified conditions...
Working with the correct order, the manipulated condition-string was processed fine by the containable behavior.
To be absolutely sure about the behaviors order, I moved the behavior-loading to the AppModels __construct() method:
// unload any configured Containable behavior
if($this->Behaviors->loaded('Containable')) {
$this->Behaviors->unload('Containable');
}
// load the PrivilegeItem behavior
if($this->alias !== 'Privilege') {
$this->Behaviors->load('PrivilegeItem');
}
// and finally (re-)attach the Containable behavior
$this->Behaviors->load('Containable');
Maybe it helps others avoiding two days of debugging headache...

Using Forge to Insert into database but not getting an insert ID

I'm new to Fuel...
got my script inserting a record using the following code:
$address = Model_Address::forge(array(
'street1' => $step1_data['street1'],
'street2' => $step1_data['street2'],
'suburb' => $step1_data['street2'],
'city' => $step1_data['city'],
'region' => $step1_data['region'],
'country' => $step1_data['country'],
'postcode' => $step1_data['postcode'],
));
$address->save();
I think I should be able to get the insert id via $address->id but it's empty.
I'm not sure what I'm doing wrong?
We are using pg_swl not sure if that makes any difference.

how to write udate query in yii for mongo db?

User::model()->update($_id, array('$set' => array('d' => 1)[, array('deleted' => 1)[, array('w' => 2)]]);
I want to update user table with specified user id.
it's not working
The brackets are optional parts, this stems from the PHP manual ( i.e.: http://php.net/manual/en/function.pathinfo.php ) so:
User::model()->update($_id, array('$set' => array('d' => 1)
[, array('deleted' => 1)[, array('w' => 2)]]);
Will never work and will actually throw a syntax error in PHP in its current state. Instead you can try:
User::model()->update($_id, array('$set' => array('d' => 1)));

Get data from one table with foreign_table and update to another in TCA

I'm modifying an image upload extension and I'm working on a feature where images can be placed in categories.
Right now the categories are listed in a select field that uses foreign_table to get the categories from a table (called tx_gallery_categories) and when saved the category Id (the value in the option field) is saved to table called tx_gallery_items.
But that column is no longer needed (i was wrong the first time). Depending on what category you choose I want TCA to update a table called tx_gallery_itemsCategory and set the categoryId where itemId is equal to the saved images uid
Here is the TCA (i have removed all other columns beside categoryId) and categoryId is the one I want to move out from this, I think, and in to it's own TCA which is connected to tx_gallery_itemsCategory:
$TCA["tx_gallery_items"] = array (
"ctrl" => $TCA["tx_gallery_items"]["ctrl"],
"interface" => array (
"showRecordFieldList" => "hidden,oid,filename, videoembedcode,caption"
),
"feInterface" => $TCA["tx_gallery_items"]["feInterface"],
"columns" => array (
"categoryId" => Array (
"exclude" => 1,
"label" => "LLL:EXT:gc_gallery/locallang_db.xml:tx_gallery_items.categories",
"config" => Array (
"type" => "select",
"foreign_table" => "tx_gallery_categories",
// "foreign_table_where" => " true"
// "itemsProcFunc" => "tx_gallery_getImageCategories->getCategories"
// 'default' => '123'
)
),
),
"types" => array (
"0" => array("showitem" => "hidden, oid, filename, categoryId, videoembedcode, caption, linkpid")
)
);
$TCA["tx_gallery_categories"] = array (
"ctrl" => $TCA["tx_gallery_categories"]["ctrl"],
"interface" => array (
"showRecordFieldList" => "categoryTitle"
),
"feInterface" => $TCA["tx_gallery_categories"]["feInterface"],
"columns" => array (
"categoryTitle" => Array (
"exclude" => 0,
"label" => "LLL:EXT:gc_gallery/locallang_db.xml:tx_gallery_items.categories",
"config" => Array (
"type" => "text",
"cols" => "30",
"rows" => "5",
)
)
),
"types" => array (
"0" => array("showitem" => "categoryTitle")
)
);
But instead of it working like that I want to save the images uid from tx_gallery_items to another table called tx_gallery_itemsCategory which is a many to many table between tx_gallery_items and tx_gallery_categories
Here are the tables:
tx_gallery_items:
uid | pid | ... (and many more but only uid is relevant)
432 | 34 | ...
tx_gallery_itemsCategory:
id | itemId | categoryId
1 | 432 | 1
tx_gallery_categories:
uid | pid | categoryTitle
1 | 34 | example category
And here is the ext_tables.php
$TCA["tx_gallery_items"] = array (
"ctrl" => array (
'title' => 'LLL:EXT:gc_gallery/locallang_db.xml:tx_gallery_items',
'label' => 'filename',
'tstamp' => 'tstamp',
'crdate' => 'crdate',
'cruser_id' => 'cruser_id',
'sortby' => 'sorting',
'delete' => 'deleted',
'enablecolumns' => array (
'disabled' => 'hidden',
),
'dynamicConfigFile' => t3lib_extMgm::extPath($_EXTKEY).'tca.php',
'iconfile' => t3lib_extMgm::extRelPath($_EXTKEY).'icon_tx_gallery_items.gif',
),
"feInterface" => array (
"fe_admin_fieldList" => "hidden, oid, filename, category, videoembedcode, caption, linkpid, categoryId",
)
);
$TCA["tx_gallery_categories"] = array (
"ctrl" => array (
'title' => 'LLL:EXT:gc_gallery/locallang_db.xml:tx_gallery_items',
'label' => 'categoryTitle',
'tstamp' => 'tstamp',
'sortby' => 'sorting',
'delete' => 'deleted',
// 'enablecolumns' => array (
// 'disabled' => 'hidden',
// ),
'dynamicConfigFile' => t3lib_extMgm::extPath($_EXTKEY).'tca.php',
'iconfile' => t3lib_extMgm::extRelPath($_EXTKEY).'icon_tx_gallery_items.gif',
),
// "feInterface" => array (
// "fe_admin_fieldList" => "uid, pid, categoryTitle, categoryDescription, tstamp, sorting, deleted, hidden, categorySlug",
// )
);
So my question is (i think) how can I get the uid from the current image the user is editing and save it to another table.
This is my first try with TCA and I'm very confused on how all this is connected.
I hope that anyone knows this better than me :)
Thanks.
There is the hook concept implemented in the tcemain component. There is one called processDatamap_postProcessFieldArray which is invoked when any record is saved in the backend. Thus, you can check whether it's "yours" and do your other queries or whatever you want to change.
There is an example of how to use this feature. Although it is pretty old, it should still be working that way.