Extracting META information from Interbase/Firebird SQL (INFORMATION_SCHEMA)



Similar documents
How To Create A Table In Sql (Ahem)

SQL. Short introduction

Schema Evolution in SQL-99 and Commercial (Object-)Relational DBMS

Physical Design. Meeting the needs of the users is the gold standard against which we measure our success in creating a database.

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

A basic create statement for a simple student table would look like the following.

Linas Virbalas Continuent, Inc.

!"# $ %& '( ! %& $ ' &)* + ! * $, $ (, ( '! -,) (# *&23. mysql> select * from from clienti;

A Brief Introduction to MySQL

In This Lecture. SQL Data Definition SQL SQL. Notes. Non-Procedural Programming. Database Systems Lecture 5 Natasha Alechina

Oracle Database 10g Express

MS ACCESS DATABASE DATA TYPES

The Relational Model. Why Study the Relational Model?

Services. Relational. Databases & JDBC. Today. Relational. Databases SQL JDBC. Next Time. Services. Relational. Databases & JDBC. Today.

CSC 443 Data Base Management Systems. Basic SQL

Database Migration from MySQL to RDM Server

SQL Server An Overview

Geodatabase Programming with SQL

The Relational Model. Ramakrishnan&Gehrke, Chapter 3 CS4320 1

MySQL for Beginners Ed 3

Introduction to SQL and database objects

EECS 647: Introduction to Database Systems

Intro to Databases. ACM Webmonkeys 2011

4 Simple Database Features

Using SQL Server Management Studio

Financial Data Access with SQL, Excel & VBA

Introduction to Database. Systems HANS- PETTER HALVORSEN,

SQL DATA DEFINITION: KEY CONSTRAINTS. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 7

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

The Relational Model. Why Study the Relational Model? Relational Database: Definitions

Database Administration with MySQL

Conventional Files versus the Database. Files versus Database. Pros and Cons of Conventional Files. Pros and Cons of Databases. Fields (continued)

database abstraction layer database abstraction layers in PHP Lukas Smith BackendMedia

2/3/04 Doc 7 SQL Part 1 slide # 1

Managing Objects with Data Dictionary Views. Copyright 2006, Oracle. All rights reserved.

Programming with SQL

Database Query 1: SQL Basics

Structured Query Language. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics

Mul$media im Netz (Online Mul$media) Wintersemester 2014/15. Übung 03 (Nebenfach)

A table is a collection of related data entries and it consists of columns and rows.

SQL Databases Course. by Applied Technology Research Center. This course provides training for MySQL, Oracle, SQL Server and PostgreSQL databases.

The Relational Model. Why Study the Relational Model? Relational Database: Definitions. Chapter 3

IT2304: Database Systems 1 (DBS 1)

New Features in MySQL 5.0, 5.1, and Beyond

Programming Database lectures for mathema

Information Technology NVEQ Level 2 Class X IT207-NQ2012-Database Development (Basic) Student s Handbook


VBA and Databases (see Chapter 14 )

In This Lecture. Security and Integrity. Database Security. DBMS Security Support. Privileges in SQL. Permissions and Privilege.

IT2305 Database Systems I (Compulsory)

Lecture 6. SQL, Logical DB Design

DBMS / Business Intelligence, SQL Server

Language Reference Guide

Ch.5 Database Security. Ch.5 Database Security Review

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

6 CHAPTER. Relational Database Management Systems and SQL Chapter Objectives In this chapter you will learn the following:

CSI 2132 Lab 3. Outline 09/02/2012. More on SQL. Destroying and Altering Relations. Exercise: DROP TABLE ALTER TABLE SELECT

Information Systems SQL. Nikolaj Popov

Basic Concepts of Database Systems

Creating Database Tables in Microsoft SQL Server

DbSchema Tutorial with Introduction in SQL Databases

Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.

4 Logical Design : RDM Schema Definition with SQL / DDL

Microsoft SQL Server to Infobright Database Migration Guide

Database Design and Programming

php tek 2006 in Orlando Florida Lukas Kahwe Smith

SQL Server. 1. What is RDBMS?

types, but key declarations and constraints Similar CREATE X commands for other schema ëdrop X name" deletes the created element of beer VARCHARè20è,

Data Generator for SQL Server User's Manual EMS Database Management Solutions

DBMS Questions. 3.) For which two constraints are indexes created when the constraint is added?

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

B.1 Database Design and Definition

Relational databases and SQL

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

Fundamentals of Database Design

Database Systems. S. Adams. Dilbert. Available: Hans-Petter Halvorsen, M.Sc.

ICAB4136B Use structured query language to create database structures and manipulate data

Lab 2: PostgreSQL Tutorial II: Command Line

Oracle Database 10g: Introduction to SQL

Chapter 6: Physical Database Design and Performance. Database Development Process. Physical Design Process. Physical Database Design

"SQL Database Professional " module PRINTED MANUAL

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

Zero Downtime Deployments with Database Migrations. Bob Feldbauer

Computer Security: Principles and Practice

Databases in Engineering / Lab-1 (MS-Access/SQL)

SQL Data Definition. Database Systems Lecture 5 Natasha Alechina

Bidirectional replication for InterBase and Firebird

Instant SQL Programming

History of SQL. Relational Database Languages. Tuple relational calculus ALPHA (Codd, 1970s) QUEL (based on ALPHA) Datalog (rule-based, like PROLOG)

XEP-0043: Jabber Database Access

Advance DBMS. Structured Query Language (SQL)

and what does it have to do with accounting software? connecting people and business

Advanced SQL. Jim Mason. Web solutions for iseries engineer, build, deploy, support, train

MySQL Command Syntax

SQL Injection. The ability to inject SQL commands into the database engine through an existing application

Database Management Systems Comparative Study: Performances of Microsoft SQL Server Versus Oracle

Procedural Extension to SQL using Triggers. SS Chung

Elena Baralis, Silvia Chiusano Politecnico di Torino. Pag. 1. Active database systems. Triggers. Triggers. Active database systems.

Transcription:

13 November 2007 22:30 Extracting META information from Interbase/Firebird SQL (INFORMATION_SCHEMA) By: http://www.alberton.info/firebird_sql_meta_info.html The SQL 2003 Standard introduced a new schema called INFORMATION_SCHEMA. PostgreSQL, SQL Server and now MySQL have it. ORACLE, DB2, Sybase, Ingres, Informix and other DBMS have something similar, usually called System Tables. The INFORMATION_SCHEMA is meant to be a set of views you can query using regular SELECT statements, for instance if you need to know something about the defined triggers, or the structure of a table to which you have access. Firebird doesn't have it, but you can retrieve pretty much everything you need from the system tables. These are metadata tables, their names start with "RDB$". Let's see how we can retrieve some useful informations from them. Test data We need a few sample tables, indices and views to test the following queries, so let's create them. We also create a sample TRIGGER to emulate the autoincrement feature of mysql, and a simple stored procedure. -- sample data to test Firebird system tables -- TABLE TEST CREATE TABLE TEST ( TEST_NAME CHAR(30) CHARACTER SET NONE NOT NULL COLLATE NONE, TEST_ID INTEGER DEFAULT '0' NOT NULL, TEST_DATE TIMESTAMP NOT NULL ALTER TABLE TEST ADD CONSTRAINT PK_TEST PRIMARY KEY (TEST_ID -- TABLE TEST2 with some CONSTRAINTs and an INDEX CREATE TABLE TEST2 ( ID INTEGER NOT NULL, FIELD1 INTEGER, FIELD2 CHAR(15) CHARACTER SET NONE COLLATE NONE, FIELD3 VARCHAR(50) CHARACTER SET NONE COLLATE NONE, FIELD4 INTEGER, FIELD5 INTEGER, ID2 INTEGER NOT NULL ALTER TABLE TEST2 ADD CONSTRAINT PRIMARY KEY (ID2 CREATE UNIQUE INDEX TEST2_FIELD1ID_IDX ON TEST2(ID, FIELD1 CREATE UNIQUE INDEX TEST2_FIELD4_IDX ON TEST2(FIELD4 CREATE INDEX TEST2_FIELD5_IDX ON TEST2(FIELD5 -- TABLE NUMBERS CREATE TABLE NUMBERS ( NUMBER INTEGER DEFAULT '0' NOT NULL, EN CHAR(100) CHARACTER SET ISO8859_1 NOT NULL COLLATE ISO8859_1, FR CHAR(100) CHARACTER SET ISO8859_1 NOT NULL COLLATE ISO8859_1 -- TABLE NEWTABLE CREATE TABLE NEWTABLE ( ID INT DEFAULT 0 NOT NULL, SOMENAME VARCHAR (12), SOMEDESCRIPTION VARCHAR (12) ALTER TABLE NEWTABLE ADD CONSTRAINT PKINDEX_IDX PRIMARY KEY (ID

CREATE GENERATOR NEWTABLE_SEQ; -- VIEW on TEST CREATE VIEW "testview"( TEST_NAME, TEST_ID, TEST_DATE ) AS SELECT * FROM TEST WHERE TEST_NAME LIKE 't%'; -- VIEW on NUMBERS CREATE VIEW "numbersview"( NUM, EN, FR ) AS SELECT * FROM NUMBERS WHERE NUMBER > 100; -- TRIGGER on NEWTABLE (emulate autoincrement) SET TERM ^ ; CREATE TRIGGER AUTOINCREMENTPK FOR NEWTABLE ACTIVE BEFORE INSERT POSITION 0 AS BEGIN IF (NEW.ID IS NULL OR NEW.ID = 0) THEN NEW.ID = GEN_ID(NEWTABLE_SEQ, 1 END^ SET TERM ; ^ -- SAMPLE STORED PROCEDURE SET TERM ^ ; CREATE PROCEDURE getenglishnumber(n INTEGER) RETURNS ( english_number CHAR(100) ) AS BEGIN FOR SELECT EN FROM NUMBERS WHERE NUMBER = :N INTO :english_number DO BEGIN SUSPEND; END END ^ SET TERM ; ^ List TABLEs Here's the query that will return the names of the tables defined in the current database: SELECT DISTINCT RDB$RELATION_NAME

FROM RDB$RELATION_FIELDS WHERE RDB$SYSTEM_FLAG=0; -- or SELECT RDB$RELATION_NAME FROM RDB$RELATIONS WHERE RDB$SYSTEM_FLAG=0; NB: the above queries will list both the user defined tables AND views. To exclude the VIEWs from the resultset, you can write one of these queries: SELECT DISTINCT RDB$RELATION_NAME FROM RDB$RELATION_FIELDS WHERE RDB$SYSTEM_FLAG=0 AND RDB$VIEW_CONTEXT IS NULL; -- or SELECT RDB$RELATION_NAME FROM RDB$RELATIONS WHERE RDB$SYSTEM_FLAG=0 AND RDB$VIEW_BLR IS NULL; List VIEWs Here's the query that will return the names of the VIEWs defined in the current database: SELECT DISTINCT RDB$VIEW_NAME FROM RDB$VIEW_RELATIONS; -- show only the VIEWs referencing a given table SELECT DISTINCT RDB$VIEW_NAME FROM RDB$VIEW_RELATIONS WHERE RDB$RELATION_NAME='TEST'; List users SELECT DISTINCT RDB$USER FROM RDB$USER_PRIVILEGES; List INDICES Here's the query that will return the names of the INDICES defined in the TEST2 table. NB: the CONSTRAINTs are not listed SELECT RDB$INDEX_NAME FROM RDB$INDICES WHERE RDB$RELATION_NAME='TEST2' AND RDB$UNIQUE_FLAG IS NULL AND RDB$FOREIGN_KEY IS NULL; Detailed INDEX info If you want to know which table columns are referenced by an index, try with this query: SELECT RDB$INDEX_SEGMENTS.RDB$FIELD_NAME AS field_name,

RDB$INDICES.RDB$DESCRIPTION AS description, (RDB$INDEX_SEGMENTS.RDB$FIELD_POSITION + 1) AS field_position FROM RDB$INDEX_SEGMENTS LEFT JOIN RDB$INDICES ON RDB$INDICES.RDB$INDEX_NAME = RDB$INDEX_SEGMENTS.RDB$INDEX_NAME LEFT JOIN RDB$RELATION_CONSTRAINTS ON RDB$RELATION_CONSTRAINTS.RDB$INDEX_NAME = RDB$INDEX_SEGMENTS.RDB$INDEX_NAME WHERE UPPER(RDB$INDICES.RDB$RELATION_NAME)='TEST2' -- table name AND UPPER(RDB$INDICES.RDB$INDEX_NAME)='TEST2_FIELD5_IDX' -- index name AND RDB$RELATION_CONSTRAINTS.RDB$CONSTRAINT_TYPE IS NULL ORDER BY RDB$INDEX_SEGMENTS.RDB$FIELD_POSITION List CONSTRAINTs Here's the query that will return the names of the CONSTRAINTs defined in the TEST2 table: SELECT RDB$INDEX_NAME FROM RDB$INDICES WHERE RDB$RELATION_NAME='TEST2' -- table name AND ( RDB$UNIQUE_FLAG IS NOT NULL OR RDB$FOREIGN_KEY IS NOT NULL List table fields Here's the query that will return the names of the fields of the TEST2 table: SELECT RDB$FIELD_NAME FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME='TEST2'; If you want some more info about the field definitions, you can retrieve a larger subset of the fields available in the RDB$RELATIONS_FIELDS table: SELECT RDB$FIELD_NAME AS field_name, RDB$FIELD_POSITION AS field_position, RDB$DESCRIPTION AS field_description, RDB$DEFAULT_VALUE AS field_default_value, RDB$NULL_FLAG AS field_not_null_constraint FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME='TEST2'; -- table name Detailed table field info If you want a really detailed description of the field, you have to join the RDB$RELATIONS_FIELDS table with RDB$FIELDS: SELECT r.rdb$field_name AS field_name, r.rdb$description AS field_description, r.rdb$default_value AS field_default_value, r.rdb$null_flag AS field_not_null_constraint, f.rdb$field_length AS field_length, f.rdb$field_precision AS field_precision, f.rdb$field_scale AS field_scale, CASE f.rdb$field_type WHEN 261 THEN 'BLOB' WHEN 14 THEN 'CHAR' WHEN 40 THEN 'CSTRING'

WHEN 11 THEN 'D_FLOAT' WHEN 27 THEN 'DOUBLE' WHEN 10 THEN 'FLOAT' WHEN 16 THEN 'INT64' WHEN 8 THEN 'INTEGER' WHEN 9 THEN 'QUAD' WHEN 7 THEN 'SMALLINT' WHEN 12 THEN 'DATE' WHEN 13 THEN 'TIME' WHEN 35 THEN 'TIMESTAMP' WHEN 37 THEN 'VARCHAR' ELSE 'UNKNOWN' END AS field_type, f.rdb$field_sub_type AS field_subtype, coll.rdb$collation_name AS field_collation, cset.rdb$character_set_name AS field_charset FROM RDB$RELATION_FIELDS r LEFT JOIN RDB$FIELDS f ON r.rdb$field_source = f.rdb$field_name LEFT JOIN RDB$COLLATIONS coll ON f.rdb$collation_id = coll.rdb$collation_id LEFT JOIN RDB$CHARACTER_SETS cset ON f.rdb$character_set_id = cset.rdb$character_set_id WHERE r.rdb$relation_name='test2' -- table name ORDER BY r.rdb$field_position; List GENERATORs (sequences) A GENERATOR is a sequential number that can be automatically inserted in a column with the GEN_ID() function. A GENERATOR is often used to ensure a unique value in a PRIMARY KEY that must uniquely identify the associated row. SELECT RDB$GENERATOR_NAME FROM RDB$GENERATORS WHERE RDB$SYSTEM_FLAG IS NULL; List TRIGGERs SELECT * FROM RDB$TRIGGERS WHERE RDB$SYSTEM_FLAG IS NULL; -- list only the triggers for a given table SELECT * FROM RDB$TRIGGERS WHERE RDB$SYSTEM_FLAG IS NULL AND RDB$RELATION_NAME='NEWTABLE'; -- table name List FUNCTIONs (UDF) SELECT * FROM RDB$FUNCTIONS WHERE RDB$SYSTEM_FLAG IS NULL; List Stored Procedures SELECT * FROM RDB$PROCEDURES; List FOREIGN KEY constraints As a bonus, I'm going to show how to get more information for the FOREIGN KEY constraints on a table, i.e.

one query that returns the FK names, the names of the table and field they're tied to, the names of the table and field they reference and the action on update/delete. These are the two test tables and the FK constraint: CREATE TABLE "a" ( "id" INTEGER NOT NULL, "name" VARCHAR(20) DEFAULT '' NOT NULL ALTER TABLE "a" ADD PRIMARY KEY ("id" CREATE TABLE "b" ( "id" INTEGER NOT NULL, "a_id" INTEGER DEFAULT 0 NOT NULL ALTER TABLE "b" ADD PRIMARY KEY ("id" ALTER TABLE "b" ADD CONSTRAINT "FK_b" FOREIGN KEY ("a_id") REFERENCES "a"("id") ON DELETE CASCADE ON UPDATE CASCADE; And this is the query that will return the above mentioned values (replace the table name in the last line to get the FK definitions relative to another table): SELECT DISTINCT rc.rdb$constraint_name AS "constraint_name", rc.rdb$relation_name AS "on table", d1.rdb$field_name AS "on field", d2.rdb$depended_on_name AS "references table", d2.rdb$field_name AS "references field", refc.rdb$update_rule AS "on update", refc.rdb$delete_rule AS "on delete" FROM RDB$RELATION_CONSTRAINTS AS rc LEFT JOIN RDB$REF_CONSTRAINTS refc ON rc.rdb$constraint_name = refc.rdb$constraint_name LEFT JOIN RDB$DEPENDENCIES d1 ON d1.rdb$depended_on_name = rc.rdb$relation_name LEFT JOIN RDB$DEPENDENCIES d2 ON d1.rdb$dependent_name = d2.rdb$dependent_name WHERE rc.rdb$constraint_type = 'FOREIGN KEY' AND d1.rdb$depended_on_name <> d2.rdb$depended_on_name AND d1.rdb$field_name <> d2.rdb$field_name AND rc.rdb$relation_name = 'b' -- table name Detailed CONSTRAINT info If you want to retrieve detailed info from any constraint (fields, type, rules, referenced table and fields for FOREIGN KEYs, etc.) given its name and table, here's the query to do so: SELECT rc.rdb$constraint_name, s.rdb$field_name AS field_name, rc.rdb$constraint_type AS constraint_type, i.rdb$description AS description, rc.rdb$deferrable AS is_deferrable, rc.rdb$initially_deferred AS is_deferred, refc.rdb$update_rule AS on_update, refc.rdb$delete_rule AS on_delete, refc.rdb$match_option AS match_type, i2.rdb$relation_name AS references_table, s2.rdb$field_name AS references_field, (s.rdb$field_position + 1) AS field_position FROM RDB$INDEX_SEGMENTS s LEFT JOIN RDB$INDICES i ON i.rdb$index_name = s.rdb$index_name

LEFT JOIN RDB$RELATION_CONSTRAINTS rc ON rc.rdb$index_name = s.rdb$index_name LEFT JOIN RDB$REF_CONSTRAINTS refc ON rc.rdb$constraint_name = refc.rdb$constraint_name LEFT JOIN RDB$RELATION_CONSTRAINTS rc2 ON rc2.rdb$constraint_name = refc.rdb$const_name_uq LEFT JOIN RDB$INDICES i2 ON i2.rdb$index_name = rc2.rdb$index_name LEFT JOIN RDB$INDEX_SEGMENTS s2 ON i2.rdb$index_name = s2.rdb$index_name WHERE i.rdb$relation_name='b' -- table name AND rc.rdb$constraint_name='fk_b' -- constraint name AND rc.rdb$constraint_type IS NOT NULL ORDER BY s.rdb$field_position Detailed TRIGGER info SELECT RDB$TRIGGER_NAME AS trigger_name, RDB$RELATION_NAME AS table_name, RDB$TRIGGER_SOURCE AS trigger_body, CASE RDB$TRIGGER_TYPE WHEN 1 THEN 'BEFORE' WHEN 2 THEN 'AFTER' WHEN 3 THEN 'BEFORE' WHEN 4 THEN 'AFTER' WHEN 5 THEN 'BEFORE' WHEN 6 THEN 'AFTER' END AS trigger_type, CASE RDB$TRIGGER_TYPE WHEN 1 THEN 'INSERT' WHEN 2 THEN 'INSERT' WHEN 3 THEN 'UPDATE' WHEN 4 THEN 'UPDATE' WHEN 5 THEN 'DELETE' WHEN 6 THEN 'DELETE' END AS trigger_event, CASE RDB$TRIGGER_INACTIVE WHEN 1 THEN 0 ELSE 1 END AS trigger_enabled, RDB$DESCRIPTION AS trigger_comment FROM RDB$TRIGGERS WHERE UPPER(RDB$TRIGGER_NAME)='AUTOINCREMENTPK' Detailed VIEW info If, given a VIEW name, you want to retrieve the field aliases and the field names in the original table, you can run this query: SELECT d.rdb$dependent_name AS view_name, r.rdb$field_name AS field_name, d.rdb$depended_on_name AS depended_on_table, d.rdb$field_name AS depended_on_field FROM RDB$DEPENDENCIES d LEFT JOIN RDB$RELATION_FIELDS r ON d.rdb$dependent_name = r.rdb$relation_name AND d.rdb$field_name = r.rdb$base_field WHERE UPPER(d.RDB$DEPENDENT_NAME)='NUMBERSVIEW' AND r.rdb$system_flag = 0 AND d.rdb$dependent_type = 1 --VIEW ORDER BY r.rdb$field_position

If you want to get the VIEW definition, though, the above query is not enough. It will only show the matches between aliases and real fields. Use the following query to get the VIEW body: SELECT RDB$VIEW_SOURCE FROM RDB$RELATIONS WHERE RDB$VIEW_SOURCE IS NOT NULL AND UPPER(RDB$RELATION_NAME) = 'NUMBERSVIEW'; One last tip Since Firebird 2.1, you can query the database for some system information, like the engine version, the network protocol, etc. Have a look at the doc/sql.extensions/readme.context_variables2.txt file for a listing of all the system variables that are available. Here's an example of what you can do: SELECT RDB$GET_CONTEXT('SYSTEM', 'ENGINE_VERSION') AS engine_version, RDB$GET_CONTEXT('SYSTEM', 'NETWORK_PROTOCOL') AS protocol, RDB$GET_CONTEXT('SYSTEM', 'CLIENT_ADDRESS') AS address FROM RDB$DATABASE; What else? System tables are a powerful tool in the hands of the Interbase/Firebird db admins. The queries listed in this page are just the top of the iceberg, you can retrieve a lot more from these tables. If you'd like to see some other examples, or have some comments and/or suggestions, just drop me a mail (you can find my address in the footer of this page) and I'll add them to this list. HTH.