fullstack_webdev

Code and notes from Full stack web developer path, LinkedIn Learning.

View on GitHub

9. Transactions

09_01 What are transactions?

09_02 Data Integrity


-- Create tables
CREATE TABLE widgetInventory (
  id INTEGER PRIMARY KEY,
  description TEXT,
  onhand INTEGER NOT NULL
);

CREATE TABLE widgetSales (
  id INTEGER PRIMARY KEY,
  inv_id INTEGER,
  quan INTEGER,
  price INTEGER
);

-- Insert into widgetInventory
INSERT INTO widgetInventory ( description, onhand ) VALUES ( 'rock', 25 );
INSERT INTO widgetInventory ( description, onhand ) VALUES ( 'paper', 25 );
INSERT INTO widgetInventory ( description, onhand ) VALUES ( 'scissors', 25 );

SELECT * FROM widgetInventory; -- Returns entries inserted above
SELECT * FROM widgetSales; -- Still empty, as no insertion so far in widgetSales table

-- We use transaction to insert in widgetSales and update in widgetInventory
--Begin transaction, we insert into widgetSales and we update widgetInventory to reduce item with id = 1 by 5.
BEGIN TRANSACTION;
INSERT INTO widgetSales ( inv_id, quan, price ) VALUES ( 1, 5, 500 );
UPDATE widgetInventory SET onhand = ( onhand - 5 ) WHERE id = 1;
END TRANSACTION;

--rollback to go to the state before we made changes into widgetInventory
BEGIN TRANSACTION;
INSERT INTO widgetInventory ( description, onhand ) VALUES ( 'toy', 25 );
ROLLBACK;
SELECT * FROM widgetInventory;

-- restore database
DROP TABLE IF EXISTS widgetInventory;
DROP TABLE IF EXISTS widgetSales;

09_03 Performance

DROP TABLE IF EXISTS test;
CREATE TABLE test(id INTEGER PRIMARY KEY, data TEXT);

BEGIN TRANSACTION;
-- COPY THE BELOW INSERT STATEMENT THOUSAND TIMES THEN RUN THE COMPARISON
INSERT INTO TEST (data) VALUES('this is a good sized line of text.');

END TRANSACTION;

SELECT COUNT(*) FROM test;