Monday, July 22, 2013

replace all in file from console


The command is:
sed -i 's/oldString/newString/g' fileToBeReplaced.txt

For MAC the behaviour is more restrictive, and wants to specify an backup file this way:
sed -i.bak 's/oldString/newString/g' fileToBeReplaced.txt

In this case, a backup file ("fileToBeReplaced.txt.bak") will be created.

Thursday, July 18, 2013

SQL FOREIGN KEY Constraints


CREATE TABLE buildings (
  building_no int(11) NOT NULL AUTO_INCREMENT,
  building_name varchar(255) NOT NULL,
  address varchar(355) NOT NULL,
  PRIMARY KEY (building_no)
) ENGINE=InnoDB;

 
CREATE TABLE rooms (
  room_no int(11) NOT NULL AUTO_INCREMENT,
  room_name varchar(255) NOT NULL,
  building_no int(11) NOT NULL,
  PRIMARY KEY (room_no),
  KEY building_no (building_no),
  CONSTRAINT rooms_ibfk_1
    FOREIGN KEY (building_no)
    REFERENCES buildings (building_no)
    ON DELETE CASCADE
) ENGINE=InnoDB;

Wednesday, July 17, 2013

SQL triggers

Syntax:

CREATE TRIGGER trigger_name trigger_time trigger_event
ON table_name
FOR EACH ROW
BEGIN
...
END

Dropping trigger:

DROP TRIGGER table_name.trigger_name
Example 1:

CREATE TABLE account (acct_num INT, amount DECIMAL(10,2));

CREATE TRIGGER ins_sum BEFORE INSERT ON account FOR EACH ROW SET @sum = @sum + NEW.amount;

SET @sum = 0;
mysql> INSERT INTO account VALUES(137,14.98),(141,1937.50),(97,-100.00);
mysql> SELECT @sum AS 'Total amount inserted';

Example 2:

CREATE TRIGGER `tutorial`.`before_delete_carts`
    BEFORE DELETE ON `trigger_carts` FOR EACH ROW
    BEGIN
        DELETE FROM trigger_cart_items WHERE OLD.cart_id = cart_id;
    END
Example 3:

CREATE TRIGGER `after_update_cost`
    AFTER UPDATE ON `trigger_items_cost` FOR EACH ROW
    BEGIN
       UPDATE trigger_items
       SET price = (NEW.cost * 1.3)
       WHERE item_id = NEW.item_id;
    END