Yii2 Question: Is there any way to get the current insert query before executing save? for instance $model->save(). For the current situation, save is actually inserting a row in a table.
I know about executing function beforeSave($insert) but this $insert only refers whether the event is valid or not, and does extra computation before saving in database.
Misc stuff: Find query can be printed as $FindResultVariable->prepare(Yii::$app->db->queryBuilder)->createCommand()->rawSql; If someone can think in this direction too for solution?Thanks.
$model->insert();
This inserts the values before save.
Related
I was just curious if it was possible to configure a trigger that would watch for table updates and then:
Look at the row with the new data.
Grab the new data.
Run the data through a series of rules.
If the data doesn't follow a rule then revert the entire row back before the update.
Else do nothing.
Create a trigger as you normally would. Here is a good breakdown of the structure of a trigger: http://www.tutorialspoint.com/plsql/plsql_triggers.htm
You can use the :NEW attribute to access the new data being entered, store it in a variable (if you choose), then execute your validation on the data. If it doesn't pass any of them then raise and error; that will exit the trigger and not update the field with the new data.
For more information on exceptions in triggers see: http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/triggers.htm#LNPLS751
Hope this helps.
I have a query that runs everytime a user logins. Since this query regards information the user might have third-party updated recently I thought it would be a good idea to turn the user_id + information combo in the table unique. As so, everytime a user tried to save new information it would only save the one information I already didn't have. So, the first query being
INSERT INTO table VALUES ("1","cake"),("1","pie"),("1","bedsheets")
And as the user logins a second time and it being
INSERT INTO table VALUES ("1","cake"),("1","pie"),("1","bedsheets"),("1","chocolate")
It would only save ("1","chocolate") because (id,info) being an unique pair all other would not be inserted. I came upon the realization they all fail if only one fails. So my question is: is there any way to override this operation? Or do I have to query the db first to filter the information I already have? tyvm...
When you use the IGNORE Keyword, so every errors, in the execution are ignored. Example: if you have a duplicate or PRIMARY key error while executing a INSERT Statement, so it will ignored and the execution is not aborted
Use this:
I NSERT IGNORE INTO table VALUES ("1","cake"),("1","pie"),("1","bedsheets"),("1","chocolate");
Hypothetically, I am going to develop a trigger that inserts a record to Table A when an insertion made to an Table A.
Therefore, I want to know how the system handles that kind of loophole or it is going to continue as a loop until the system hangs which requires restart and possibly remove the DB.
I'm trying to gather information on almost every DBMS on this issue or loophole.
I can only speak to Oracle, I know nothing of MySQL.
In Oracle, this situation is known as mutation. Oracle will not spiral into an endless loop. It will detect the condition, and raise an ORA-04091 error.
That is:
ORA-04091: table XXXX is mutating, trigger/function may not see it
The standard solution is to define a package with three functions and a package level array. The three functions are as follows:
initialize - this will only zero out the array.
save_row - this will save the id of the current row (uk or pk) into the arrray.
process_rows - this will go through the array, and actually do the trigger action for each row.
Now, define some trigger actions:
statement level BEFORE: call initialize
row level BEFORE or AFTER: call save_row
statement level AFTER: call process_rows
In this way, Oracle can avoid mutation, and your trigger will work.
More details and some sample code can be found here:
https://asktom.oracle.com/pls/asktom/ASKTOM.download_file?p_file=6551198119097816936
You can only insert a record in same table if you are using instead of trigger. In all other cases you can only modify the record being inserted.
I hope this answers your quest.
you can create trigger in mysql DBMS.
check below link for create insert trigger syntex
http://www.techonthenet.com/oracle/triggers/after_insert.php
I have so many tables in my DB.
eg. user, organisation,etc.
**User**
userId,name,age,orgId,etc..
**SessionLog**
logId, userId, operations, reason
If one admin makes changes like inserting, updating ,deleting, I will log every operations in SessionLog table WHAT he made.
So I plan to use Trigger.But the problem is I want to log the userId for WHO too. By using Trigger WHAT is OK. But for logging WHO, how can I do ?
1) do I need to retrieve the logId and need to update the row with WHO?
or
2) just use the simple INSERT statement to log everything? which way is better?
3) Is there any way to pass desired parameters to Trigger?
Thanks.
1. User
You can use CURRENT_USER to get this. http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_current-user
2. Insert statement vs. Trigger
A trigger will abstract logging away from everybody else, and usually is the easiest solution that stays hidden.
INSERTS / UPDATES will not return until the trigger has completed.
Therefore while triggers on tables with light activity is an OK idea, it will become a real hindrance when dealing with tables that have a lot of activity.
Another option is to encapsulate this in the data access layer, but if you have even a single user that has direct access to the data (DBA included) then I do not recommend this approach.
I am working on a web app project and there is a rather large html form that needs to have its data stored in a table. The form and insert are already done but my client wants to be able to load the saved data back into the HTML form and be able to change it, again, this is no problem, but I came across a question when going to do the update, would it be appropriate to just keep the insert query and then delete the old row if it was an edit?
Basically, what already happens is when the form is submitted all of the data is put into a table using INSERT, I also have a flag called edit that contains the primary key ID if the data is for an existing field being updated. I can handle the update function two ways:
a) Create an actual update query with all the fields/data set and use an if/else to decide whether to run the update or insert query.
b) Do the insert every time but add a single line to DELETE WHERE row=editID after the insert is successful.
Since the Delete would only happen if the INSERT was successful I don't run the risk of deleting the data without inserting, thus losing the data, but since INSERT/DELETE is two queries, would it be less efficient than just using an if/else to decide whether to run an insert or update?
There is a second table that uses the auto-increment id as a foreign key, but this table has to be updated every time the form is submitted, so if I delete the row in table A, I will also be deleting the associated rows from table b. This seems like it would be bad programming practice, so I am leaning towards option a) anyway, but it is very tempting just to use the single line option. The DELETE would basically be as follows. Would this in fact be bad programming practice? Aside from conventions, are there any reasons why this is a "never do that!" type of code?
if ($insertFormResults) {
$formId = mysql_insert_id();
echo "Your form was saved successfully.";
if(isset($_POST['edit'])){
$query = "DELETE FROM registerForm WHERE id='$_POST[edit]'";
$result = mysql_query($query);
}
}
Whilst the INSERT/DELETE option would work perfectly well I'd recommend against it as:
Unless you bundle the INSERT/DELETE
up into a single transaction, or
better yet encapsulate the
INSERT/DELETE up into a stored
procedure you do run the theoretical
risk of accumulating duplicates. If
you use a SP or a transaction you're
just effectively rewriting the UPDATE
statement which is obviously
inefficient and moreover will give
rise to a few WTF raised eyebrows
later by anyone maintaining your
code.
Although it doesn't sound like an
issue in your case you are
potentially impacting referential
integrity should you need that.
Furthermore you are loosing the
rather useful ability to easily
retrieve records in creation order.
Probably not a great consideration on
a small application, but you are
going to end up with a seriously
fragmented database fairly quickly
which will slow data retrieval.
Update is only one round trip to the server, which is more efficient. Unless you have a reason that involves the possibility of bad data, always default to using an UPDATE.
It seems to me that doing the delete is pointless, if you run an update in MySql it will only update the record if it is different that what is stored already, is there some reason why you would need to do a delete instead. I usually use a case(switch) to catch update/delete calls from the user,
<?php
switch (action) {
case "delete" :
block of coding;
if the condition equals value1;
break;
case "edit" :
block of coding;
if the condition equals value2;
break;
}
?>