By Lloyd Albin 12/3/2013.  Functions The Basics - Languages.

Slides:



Advertisements
Similar presentations
PHP II Interacting with Database Data. The whole idea of a database-driven website is to enable the content of the site to reside in a database, and to.
Advertisements

AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
PL/SQL. Introduction to PL/SQL PL/SQL is the procedure extension to Oracle SQL. It is used to access an Oracle database from various environments (e.g.
Let’s try Oracle. Accessing Oracle The Oracle system, like the SQL Server system, is client / server. For SQL Server, –the client is the Query Analyser.
PHP (2) – Functions, Arrays, Databases, and sessions.
Introduction to Structured Query Language (SQL)
Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
Introduction to Structured Query Language (SQL)
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
Phonegap Bridge – File System CIS 136 Building Mobile Apps 1.
Introduction To Databases IDIA 618 Fall 2014 Bridget M. Blodgett.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Session 5: Working with MySQL iNET Academy Open Source Web Development.
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
HAP 709 – Healthcare Databases SQL Data Manipulation Language (DML) Updated Fall, 2009.
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
1 Definition of a subquery Nested subqueries Correlated subqueries The ISNULL function Derived tables The EXISTS operator Mixing data types: CAST & CONVERT.
Programming in postgreSQL with PL/pgSQL ProceduralLanguageextension topostgreSQL.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Chapter 5 MYSQL Database. Introduction to MYSQL MySQL is the world's most popular open-source database. Open source means that the source code, the programming.
Stored Procedures Week 9. Test Details Stored Procedures SQL can call code written in iSeries High Level Languages –Called stored procedures SQL has.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
ITBIS373 Database Development Lecture 3a - Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
SQL Basic. What is SQL? SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to communicate with a database.
Advanced SQL: Triggers & Assertions
Objectives Database triggers and syntax
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Controlling User Access. 2 home back first prev next last What Will I Learn? Compare the difference between object privileges and system privileges Construct.
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
Using Partial Indexes with PostgreSQL By Lloyd Albin 4/3/2012.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 9 Database Triggers.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
Transactions, Roles & Privileges Oracle and ANSI Standard SQL Lecture 11.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the procedure.
Starting with Oracle SQL Plus. Today in the lab… Connect to SQL Plus – your schema. Set up two tables. Find the tables in the catalog. Insert four rows.
Aggregator Stage : Definition : Aggregator classifies data rows from a single input link into groups and calculates totals or other aggregate functions.
CSC314 DAY 8 Introduction to SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall SQL OVERVIEW  Structured Query Language  The.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
SQL Triggers, Functions & Stored Procedures Programming Operations.
 CONACT UC:  Magnific training   
Programming in postgreSQL with PL/pgSQL ProceduralLanguageextension topostgreSQL 1.
SQL Basics Review Reviewing what we’ve learned so far…….
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
1. Advanced SQL Functions Procedural Constructs Triggers.
Programming in postgreSQL with PL/pgSQL
Trigger used in PosgreSQL
PostgreSQL Conference East 2009
UNIT - V STORED PROCEDURE.
Writing PostgreSQL Functions and how to debug them
CS4222 Principles of Database System
Developing a Model-View-Controller Component for Joomla Part 3
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.

Contents Preface I Introduction Lesson Objectives I-2
Tutorial 6 PHP & MySQL Li Xu
PRACTICE OVERVIEW PL/SQL Part - 1.
Prof. Arfaoui. COM390 Chapter 9
Presentation transcript:

By Lloyd Albin 12/3/2013

 Functions The Basics - Languages

  Pre-Installed Languages:  SQL  C  internal  Installable Languages that come with Postgres:  plpgsql  plperl  plperlu  pltcl  plpython  Other Downloadable Languages:  pljava  plphp  plpy  plr  plruby  plscheme  plsh Languages

  SELECT name, comment FROM pg_available_extensions WHERE comment LIKE '%language%'; Finding Languages that can be Installed NameComment plperlPL/Perl procedural language plperluPL/PerlU untrusted procedural language plpgsqlPL/pgSQL procedural language

      Finding Downloadable Languages NameLanguageWebsite (Postgres 9.2 & 9.3) PL/JavaJavahttp://pljava.projects.postgresql.org/ PL/PHPPHPhttp:// PL/PyPythonhttp://python.projects.postgresql.org/backend/ PL/RRhttp:// PL/RubyRubyhttp://raa.ruby-lang.org/project/pl-ruby/ PL/SchemeSchemehttp://plscheme.projects.postgresql.org/ PL/shUnix shellhttp://plsh.projects.postgresql.org/

  CREATE EXTENSION plperl;  CREATE EXTENSION plperlu;  CREATE EXTENSION plpgsql; How to Install a Language

  DROP EXTENSION plperl;  DROP EXTENSION plperlu;  DROP EXTENSION plpgsql; Uninstalling a Language

 Functions The Basics – Function Behavior

  IMMUTABLE indicates that the function cannot modify the database and always returns the same result when given the same argument values; that is, it does not do database lookups or otherwise use information not directly present in its argument list.  If this option is given, any call of the function with all-constant arguments can be immediately replaced with the function value.  What this means is these types of functions can be used as a type converter or indexer. IMMUTABLE

  STABLE indicates that the function cannot modify the database, and that within a single table scan it will consistently return the same result for the same argument values, but that its result could change across SQL statements.  This is the appropriate selection for functions whose results depend on database lookups, parameter variables (such as the current time zone), etc.  It is inappropriate for AFTER triggers that wish to query rows modified by the current command.  Also note that the current_timestamp family of functions qualify as stable, since their values do not change within a transaction. STABLE

  VOLATILE indicates that the function value can change even within a single table scan, so no optimizations can be made.  Relatively few database functions are volatile in this sense; some examples are random(), currval(), timeofday().  But note that any function that has side-effects must be classified volatile, even if its result is quite predictable, to prevent calls from being optimized away; some example are random(), currval(), timeofday() VOLATILE

 Functions The Basics – NULL INPUT

  CALLED ON NULL INPUT – This is the default if you don’t say anything. You will need to handle the NULL’s within your code.  RETURNS NULL ON NULL INPUT or STRICT – This will cause the function to return NULL when any of the input values are NULL. The body of the function is never executed. What to do with NULL?

 Functions The Basics - SECURITY

  SECURITY INVOKER – This is the default. The function is to be executed with the privileges of the user that calls it.  SECURITY DEFINER – This specifies that the function is to be executed with the privileges of the user that created it. This could be used to have a function update a table that the calling user does not have permissions to access, etc.

 Functions The Basics - Syntax

 CREATE OR REPLACE FUNCTION ( argname text ) RETURNS numeric AS $body$ …. $body$ LANGUAGE 'sql' IMMUTABLE | STABLE | VOLATILE RETURNS NULL ON NULL INPUT SECURITY DEFINER ; CREATE FUNCTION

  void – This is for when the trigger should not return anything. It is just doing some backgroud process for you.  trigger – This must be set for all trigger functions.  boolean, text, etc – This is for a single values being passed back.  SET OF schema.table – This is for returning multiple rows of data. This can either point to an existing table or a composite type to get the table/field layout. Additional Return Types

 Simple Functions Basic SQL functions – Converting a field type

 CREATE TABLE tools.lloyd_test ( mynumber VARCHAR ); ALTER TABLE tools.lloyd_test ALTER COLUMN mynumber TYPE INTEGER COLLATE pg_catalog."default"; ERROR: collations are not supported by type integer Converting a tables field

 ALTER TABLE tools.lloyd_test ALTER COLUMN mynumber TYPE INTEGER USING tools.chartoint(mynumber); Using a function to do the conversion

 CREATE OR REPLACE FUNCTION tools.chartoint ( chartoconvert varchar ) RETURNS integer AS $body$ SELECT CASE WHEN trim(chartoconvert) SIMILAR TO '[0-9,]+' THEN CAST(trim(REPLACE(chartoconvert,',','')) AS integer) ELSE NULL END; $body$ LANGUAGE 'sql' IMMUTABLE RETURNS NULL ON NULL INPUT SECURITY INVOKER; Convert varchar to int

 CREATE OR REPLACE FUNCTION tools.chartonumeric ( chartoconvert varchar ) RETURNS numeric AS $body$ SELECT CASE WHEN trim(chartoconvert) SIMILAR TO '[0-9,.-]+' THEN CAST(trim(REPLACE(chartoconvert,',','')) AS integer) ELSE NULL END; $body$ LANGUAGE 'sql' IMMUTABLE RETURNS NULL ON NULL INPUT SECURITY INVOKER; Convert varchar to int

 Simple Functions Basic PL/pgSQL functions – Using as an index

  We receive faxes that are multi-page TIFF’s. The TIFF file name are called the raster id. We have data where we have the full path of the file name, the raster id and the raster id with page number.  Examples:  0000/  0000/  /studydata/studyname/0000/ The Problem

 The first thing to do, is to be able to find the Raster ID, no matter which format is supplied. CREATE FUNCTION find_raster (raster varchar) RETURNS VARCHAR(11) AS $$ BEGIN CASE length(raster) WHEN 11 THEN -- Format: 1234/ Returns: 1234/ RETURN raster; WHEN 15 THEN -- Format: 1234/ Returns: 1234/ RETURN substr(raster, 1, 11); ELSE -- Format: /study_data/study_name/1234/ Returns: 1234/ RETURN substr(raster, length(raster)-10, 11); END CASE; END; $$ LANGUAGE plpgsql IMMUTABLE RETURNS NULL ON NULL INPUT; Finding the Raster ID

 -- Test returning of Raster ID when Submitting Raster ID SELECT find_raster('1234/567890'); -- Returns: 1234/ Test returning of Raster ID when Submitting Raster ID with 4 Digit Page Number SELECT find_raster('1234/ '); -- Returns: 1234/ Test returning of Raster ID when Submitting Filename that includes Raster ID SELECT find_raster('/study_data/study_name/1234/567890'); -- Returns: 1234/ Examples of the find_raster Function

 CREATE INDEX [ name ] ON table ( expression ) expression An expression based on one or more columns of the table. The expression usually must be written with surrounding parentheses, as shown in the syntax. However, the parentheses can be omitted if the expression has the form of a function call. CREATE INDEX raster_raster_idx ON raster find_raster(raster); CREATE INDEX raster_file_raster_idx ON raster_file find_raster(raster); CREATE INDEX raster_page_raster_idx ON raster_page find_raster(raster); Adding the Index

 The benefits of the Index Without Index SELECT raster.*, raster_page.* FROM (SELECT * FROM raster OFFSET LIMIT 100) raster LEFT JOIN raster_page ON raster.raster = substr(raster_page.raster, 1, 11);  Total runtime: ms  Total runtime: s With Index SELECT raster.*, raster_page.* FROM (SELECT * FROM raster OFFSET LIMIT 100) raster LEFT JOIN raster_page ON raster.raster = find_raster(raster_page.raster);  Total runtime: ms  Total runtime: s

 Simple Functions Basic PL/pgSQL functions – Triggers

  Sometimes we want to have a copy of a table and know when everything happened to the original table, insert, update, delete, and truncate. This is possible to have happen automatically with a trigger function. Shadow Tables

  Table 1 CREATE TABLE public.table1 ( key SERIAL, value INTEGER, value_type VARCHAR, PRIMARY KEY(key) ) ;  Table 2 CREATE TABLE public.table2 ( key INTEGER, value INTEGER, value_type VARCHAR, user_name NAME, action VARCHAR, action_time TIMESTAMP ) ; Creating the base tables

 CREATE FUNCTION public.shadow_table1 ( ) RETURNS trigger AS $body$ BEGIN IF TG_OP = 'INSERT' THEN INSERT INTO public.table2 VALUES(NEW.key, NEW.value, NEW.value_type, current_user, TG_OP, now()); RETURN NEW; END IF; IF TG_OP = 'UPDATE' THEN INSERT INTO public.table2 VALUES(NEW.key, NEW.value, NEW.value_type, current_user, TG_OP, now()); RETURN NEW; END IF; IF TG_OP = 'DELETE' THEN INSERT INTO public.table2 VALUES(OLD.key, OLD.value, OLD.value_type, current_user, TG_OP, now()); RETURN OLD; END IF; END; $body$ LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY DEFINER; The Shadow Function

 CREATE TRIGGER table1_tr BEFORE INSERT OR UPDATE OR DELETE ON public.table1 FOR EACH ROW EXECUTE PROCEDURE public.shadow_table1(); Adding the trigger to the table

 INSERT INTO public.table1 (value, value_type) VALUES ('30', 'meters'); INSERT INTO public.table1 (value, value_type) VALUES ('10', 'inches'); UPDATE public.table1 SET value = '20' WHERE value_type = 'inches'; DELETE FROM public.table1 WHERE value_type = 'inches'; INSERT INTO public.table1 (value, value_type) VALUES ('50', 'inches'); Working with Table1

 What they look like Table1 keyvaluevalue_type 130meters 350inches Table2 keyvaluevalue_typeuser_nameactionaction_time 130meterspostgresINSERT12/3/2013 4:58:04 PM 210inchespostgresINSERT12/3/2013 4:58:04 PM 220inchespostgresUPDATE12/3/2013 4:58:04 PM 220inchespostgresDELETE12/3/2013 4:58:04 PM 350inchespostgresINSERT12/3/2013 4:58:04 PM

 Simple Functions Basic PL/pgSQL functions – Write to a hidden table

  Sometimes you may want a normal user to be able to write a table, but that user also not be able to view/select any contents from the table aka INSERT only.  This does not play with some front end applications.  Some people will write functions where you pass in the variables, but that is not always possible depending on the front end that is being written. Hidden Tables

  Table 1 SET ROLE a; CREATE TABLE public.table1 ( key SERIAL, value INTEGER, value_type VARCHAR, PRIMARY KEY(key) ) ;  Table 2 SET ROLE b; CREATE TABLE public.table2 ( key INTEGER, value INTEGER, value_type VARCHAR, PRIMARY KEY(key) ) ; Creating the base tables

 SET ROLE b; CREATE FUNCTION public.hidden_table1 ( ) RETURNS trigger AS $body$ BEGIN INSERT INTO public.table2 VALUES(NEW.key, NEW.value, NEW.value_type); RETURN NULL; END; $body$ LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY DEFINER; The Hidden Function

 CREATE TRIGGER table1_tr BEFORE INSERT ON public.table1 FOR EACH ROW EXECUTE PROCEDURE public.hidden_table1(); Adding the trigger to the table

 INSERT INTO public.table1 (value, value_type) VALUES ('30', 'meters'); INSERT INTO public.table1 (value, value_type) VALUES ('10', 'inches'); INSERT INTO public.table1 (value, value_type) VALUES ('50', 'inches'); Working with Table1

 What they look like Table1 keyvaluevalue_type Table2 keyvaluevalue_type 130meters 210inches 350inches

 Simple Functions Basic PL/pgSQL functions – Returning a Table

 CREATE OR REPLACE FUNCTION tools.count_schema_rows (search_schema_name name) RETURNS SETOF tools.schema_row_count AS $body$ DECLARE schema_results RECORD; table_results RECORD; BEGIN FOR schema_results IN SELECT table_schema, table_name FROM information_schema.tables WHERE table_schema = search_schema_name AND table_type = 'BASE TABLE' ORDER BY table_name LOOP -- looping through tables in schema here EXECUTE 'SELECT ' || quote_literal(schema_results.table_schema) || '::NAME AS schema_name, ' || quote_literal(schema_results.table_name) || '::NAME AS table_name, count(*), pg_total_relation_size(''' || schema_results.table_schema || '.' || schema_results.table_name || ''') AS total_size, pg_size_pretty(pg_total_relation_size(''' || schema_results.table_schema || '.' || schema_results.table_name || ''')) AS total_size_pretty FROM ' || quote_ident(schema_results.table_schema) || '.' || quote_ident(schema_results.table_name) INTO table_results; RETURN NEXT table_results; END LOOP; END; $body$ LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY DEFINER; Counting the tables

  SELECT * FROM tools.count_schema_rows ('dffax'); Counting the tables schema_nametable_namerow_counttotal_sizetotal_size_pretty dffaxdfx_time1_p MB dffaxdfx_time1_h MB dffaxdfx_time1_m MB

By Lloyd Albin 1/7/2014

  Materialized Views  Single Table Shadow functions.  Lookup User Dependencies  Update sequences for an entire schema Sample of Functions