Firebird v2.1.3.ReleaseNotes
Firebird v2.1.3.ReleaseNotes
Firebird v2.1.3.ReleaseNotes
1 Release Notes
Helen Borrie (Collator/Editor)
4 September 2009 - Document v.0213_13 - for Firebird 2.1.3
Table of Contents
1. General Notes .................................................................................................................................... 1 Patch Release 2.1.3 ........................................................................................................................ 1 Issues to Note ........................................................................................................................ 1 Patch Release 2.1.2 ........................................................................................................................ 2 Patch Release 2.1.1 ........................................................................................................................ 2 Bug Reporting ............................................................................................................................... 3 Additional Documentation .............................................................................................................. 3 2. New in Firebird 2 .............................................................................................................................. 5 New Features Implemented ............................................................................................................ 5 On-Disk Structure .................................................................................................................. 5 Database Triggers .................................................................................................................. 5 SQL and Objects ................................................................................................................... 5 Procedural SQL ..................................................................................................................... 7 Security ................................................................................................................................. 7 International Language Support .............................................................................................. 7 Platform Support .................................................................................................................... 8 Administrative ....................................................................................................................... 8 Remote Interface .................................................................................................................... 8 Derived Tables ....................................................................................................................... 9 PSQL Now Supports Named Cursors ...................................................................................... 9 Reimplemented Protocols on Windows ................................................................................... 9 Reworking of Garbage Collection ......................................................................................... 10 Porting of the Services API to Classic is Complete ................................................................ 11 Lock Timeout for WAIT Transactions ................................................................................... 11 New Implementation of String Search Operators .................................................................... 11 Reworking of Updatable Views ............................................................................................ 11 Additional Database Shutdown Modes Introduced .................................................................. 12 UDFs Improved re NULL Handling ...................................................................................... 12 Run-time Checking for Concatenation Overflow .................................................................... 12 Changes to Synchronisation Logic ........................................................................................ 13 Support for 64-bit Platforms ................................................................................................. 13 Record Enumeration Limits Increased ................................................................................... 13 Debugging Improvements ..................................................................................................... 13 Improved Connection Handling on POSIX Superserver .......................................................... 14 PSQL Invariant Tracking Reworked ...................................................................................... 14 ROLLBACK RETAIN Syntax Support ................................................................................. 14 No More Registry Search on Win32 Servers .......................................................................... 14 More Optimizer Improvements ............................................................................................. 15 3. Changes to the Firebird API and ODS .............................................................................................. 16 API (Application Programming Interface) ..................................................................................... 16 User Restrictions in the DPB ................................................................................................ 16 Cleanup of ibase.h ................................................................................................................ 17 Lock Timeout for WAIT Transactions ................................................................................... 17 isc_dsql_sql_info() Now Includes Relation Aliases ................................................................ 17 Enhancement to isc_blob_lookup_desc() ................................................................................ 17 API Identifies Client Version ................................................................................................ 17 Additions to the isc_database_info() Structure ....................................................................... 18 Additions to the isc_transaction_info() Structure .................................................................... 18 iv
Firebird 2.1 Release Notes Improved Services API ......................................................................................................... New Function for Delivering Error Text ................................................................................ Accommodation of New Shutdown <state> Parameters .......................................................... ODS (On-Disk Structure) Changes ................................................................................................ New ODS Number ............................................................................................................... Size limit for exception messages increased ........................................................................... New Description Field for Generators ................................................................................... New Description Field for SQL Roles ................................................................................... ODS Type Recognition ..................................................................................................... Smarter DSQL Error Reporting ............................................................................................. New Column in RDB$Index_Segments ................................................................................. 4. Global Improvements in Firebird 2.1 ................................................................................................. Forced Writes on Linux Now Works! ........................................................................................... Forensics .............................................................................................................................. Instant Fix for an Older Firebird ........................................................................................... Databases on Raw Devices ........................................................................................................... Moving a Database to a Raw Device .................................................................................... Special Issues for nbak/nbackup ............................................................................................ Further Advice about Raw Devices ....................................................................................... Remote Interface Improvements .................................................................................................... API Changes ................................................................................................................................ XSQLVAR .......................................................................................................................... Optimization ................................................................................................................................ Optimization for Multiple Index Scans .................................................................................. Optimize sparse bitmap operations ........................................................................................ Configuration and Tuning ............................................................................................................. Increased Lock Manager Limits & Defaults ........................................................................... Page sizes of 1K and 2K Deprecated .................................................................................... Enlarge Disk Allocation Chunks ........................................................................................... Bypass Filesystem Caching on Superserver ........................................................................... Other Global Improvements .......................................................................................................... Garbage Collector Rationalisation ......................................................................................... Immediate Release of External Files ..................................................................................... Synchronization of DSQL metadata cache objects in Classic server ......................................... BLOB Improvements ........................................................................................................... Type Flag for Stored Procedures ........................................................................................... Help for Getting Core Dumps on Linux ................................................................................ 5. Data Definition Language (DDL) ...................................................................................................... Quick Links ................................................................................................................................. Database Triggers ................................................................................................................. Global Temporary Tables ..................................................................................................... Views Enhancements ............................................................................................................ SQL2003 compliance for CREATE TRIGGER ...................................................................... SQL2003 Compliant Alternative for Computed Fields ............................................................ CREATE SEQUENCE ......................................................................................................... REVOKE ADMIN OPTION ................................................................................................. SET/DROP DEFAULT Clauses for ALTER TABLE ............................................................. Syntaxes for Changing Exceptions ........................................................................................ ALTER EXTERNAL FUNCTION ........................................................................................ COMMENT Statement ......................................................................................................... Extensions to CREATE VIEW Specification ......................................................................... RECREATE TRIGGER Statement Implemented .................................................................... 19 20 20 21 21 21 21 21 22 22 22 23 23 23 24 24 24 24 25 26 27 27 27 27 27 28 28 28 28 30 30 30 30 31 31 31 31 33 33 33 35 36 37 37 38 39 39 39 40 40 41 41
Firebird 2.1 Release Notes Usage Enhancements ............................................................................................................ 6. Data Manipulation Language (DML) ................................................................................................. Quick Links ................................................................................................................................. Common Table Expressions .................................................................................................. The LIST Function ............................................................................................................... The RETURNING Clause .................................................................................................... UPDATE OR INSERT Statement ......................................................................................... MERGE Statement ............................................................................................................... New JOIN Types ................................................................................................................. INSERT with Defaults ......................................................................................................... BLOB Subtype 1 Compatibility with VARCHAR .................................................................. Full Equality Comparisons Between BLOBs .......................................................................... RDB$DB_KEY Returns NULL in Outer Joins ...................................................................... Sorting on BLOB and ARRAY Columns is Restored ............................................................. Built-in Functions ................................................................................................................. Functions Enhanced in V.2.0.x ............................................................................................. DSQL Parsing of Table Names is Stricter .............................................................................. EXECUTE BLOCK Statement .............................................................................................. Derived Tables ..................................................................................................................... ROLLBACK RETAIN Syntax .............................................................................................. ROWS Syntax ...................................................................................................................... Enhancements to UNION Handling ....................................................................................... Enhancements to NULL Logic .............................................................................................. Subqueries and INSERT Statements Can Now Accept UNION Sets ........................................ New Extensions to UPDATE and DELETE Syntaxes ............................................................. Extended Context Variables .................................................................................................. Improvements in Handling User-specified Query Plans .......................................................... Improvements in Sorting ...................................................................................................... NEXT VALUE FOR Expression ........................................................................................... Articles ........................................................................................................................................ SELECT Statement & Expression Syntax .............................................................................. Data Type of an Aggregation Result ..................................................................................... A Useful Trick with Date Literals ......................................................................................... 7. Procedural SQL (PSQL) ................................................................................................................... Quick Links ................................................................................................................................. Domains in PSQL ................................................................................................................ COLLATE in Stored Procedures and Parameters ................................................................... WHERE CURRENT OF Now Allowed for Views ................................................................. Context Variable ROW_COUNT Enhanced ........................................................................... Explicit Cursors ................................................................................................................... Defaults for Stored Procedure Arguments .............................................................................. LEAVE <label> Syntax Support ........................................................................................... OLD Context Variables Now Read-only ................................................................................ PSQL Stack Trace ................................................................................................................ Call a UDF as a Void Function (Procedure) .......................................................................... 8. New Reserved Words and Changes ................................................................................................... Newly Reserved Words ................................................................................................................ Changed from Non-reserved to Reserved ....................................................................................... Keywords Added as Non-reserved ................................................................................................ Keywords No Longer Reserved .................................................................................................... No Longer Reserved as Keywords ................................................................................................ 9. Indexing & Optimizations ................................................................................................................. 41 43 43 44 47 48 50 51 52 53 54 54 54 54 54 56 58 60 61 62 63 63 65 67 67 68 72 73 75 75 75 76 77 79 79 79 80 80 80 81 82 84 85 86 87 89 89 89 89 91 91 92
vi
Firebird 2.1 Release Notes Optimizations in V.2.1 ................................................................................................................. 92 Improved PLAN Clause ............................................................................................................... 92 Optimizer Improvements .............................................................................................................. 92 For All Databases ................................................................................................................ 93 For ODS 11 Databases only ................................................................................................. 94 Enhancements to Indexing ............................................................................................................ 95 252-byte index length limit is gone ....................................................................................... 95 Expression Indexes ............................................................................................................... 95 Changes to Null keys handling ............................................................................................. 96 Improved Index Compression ............................................................................................... 96 Selectivity Maintenance per Segment .................................................................................... 97 10. International Language Support (INTL) ........................................................................................... 98 New INTL Interface for Non-ASCII Character Sets ....................................................................... 98 Architecture ......................................................................................................................... 98 Enhancements ...................................................................................................................... 98 INTL Plug-ins .................................................................................................................... 100 New Character Sets/Collations ............................................................................................ 101 Developments in V.2.1 ....................................................................................................... 102 ICU Character Sets ............................................................................................................. 102 The UNICODE Collations .................................................................................................. 104 Specific Attributes for Collations ........................................................................................ 104 Collation Changes in V.2.1 ................................................................................................. 105 Metadata Text Conversion .......................................................................................................... 106 Repairing Your Metadata Text ............................................................................................ 106 Supported Character Sets ............................................................................................................ 107 11. Administrative Features ................................................................................................................ 108 Monitoring Tables ...................................................................................................................... 108 The Concept ....................................................................................................................... 108 Scope and Security ............................................................................................................. 108 Metadata ............................................................................................................................ 109 Usage ................................................................................................................................. 112 Cancel a Running Query ..................................................................................................... 114 Performance Guidelines for Using MON$ Under Load ......................................................... 114 More Context Information .......................................................................................................... 115 12. Security ........................................................................................................................................ 117 Summary of Changes ................................................................................................................. 117 New security database ........................................................................................................ 117 Using Windows Security to Authenticate Users .................................................................... 117 Better password encryption ................................................................................................. 117 Users can modify their own passwords ................................................................................ 117 Non-server access to security database is rejected ................................................................ 118 Active protection from brute-force attack ............................................................................. 118 Vulnerabilities have been closed ......................................................................................... 118 Details of the Security Changes in Firebird 2 ............................................................................... 118 Authentication .................................................................................................................... 119 gsec in Firebird 2 ............................................................................................................... 120 Protection from Brute-force Hacking ................................................................................... 120 Using Windows Security to Authenticate Users ........................................................................... 120 SQL Privileges ................................................................................................................... 121 Administrators .................................................................................................................... 121 Configuration Parameter Authentication ........................................................................... 121 Forcing Trusted Authentication ........................................................................................... 122
vii
Firebird 2.1 Release Notes Classic Server on POSIX ............................................................................................................ For Any Platform ....................................................................................................................... Other Security Improvements ...................................................................................................... isc_service_query() wrongly revealed the full database file spec ............................................ Any user could view the server log through the Services API ................................................ Dealing with the New Security Database ..................................................................................... Doing the Security Database Upgrade ................................................................................. 13. Command-line Utilities ................................................................................................................. General Enhancements ................................................................................................................ Utilities Support for Database Triggers ................................................................................ Password Hiding ................................................................................................................ Firebird Services ........................................................................................................................ New Command-line Utility fbsvcmgr .................................................................................. Backup Tools ............................................................................................................................. New On-line Incremental Backup ........................................................................................ gbak Backup/Porting/Restore Utility .................................................................................... ISQL Query Utility .................................................................................................................... New Switches .................................................................................................................... New Commands and Enhancements .................................................................................... gsec Authentication Manager ...................................................................................................... gsec return code ................................................................................................................. gfix Server Utility ...................................................................................................................... New Shutdown States (Modes) ........................................................................................... Builds and Installs ...................................................................................................................... Parameter for Instance name added to instsvc.exe ................................................................ Revised Win32 Installer Docs ............................................................................................. Gentoo/FreeBSD detection during install ............................................................................. 14. External Functions (UDFs) ............................................................................................................ Ability to Signal SQL NULL via a Null Pointer .......................................................................... UDF library diagnostic messages improved ................................................................................. UDFs Added and Changed ......................................................................................................... IB_UDF_rand() vs IB_UDF_srand() .................................................................................... IB_UDF_lower ................................................................................................................... General UDF Changes ................................................................................................................ Build Changes .................................................................................................................... 15. New Configuration Parameters and Changes .................................................................................. Authentication ............................................................................................................................ RelaxedAliasChecking ................................................................................................................ MaxFileSystemCache ................................................................................................................. DatabaseGrowthIncrement .......................................................................................................... ExternalFileAccess ..................................................................................................................... LegacyHash ............................................................................................................................... Redirection ................................................................................................................................. About Multi-hop ................................................................................................................. GCPolicy ................................................................................................................................... OldColumnNaming ..................................................................................................................... UsePriorityScheduler .................................................................................................................. TCPNoNagle has changed .......................................................................................................... IPCName Behaviour Has Changed .............................................................................................. Renamed Parameters .................................................................................................................. SortMemBlockSize Changed to TempCacheBlockSize ......................................................... SortMemUpperLimit Changed to TempCacheUpperLimit ..................................................... 122 123 123 123 123 123 124 126 126 126 126 126 126 129 130 132 133 133 136 138 139 139 139 140 140 140 140 141 141 142 142 142 143 143 143 144 144 144 145 145 146 146 146 146 147 147 147 147 147 148 148 148
viii
Firebird 2.1 Release Notes Removed or Deprecated Parameters ............................................................................................ CreateInternalWindow ........................................................................................................ DeadThreadsCollection is no longer used ............................................................................ 16. Firebird 2 Project Teams ............................................................................................................... Appendix A: New Built-in Functions .................................................................................................. Appendix B: International Character Sets ............................................................................................ New Character Sets and Collations Implemented ......................................................................... Narrow Character Sets ................................................................................................................ ICU Character Sets ..................................................................................................................... Appendix C: Security Database Upgrade for Firebird 2 ........................................................................ Security Upgrade Script .............................................................................................................. 148 148 148 149 151 161 161 162 162 168 168
ix
List of Tables
16.1. Firebird Development Teams ...................................................................................................... 149
Chapter 1
General Notes
Firebird 2.1 is a full version release that builds on the architectural changes introduced in the V.2.0 series. Thanks to all who field-tested the Alphas and Betas during 2007 and the first quarter of 2008 we have a release that is bright with new features and improvements, including the long-awaited global temporary tables, a catalogue of new run-time monitoring mechanisms, database triggers and the injection of dozens of internal functions into the SQL language set.
Issues to Note
The default authentication method on Windows platforms is no longer mixed. It has been changed to native. For more information, see the notes on the configuration parameter Authentication. A fix in Firebird 2.5 that alleviates the hogging behaviour of the nBackup utility has been backported to this patch release. For more information, see the Improvement in V.2.1.3 note in the nBackup section of the Utilities chapter. By popular request, Dmitry Yemanov adds some helpful performance guidelines pertaining to the internals of the database monitoring system (a.k.a. MON$). The purpose is to assist those using this facility on heavily loaded systems to employ it in ways that provide the information you want while minimising its impact on the end-user experience. Known Issue At some point in V.2.1 development, a breakage occurred in the behaviour of TempDirectories, the configuration parameter by which you can configure a list of spaces where the engine can write the intermediate sets for sorting when it finds it does not have enough RAM available for these sets. Since V.2.1 (and still), although the engine will use the first space listed in TempDirectories, it fails to hand on sets to the any of the other configured spaces if the first space is exhausted. (Tracker reference CORE-2422). Because of the impact on related code, this regression cannot be fixed for the V.2.1.3 patch release. The workaround for now is to ensure that you configure enough space in the single location that the engine can address.
General Notes
It also includes three minor improvements that have come from user requests: Requested in Tracker CORE-2243 was an improvement to reduce the duplication and confusion of the Microsoft Visual C 8 runtime assembly rules for XP, Server2003 and Vista platforms, that have wracked the installation of the v.2.1.x Windows packages so far. Vlad Khorsun has met that request for this sub-release. For more information, refer to Windows installation section of the accompanying Firebird 2 Migration & Installation document. Dmitry Yemanov has improved database monitoring to enable a non-SYSDBA user to monitor all of its own attachments, not just the one which is that user's CURRENT_CONNECTION. This improvement was requested in Tracker CORE-2233. See also Monitor Multiple Attachments in the Administrative Features chapter. Dmitry has addressed a complaint about slowness in executing cross joins across three or more tables, particularly when one or more tables are empty. See the notes here and Tracker item CORE-2200.
General Notes
Bug Reporting
If you think you have discovered a new bug in this release, please make a point of reading the instructions for bug reporting in the article How to Report Bugs Effectively, at the Firebird Project website. If you think a bug fix hasn't worked, or has caused a regression, please locate the original bug report in the Tracker, reopen it if necessary, and follow the instructions below. Follow these guidelines as you attempt to analyse your bug: 1. 2. Write detailed bug reports, supplying the exact build number of your Firebird kit. Also provide details of the OS platform. Include reproducible test data in your report and post it to our Tracker. You are warmly encouraged to make yourself known as a field-tester by subscribing to the field-testers' list and posting the best possible bug description you can. If you want to start a discussion thread about a bug or an implementation, please do so by subscribing to the firebird-devel list. In that forum you might also see feedback about any tracker ticket you post regarding this release.
3.
Additional Documentation
You will find README documents for many of the new v.2 and v.2.1 features in your installation kit, installed by default in the /doc/ sub-directory. 3
General Notes An automated "Release Notes" page in the Tracker provides access to lists and links for all of the Tracker tickets associated with this version and its various builds. Use this link. For your convenience, the many bug-fixes and regressions fixed during the development of Firebird 2.0.x and 2.1 are listed in descending chronological order in the separate Bugfixes document. Firebird 2 Project Team
Chapter 2
New in Firebird 2
New Features Implemented
This chapter summarises the new features implemented in Firebird 2, encompassing both v.2.1 and the v.2.0.x series. Important Change to API DPB Parameters in V.2.1.2
A long-standing, legacy loophole in the handling of DPB parameters enabled ordinary users to make connection settings that could lead to database corruptions or give them access to SYSDBA-only operations. The loophole has been closed, a change that could affect several existing applications, database tools and connectivity layers (drivers, components). Details are in Chapter 3, Changes to the Firebird API and ODS.
On-Disk Structure
Databases created or restored under Firebird 2 have an on-disk structure (ODS) of 11 or higher. Firebird 2.1 creates databases with an ODS of 11.1. It can read databases of lower ODS but most of its new features will be unavailable to such databases. Firebird 2.0.x servers create databases with an ODS of 11 (sometimes expressed as 11.0). If you wish to have the full range of v.2.1 features available, you should upgrade ODS 11 and lower databases by backing them up and restoring them under v.2.1.
Database Triggers
(v.2.1) Newly implemented database triggers are user-defined PSQL modules that can be designed to fire in various connection-level and transaction- level events. See Database Triggers.
New in Firebird 2
RETURNING Clause
(v.2.1) Optional RETURNING clause for all singleton operations update, insert and delete operations. See RETURNING Clause.
MERGE Statement
(v.2.1) New statement syntax that performs either an update to an existing record if a condition is met or an insert if the condition is not met. See MERGE Statement.
LIST() function
(v.2.1) A new aggregate function LIST(<SOMETHING>) retrieves all of the SOMETHINGs in a group and aggregates them into a comma-separated list. See LIST Function.
New in Firebird 2
Procedural SQL
Domains for Defining PSQL Variables and Arguments
(v.2.1) PSQL local variables and input and output arguments for stored procedures can now be declared using domains in lieu of canonical data types. See Domains in PSQL.
Security
Windows Security to Authenticate Users
(v.2.1) Windows Trusted User security can be applied for authenticating Firebird users on a Windows host. See Windows Trusted User Security.
New in Firebird 2
Platform Support
Ports to Windows 2003 64-bit
D. Yemanov Feature request CORE-819 and CORE-682 (v.2.1) 64-bit Windows platform (AMD64 and Intel EM64T) ports of Classic, Superserver and Embedded models.
Administrative
Database Monitoring via SQL
(v.2.1) Implementation of run-time database snapshot monitoring (transactions, tables, etc.) via SQL over some new virtualized system tables. See Monitoring Tables. Included in the set of tables is one named MON$DATABASE that provides a lot of the database header information that could not be obtained previously via SQL: such details as the on-disk structure (ODS) version, SQL dialect, sweep interval, OIT and OAT and so on. It is possible to use the information from the monitoring tables to cancel a rogue query. See Cancel a Running Query.
Remote Interface
(v.2.1) The remote protocol has been slightly improved to perform better in slow networks once drivers are updated to utilise the changes. Testing showed that API round trips were reduced by about 50 percent, resulting in about 40 per cent fewer TCP round trips. See Remote Interface Improvement. 8
New in Firebird 2
Derived Tables
A. Brinkman Implemented support for derived tables in DSQL (subqueries in FROM clause) as defined by SQL200X. A derived table is a set, derived from a dynamic SELECT statement. Derived tables can be nested, if required, to build complex queries and they can be involved in joins as though they were normal tables or views. More details under Derived Tables in the DML chapter.
Local Protocol--XNET
Firebird 2.0 has replaced the former implementation of the local transport protocol (often referred to as IPC or IPServer) with a new one, named XNET. It serves exactly the same goal, to provide an efficient way to connect to server located on the same machine as the connecting client without a remote node name in the connection string. The new implementation is different and addresses the known issues with the old protocol. Like the old IPServer implementation, the XNET implementation uses shared memory for inter-process communication. However, XNET eliminates the use of window messages to deliver attachment requests and it also implements a different synchronization logic.
Benefits of the XNET Protocol over IPServer Besides providing a more robust protocol for local clients, the XNET protocol brings some notable benefits: it works with Classic Server it works for non-interactive services and terminal sessions it eliminates lockups when a number of simultaneous connections are attempted
Performance The XNET implementation should be similar to the old IPServer implementation, although XNET is expected to be slightly faster. 9
New in Firebird 2
Disadvantages The one disadvantage is that the XNET and IPServer implementations are not compatible with each other. This makes it essential that your fbclient.dll version should match the version of the server binaries you are using (fbserver.exe or fb_inet_server.exe) exactly. It will not be possible to to establish a local connection if this detail is overlooked. (A TCP localhost loopback connection via an ill-matched client will still do the trick, of course).
10
New in Firebird 2 background - garbage collection will be performed only by background threads, as is the case for Firebird 1.5 and earlier. User table-scan requests will not remove unused record versions but will cause the GC thread to be notified about any page where an unused record version is detected. The engine will also remember those page numbers where UPDATE and DELETE statements created back versions. combined (the installation default for Superserver) - both background and cooperative garbage collection are performed. Note
The Classic server ignores this parameter and always works in cooperative mode.
2. 3.
New in Firebird 2 For details, see the notes in the Compatibility chapter of the separate Installation Notes document.
normal state = online database multi state = multi-user shutdown mode (the legacy one, unlimited attachments of SYSDBA/owner are allowed) single state = single-user shutdown (only one attachment is allowed, used by the restore process) full state = full/exclusive shutdown (no attachments are allowed) For more details, refer to the section on Gfix New Shutdown Modes, in the Utilities chapter. For a list of shutdown state flag symbols and an example of usage, see Shutdown State in the API.
New in Firebird 2 From Firebird 1.0 onward, concatenation operations have been checked for the possibility that the resulting string might exceed the string length limit of 32,000 bytes, i.e. overflow. This check was performed during the statement prepare, using the declared operand sizes and would throw an error for an expressions such as:
CAST('qwe' AS VARCHAR(30000)) || CAST('rty' AS VARCHAR(30000))
From Firebird 2.0 onward, this expression throws only a warning at prepare time and the overflow check is repeated at runtime, using the sizes of the actual operands. The result is that our example will be executed without errors being thrown. The isc_concat_overflow exception is now thrown only for actual overflows, thus bringing the behaviour of overflow detection for concatenation into line with that for arithmetic operations.
2. 3. 4.
Debugging Improvements
Various Contributors
New in Firebird 2
Diagnostic Enhancement
Syslog messages will be copied to the user's tty if a process is attached to it. (A. Peshkov)
This query performs only one fetch from rdb$database instead of evaluating the subquery for every row of rdb $relations.
New in Firebird 2
Important
The command-line utilities still check the Registry.
15
Chapter 3
16
Important Note for Developers and Users of Data Access Drivers and Tools
This change will affect any of the listed DPB parameters that have been explicitly set, either by including them in the DPB implementation by default property values or by enabling them in tools and applications that access databases as ordinary users. For example, a Delphi application that included 'RESERVE PAGE SPACE=TRUE' and 'FORCED WRITES=TRUE' in its database Params property, which caused no problems when the application connected to Firebird 1.x, 2.0.x or 2.1.0/2.1.1, now rejects a connection by a non-SYSDBA user with ISC ERROR CODE 335544788, Unable to perform operation. You must be either SYSDBA or owner of the database.
Cleanup of ibase.h
D. Yemanov, A. Peshkov The API header file, ibase.h has been subjected to a cleanup. with the result that public headers no longer contain private declarations.
Enhancement to isc_blob_lookup_desc()
A. dos Santos Fernandes isc_blob_lookup_desc() now also describes blobs that are outputs of stored procedures
Changes to the Firebird API and ODS The current value of FB_API_VER is 20 (two-digit equivalent of 2.0). This macro can be used by client applications to check the version of ibase.h its being compiled with.
isc_info_active_tran_count
Returns the number of currently active transactions.
isc_info_creation_date
Returns the date and time when the database was [re]created. To decode the returned value, call isc_vax_integer twice to extract (first) the date and (second) the time portions of the ISC_TIMESTAMP. Then, use isc_decode_timestamp() as usual.
isc_info_tra_oldest_interesting
Returns the number of the oldest [interesting] transaction when the current transaction started. For snapshot transactions, this is also the number of the oldest transaction in the private copy of the transaction inventory page (TIP).
isc_info_tra_oldest_active
For a read-committed transaction, returns the number of the current transaction. For all other transactions, returns the number of the oldest active transaction when the current transaction started.
isc_info_tra_oldest_snapshot
Returns the number of the lowest tra_oldest_active of all transactions that were active when the current transaction started. Note
This value is used as the threshold ("high-water mark") for garbage collection.
18
isc_info_tra_isolation
Returns the isolation level of the current transaction. The format of the returned clumplets is:
isc_info_tra_isolation, 1, isc_info_tra_consistency | isc_info_tra_concurrency | 2, isc_info_tra_read_committed, isc_info_tra_no_rec_version | isc_info_tra_rec_version
That is, for Read Committed transactions, two items are returned (isolation level and record versioning policy) while, for other transactions, one item is returned (isolation level).
isc_info_tra_access
Returns the access mode (read-only or read-write) of the current transaction. The format of the returned clumplets is:
isc_info_tra_access, 1, isc_info_tra_readonly | isc_info_tra_readwrite
isc_info_tra_lock_timeout
Returns the lock timeout set for the current transaction.
Parameter isc_spb_trusted_auth
(V.2.1, ODS 11.1) isc_spb_trusted_auth applies only to Windows and is used to force Firebird to use Windows trusted authentication for the requested service.
Parameter isc_spb_dbname
(V.2.1, ODS 11.1) For any services related to the security database, provides the ability to supply the name of the security database when invoking a security service remotely. It is equivalent to supplying the -database switch when calling the gsec utility remotely.
20
const int dpb_length = dpb - dpb_buffer; isc_attach_database(status_vector, 0, employee.db, &handle, dpb_length, dpb_buffer); if (status_vector[0] == 1 && status_vector[1]) { isc_print_status(status_vector); } else { isc_detach_database(status_vector, &handle); }
22
Chapter 4
Forensics
Speed tests on Linux showed that setting O_SYNC on a file has no effect at all on performance! Fine, fast operating system we may think? Alas, no, it's a documented bug in the Linux kernel! According to the Linux manual, On Linux this command (i.e. fcntl(fd, F_SETFL, flags)) can only change the O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME, and O_NONBLOCK flags. Though it is not documented in any place known to me, it turns out that an attempt to set any flag other than those listed in the manual (such as O_SYNC, for example) won't work but it does not cause fcntl() to return an error, either. For Firebird and for InterBase versions since Day One, it means that Forced Writes has never worked on Linux. It certainly works on Windows. It seems likely that this is not a problem that affects other operating systems, although we cannot guarantee that. To make sure, you can check whether the implementation of fcntl() on your OS is capable of setting the O_SYNC flag. The technique used currently, introduced in the Beta 2 release of Firebird 2.1, is to re-open the file. It should guarantee correct operation on any OS, provided the open() system call works correctly in this respect. It appears that no such problems are reported. The Firebird developers have no idea why such a bug would remain unfixed almost two years after getting into the Linux kernel's bug-tracker. Apparently, in Linux, a documented bug evolves into a feature... 23
/dev/sda9
/usr/database
ext3
noatime,sync
1 2
will restore your database on the third logical disk in the extended partition of your first SCSI or SATA harddrive (disk0). Note
The database does not have a database name other than the device name itself. In the example given, the name of the database is '/dev/sda7'.
24
To keep the size of the nbak copy within reasonable bounds, it is of benefit to know how much storage on the device is actually occupied. The '-s' switch of nbackup will return the size of the database in database pages:
# nbackup -s -l /dev/sda7 77173
Don't confuse the result here with the block size of the device. The figure returned77173is the number of pages occupied by the database. Calculate the physical size (in bytes) as (number of pages * page size). If you are unsure of the page size, you can query it from the database header using gstat -h:
# gstat -h /dev/sda7 Database "/dev/sda7" Database header page information: Flags 0 Checksum 12345 Generation 43 Page size 4096 < ODS version 11.1 .......
2.
25
Global Improvements in Firebird 2.1 the very Windows-knowledgeable might want to try out the concept of raw device storage on Windows systems. It has not been a project priority to explore how it might be achieved on that platform. However, if you think you know a way to do it, please feel welcome to test the idea in your Windows lab and report your observationsgood or bad or indifferentback to the firebird-devel list. Tip
Maintain your raw devices in aliases.conf. That way, in the event of needing to reconfigure the storage hardware, there will be no need to alter any connection strings in your application code.
b.
d.
Note
A faintly possible side-effect is that, if isc_dsql_execute should happen to fail with a certain exception, this exception is returned to the client in the response to the API call that was actually responsible; i.e., instead of being returned by isc_dsql_execute it would be returned by isc_dsql_fetch, isc_dsql_info, or whichever API call actually dispatched the op_execute call. In most cases, the side-effect would be transparent: it might show up in a case where some error occurred with default values for PSQL parameters or variables and would be noticed as an exception array where the exceptions were delivered in an unusual sequence.
The changes work with either TCP/IP or NetBEUI. They are backward-compatible, so existing client code will not be broken. However, when you are using a driver layer that implements its own interpretation of the remote protocolsuch as the Jaybird JDBC and the FirebirdClient .NET driversyour existing code will not enable the enhancements unless you usedrivers are updated.
API Changes
XSQLVAR
A. dos Santos Fernandes The identifier of the connection character set or, when the connection character set is NONE, the BLOB character set, is now passed in the XSQLVAR::sqlscale item of text BLOBs.
Optimization
Optimization for Multiple Index Scans
V. Khorsun Feature request CORE-1069 An optimization was done for index scanning when more than one index is to be scanned with AND conjunctions.
27
2.
File fragmentation Allocating disk space in relatively small chunks can lead to significant fragmentation of the database file at file system level, impairing the performance of large scans, as during a backup, for example.
The Solution
The solution is to introduce some rules and rationales to govern page writes according to the state of available disk space, as follows.a. Each newly allocated page writes to disk immediately before returning to the engine. If the page cannot be written then the allocation does not happen: the PIP bit remains uncleared and the appropriate I/O error is raised. Corruption cannot arise, since it is guaranteed that all dirty pages in cache have disk space allocated and can be written safely. Because this change adds an extra write for each newly-allocated page, some performance penalty is to be expected. To mitigate the effect, writes of newly-allocated pages are performed in batches of up to 128 Kb and Firebird keeps track of the number of these initialized pages in the PIP header. Note
A page that has been allocated, released and re-allocated is already space in hand, meaning that no further verification is required in order to initialize it. Hence, a newly allocated page is subjected to this double-write only if it is a block that has never been allocated before.
b.
To address the issue of file fragmentation, Firebird now uses the appropriate call to the API of the file system to preallocate disk space in relatively large chunks. Preallocation also gives room to avoid corruptions in the event of an out of disk space condition. Chances are that the database will have enough space preallocated to continue operating until the administrator can make some disk space available. Important
Windows Only (for Now) Currently, only Windows file systems publish such API calls, which means that, for now, this aspect of the solution is supported only in the Windows builds of Firebird. However, similar facilities have recently been added to the Linux API, allowing the prospect that a suitable API function call will appear in such popular file systems as ext3 in future.
29
Now, Superserver on both Windows and POSIX can be configured by a new configuration parameter, MaxFileSystemCache, to prevent or enable filesystem caching. It may provide the benefit of freeing more memory for other operations such as sorting and, where there are multiple databases, reduce the demands made on host resources. Note
For Classic, there is no escaping filesystem caching.
BLOB Improvements
A. dos Santos Fernandes Feature request CORE-1169 Conversion of temporary blobs to the destination blob type now occurs when materializing.
Global Improvements in Firebird 2.1 working directory) to an appropriate writable location (/tmp) and set the core file size limit so that the 'soft' limit equals the 'hard' limit. Note
In a release version, the automated core-dumping is active only when the BugcheckAbort parameter in firebird.conf is set to true (1). In a debug version, it is always active. If you need to enable the facility, don't forget that the server needs to be restarted to activate a parameter change.
32
Chapter 5
Quick Links
Database Triggers Global Temporary Tables Column Aliases in CREATE VIEW CREATE TRIGGER SQL2003 Variant Alternative Syntax for Computed Fields CREATE SEQUENCE REVOKE ADMIN OPTION SET/DROP DEFAULT Clauses Syntaxes for Changing Exceptions ALTER EXTERNAL FUNCTION COMMENT Statement CREATE VIEW Extensions Create FKs Without Exclusive Access Changed Logic for View Updates Descriptive Identifiers for BLOB Subtypes CREATE COLLATION statement
Database Triggers
Adriano dos Santos Fernandes (v.2.1) A database trigger is a PSQL module that is executed when a connection or transaction event occurs. The events and the timings of their triggers are as follows.CONNECT
Database connection is established A transaction is started Triggers are fired; uncaught exceptions roll back the transaction, disconnect the attachment and are returned to the client The transaction is committed
DISCONNECT
A transaction is started
33
Data Definition Language (DDL) Triggers are fired; uncaught exceptions roll back the transaction, disconnect the attachment and are swallowed The transaction is committed The attachment is disconnected
TRANSACTION START
Triggers are fired in the newly-created user transaction; uncaught exceptions are returned to the client and the transaction is rolled back.
TRANSACTION COMMIT
Triggers are fired in the committing transaction; uncaught exceptions roll back the trigger's savepoint, the commit command is aborted and the exception is returned to the client. Note
For two-phase transactions, the triggers are fired in the prepare, not in the commit.
TRANSACTION ROLLBACK
Triggers are fired during the roll-back of the transaction. Changes done will be rolled back with the transaction. Exceptions are swallowed Syntax
<database-trigger> ::= {CREATE | RECREATE | CREATE OR ALTER} TRIGGER <name> [ACTIVE | INACTIVE] ON <event> [POSITION <n>] AS BEGIN ... END <event> ::= CONNECT | DISCONNECT | TRANSACTION START | TRANSACTION COMMIT | TRANSACTION ROLLBACK
Rules and Restrictions 1. 2. Database triggers type cannot be changed. Permission to create, recreate, create or alter, or drop database triggers is restricted to the database owner and SYSDBA.
Creates the metadata for the temporary table in the system catalogue. The clause ON COMMIT sets the kind of temporary table: ON COMMIT PRESERVE ROWS Data left in the given table after the end of the transaction remain in database until the connection ends. ON COMMIT DELETE ROWS Data in the given table are deleted from the database immediately after the end of the transaction. ON COMMIT DELETE ROWS is used by default if the optional clause ON COMMIT is not specified. CREATE GLOBAL TEMPORARY TABLE is a regular DDL statement that is processed by the engine the same way as a CREATE TABLE statement is processed. Accordingly, it not possible to create or drop a GTT within a stored procedure or trigger. Relation Type GTT definitions are distinguished in the system catalogue from one another and from permanent tables by the value of RDB$RELATIONS.RDB$RELATION_TYPE: A GTT with ON COMMIT PRESERVE ROWS option has RDB$RELATION_TYPE = 4 A GTT with ON COMMIT DELETE ROWS option has RDB$RELATION_TYPE = 5. Note
For the full list of values, see RDB$TYPES.
35
Data Definition Language (DDL) Structural Feature Support The same structural features that you can apply to regular tables (indexes, triggers, field-level and table level constraints) are also available to a GTT, with certain restrictions on how GTTs and regular tables can interrelate.a. b. references between persistent and temporary tables are forbidden A GTT with ON COMMIT PRESERVE ROWS cannot have a reference on a GTT with ON COMMIT DELETE ROWS A domain constraint cannot have a reference to any GTT.
c.
Implementation Notes
An instance of a GTTa set of data rows created by and visible within the given connection or transaction is created when the GTT is referenced for the first time, usually at statement prepare time. Each instance has its own private set of pages on which data and indexes are stored. The data rows and indexes have the same physical storage layout as permanent tables. When the connection or transaction ends, all pages of a GTT instance are released immediately. It is similar to what happens when a DROP TABLE is performed, except that the metadata definition is retained, of course. This is much quicker than the traditional row-by-row delete + garbage collection of deleted record versions. Note
This method of deletion does not cause DELETE triggers to fire, so do not be tempted to define Before or After Delete triggers on the false assumption that you can incorporate some kind of last rites that will be execute just as your temporary data breathes its last!
The data and index pages of all GTT instances are placed in separate temporary files. Each connection has its own temporary file created the first time the connection references some GTT. Note
These temporary files are always opened with Forced Writes = OFF, regardless of the database setting for Forced Writes.
No limit is placed on the number of GTT instances that can coexist. If you have N transactions active simultaneously and each transaction has referenced some GTT then you will have N instances of the GTT.
Views Enhancements
D. Yemanov A couple of enhancements were made to view definitions in v.2.1.-
Data Definition Language (DDL) (v.2.1) Column aliases can now be processed as column names in the view definition. Example
CREATE VIEW V_TEST AS SELECT ID, COL1 AS CODE, COL2 AS NAME FROM TAB;
SQL2003 Form
create trigger t2 [active] before insert or update ON atable as begin ... end
Note the different positions of the clause identifying the table and the different keywords pointing to the table identifier (existing: FOR; SQL2003: ON). Both syntaxes are valid and are available also for all CREATE TRIGGER, RECREATE TRIGGER and CREATE OR ALTER TRIGGER statements.
Data Definition Language (DDL) (v.2.1) SQL-compliant alternative syntax GENERATED ALWAYS AS was implemented for defining a computed field in CREATE/ALTER TABLE. Syntax Pattern
<column name> [<type>] GENERATED ALWAYS AS ( <expr> )
Example
CREATE TABLE T (PK INT, EXPR GENERATED ALWAYS AS (PK + 1))
CREATE SEQUENCE
D. Yemanov SEQUENCE has been introduced as a synonym for GENERATOR, in accordance with SQL-99. SEQUENCE is a syntax term described in the SQL specification, whereas GENERATOR is a legacy InterBase syntax term. Use of the standard SEQUENCE syntax in your applications is recommended. A sequence generator is a mechanism for generating successive exact numeric values, one at a time. A sequence generator is a named schema object. In dialect 3 it is a BIGINT, in dialect 1 it is an INTEGER. Syntax patterns
CREATE { SEQUENCE | GENERATOR } <name> DROP { SEQUENCE | GENERATOR } <name> SET GENERATOR <name> TO <start_value> ALTER SEQUENCE <name> RESTART WITH <start_value> GEN_ID (<name>, <increment_value>) NEXT VALUE FOR <name>
Examples 1.
CREATE SEQUENCE S_EMPLOYEE;
2.
ALTER SEQUENCE S_EMPLOYEE RESTART WITH 0;
Warning
ALTER SEQUENCE, like SET GENERATOR, is a good way to screw up the generation of key values!
Note
Array fields cannot have a default value. If you change the type of a field, its default may remain in place. This is because a field could be changed to a defaulted domain, while the field definition itself could override the domain's default. On the other hand, if the field is given a new type directly, any default belongs logically to the field and is maintained on the implicit domain created for it behind the scenes.
RECREATE EXCEPTION
RECREATE EXCEPTION is exactly like CREATE EXCEPTION if the exception does not already exist. If it does exist, its definition will be completely replaced, if there are no dependencies on it.
COMMENT Statement
C. Valderrama The COMMENT statement has been implemented for setting metadata descriptions. Syntax Pattern
COMMENT COMMENT COMMENT COMMENT ON ON ON ON DATABASE IS {'txt'|NULL}; <basic_type> name IS {'txt'|NULL}; COLUMN tblviewname.fieldname IS {'txt'|NULL}; PARAMETER procname.parname IS {'txt'|NULL};
An empty literal string '' will act as NULL since the internal code (DYN in this case) works this way with blobs.
<basic_type>: DOMAIN TABLE VIEW PROCEDURE TRIGGER EXTERNAL FUNCTION FILTER EXCEPTION GENERATOR SEQUENCE INDEX ROLE CHARACTER SET COLLATION SECURITY CLASS1
1
Usage Enhancements
The following changes will affect usage or existing, pre-Firebird 2 workarounds in existing applications or databases to some degree.
41
where <mnemonic> refers to a subtype identifier known to the engine. Initially they are binary, text and others mostly for internal usage, but an adventurous user could write a new mnemonic in rdb$types and use it, since it is parsed only at declaration time. The engine keeps the numerical value. Remember, only negative subtype values are meant to be defined by users. To get the predefined types, do
select RDB$TYPE, RDB$TYPE_NAME, RDB$SYSTEM_FLAG from rdb$types where rdb$field_name = 'RDB$FIELD_SUB_TYPE'; RDB$TYPE RDB$TYPE_NAME RDB$SYSTEM_FLAG ========= ============================ ================= 0 1 2 3 4 5 6 7 8 BINARY TEXT BLR ACL RANGES SUMMARY FORMAT TRANSACTION_DESCRIPTION EXTERNAL_FILE_DESCRIPTION 1 1 1 1 1 1 1 1 1
Alternative declaration:
declare filter pesh input_type binary output_type acl entry_point 'f' module_name 'p';
Declaring a name for a user defined blob subtype (remember to commit after the insertion):
SQL> CON> SQL> SQL> CON> SQL> BLOB insert into rdb$types values('RDB$FIELD_SUB_TYPE', -100, 'XDR', 'test type', 0); commit; declare filter pesh2 input_type xdr output_type text entry_point 'p2' module_name 'p'; show filter pesh2; Filter: PESH2 Input subtype: -100 Output subtype: 1 Filter library is p Entry point is p2
42
Chapter 6
Quick Links
Common Table Expressions LIST Function RETURNING Clause UPDATE OR INSERT Statement MERGE Statement New JOIN Types - NAMED COLUMNS & NATURAL JOIN - CROSS JOIN INSERT with Defaults Text BLOB Compatibility Compare BLOB=BLOB Sorting on BLOBs RDB$DB_KEY Returns NULL in Outer Joins New Built-in Functions Enhancements to Built-in Functions IIF() Expression Improvement in CAST() Behaviour Expression Arguments for SUBSTRING() DSQL Parsing of Table Names is Stricter EXECUTE BLOCK Statement Derived Tables ROLLBACK RETAIN Syntax ROWS Syntax UNION DISTINCT Improved Type Coercion in UNIONs UNIONs Allowed in ANY/ALL/IN Subqueries 43
Data Manipulation Language (DML) New [NOT] DISTINCT Predicate NULL Comparison Rule Relaxed NULLs Ordering Changed UNION Sets in Subquery Constructs Extended Context Variables Query Plans Improvements GROUP or ORDER by Alias Name GROUP BY Arbitrary Expressions Order * Sets by Implicit Degree Number NEXT VALUE FOR Articles 1. Select Statement & Expression Syntax 2. Data Type of an Aggregation Result 3. A Useful Trick with Date Literals
Benefits of CTEs
Using CTEs allows you to specify dynamic queries that are recursive: The engine begins execution from a non-recursive member. For each row evaluated, it starts executing each recursive member one-by-one, using the current values from the outer row as parameters. If the currently executing instance of a recursive member produces no rows, execution loops back one level and gets the next row from the outer result set. The memory and CPU overhead of a recursive CTE is much less than that of an equivalent recursive stored procedure.
Recursion Limit
Currently the recursion depth is limited to a hard-coded value of 1024.
44
Rules for Non-Recursive CTEs Multiple table expressions can be defined in one query Any clause legal in a SELECT specification is legal in table expressions Table expressions can reference one another References between expressions should not have loops Table expressions can be used within any part of the main query or another table expression The same table expression can be used more than once in the main query Table expressions (as subqueries) can be used in INSERT, UPDATE and DELETE statements Table expressions are legal in PSQL code WITH statements can not be nested Example of a non-recursive CTE
WITH DEPT_YEAR_BUDGET AS ( SELECT FISCAL_YEAR, DEPT_NO, SUM(PROJECTED_BUDGET) AS BUDGET FROM PROJ_DEPT_BUDGET GROUP BY FISCAL_YEAR, DEPT_NO ) SELECT D.DEPT_NO, D.DEPARTMENT, B_1993.BUDGET AS B_1993, B_1994.BUDGET AS B_1994, B_1995.BUDGET AS B_1995, B_1996.BUDGET AS B_1996 FROM DEPARTMENT D
45
Rules for Recursive CTEs A recursive CTE is self-referencing (has a reference to itself) A recursive CTE is a UNION of recursive and non-recursive members: - At least one non-recursive member (anchor) must be present - Non-recursive members are placed first in the UNION - Recursive members are separated from anchor members and from one another with UNION ALL clauses, i.e., non-recursive member (anchor) UNION [ALL | DISTINCT] non-recursive member (anchor) UNION [ALL | DISTINCT] non-recursive member (anchor) UNION ALL recursive member UNION ALL recursive member
References between CTEs should not have loops Aggregates (DISTINCT, GROUP BY, HAVING) and aggregate functions (SUM, COUNT, MAX etc) are not allowed in recursive members A recursive member can have only one reference to itself and only in a FROM clause A recursive reference cannot participate in an outer join Example of a recursive CTE
WITH RECURSIVE DEPT_YEAR_BUDGET AS (
46
47
Syntax Rules 1. 2. If neither ALL nor DISTINCT is specified, ALL is implied. If <delimiter value> is omitted, a comma is used to separate the concatenated values.
Other Notes 1. 2. 3. Numeric and date/time values are implicitly converted to strings during evaluation. The result value is of type BLOB with SUB_TYPE TEXT for all cases except list of BLOB with different subtype. Ordering of values within a group is implementation-defined.
Examples
/* A */ SELECT LIST(ID, ':') FROM MY_TABLE /* B */ SELECT TAG_TYPE, LIST(TAG_VALUE) FROM TAGS GROUP BY TAG_TYPE
48
3. 4.
5.
Examples 1.
INSERT INTO T1 (F1, F2) VALUES (:F1, :F2) RETURNING F1, F2 INTO :V1, :V2;
2.
INSERT INTO T2 (F1, F2) VALUES (1, 2) RETURNING ID INTO :PK;
3.
DELETE FROM T1 WHERE F1 = 1 RETURNING F2;
49
4.
UPDATE T1 SET F2 = F2 * 10 RETURNING OLD.F2, NEW.F2;
Examples 1.
UPDATE OR INSERT INTO T1 (F1, F2) VALUES (:F1, :F2);
2.
UPDATE OR INSERT INTO EMPLOYEE (ID, NAME) VALUES (:ID, :NAME) RETURNING ID;
3.
UPDATE OR INSERT INTO T1 (F1, F2) VALUES (:F1, :F2) MATCHING (F1);
4.
UPDATE OR INSERT INTO EMPLOYEE (ID, NAME) VALUES (:ID, :NAME) RETURNING OLD.NAME;
Usage Notes
1. 2. When MATCHING is omitted, the existence of a primary key is required. INSERT and UPDATE permissions are needed on <table or view>. 50
3.
If the RETURNING clause is present, then the statement is described as isc_info_sql_stmt_exec_ procedure by the API; otherwise, it is described as isc_info_sql_stmt_insert. Note
A multiple rows in singleton select error will be raised if the RETURNING clause is present and more than one record matches the search condition.
MERGE Statement
Adriano dos Santos Fernandes (v.2.1) This syntax has been introduced to enable a record to be either updated or inserted, according to whether or not a stated condition is met. The statement is available in both DSQL and PSQL. Syntax Pattern
<merge statement> ::= MERGE INTO <table or view> [ [AS] <correlation name> ] USING <table or view or derived table> [ [AS] <correlation name> ] ON <condition> [ <merge when matched> ] [ <merge when not matched> ] <merge when matched> ::= WHEN MATCHED THEN UPDATE SET <assignment list> <merge when not matched> ::= WHEN NOT MATCHED THEN INSERT [ <left paren> <column list> <right paren> ] VALUES <left paren> <value list> <right paren>
Example
MERGE INTO customers c
51
Named columns join 1. 2. 3. 4. All columns specified in <column list> should exist in the tables at both sides. An equi-join (<left table>.<column> = <right table>.<column>) is automatically created for all columns (ANDed). The USING columns can be accessed without qualifiersin this case, the result is equivalent to COALESCE(<left table>.<column>, <right table>.<column>). In SELECT *, USING columns are expanded once, using the above rule.
Natural join 1. 2. A named columns join is automatically created with all columns common to the left and right tables. If there is no common column, a CROSS JOIN is created.
Examples
/* 1 */ select * from employee join department
52
CROSS JOIN
D. Yemanov (V.2.0.x) CROSS JOIN is now supported. Logically, this syntax pattern:
A CROSS JOIN B
or, simply:
FROM A, B
Performance Improvement at V.2.1.2 D. Yemanov In the rare case where a cross join of three or more tables involved table[s] that contained no records, extremely slow performance was reported (CORE-2200). A performance improvement was gained by teaching the optimizer not to waste time and effort on walking through populated tables in an attempt to find matches in empty tables.
53
Built-in Functions
(v.2.1) Some existing built-in functions have been enhanced, while a large number of new ones has been added. 54
Enhancements to Functions
A. dos Santos Fernandes EXTRACT(WEEK FROM DATE) Feature request CORE-663 The EXTRACT() function is extended to support the ISO-8601 ordinal week numbers. For example:
EXTRACT (WEEK FROM date '30.09.2007')
returns 39
alter table xyz add WeekOfTheYear computed by ( case when (extract(month from CertainDate) = 12) and (extract(week from CertainDate) = 1) then 'Week '||extract (WEEK from CertainDate)||' of year ' || (1 + (extract( year from CertainDate))) else 'Week '||extract (WEEK from CertainDate)||' of year ' ||extract( year from CertainDate) end )
55
Data Manipulation Language (DML) Specify the Scale for TRUNC() Feature request CORE-1340 In Beta 1 the implementation of the TRUNC() function supported only one argument, the value to be truncated. From Beta 2, an optional second argument can be supplied to specify the scale of the truncation. For example:
select trunc(987.65, 1), trunc(987.65, -1) from rdb$database;
returns 987.60, 980.00 For other examples of using TRUNC() with and without the optional scale argument, refer to the alphabetical listing of functions in Appendix A. Milliseconds Handling for EXTRACT(), DATEADD() and DATEDIFF() Feature request CORE-1387 From v.2.1 Beta 2, EXTRACT(), DATEADD() and DATEDIFF() can operate with milliseconds (represented as an integer number). For example:
EXTRACT ( MILLISECOND FROM timestamp '01.01.2000 01:00:00.1234' )
returns 123
DATEADD ( MILLISECOND, 100, timestamp '01.01.2000 01:00:00.0000' ) DATEDIFF ( MILLISECOND, timestamp '01.01.2000 02:00:00.0000', timestamp '01.01.2000 01:00:00.
For more explanatory examples of using DATEADD() and DATEDIFF(), refer to the alphabetical listing of functions in Appendix A.
IIF() Expression
O. Loa (V.2.0.x) An IIF() expression can be used as a shortcut for a CASE expression that tests exactly two conditions. It returns the value of the first sub-expression if the given search condition evaluates to TRUE, otherwise it returns a value of the second sub-expression.
IIF (<search_condition>, <value1>, <value2>)
Example
SELECT IIF(VAL > 0, VAL, -VAL) FROM OPERATION
Expression Arguments for SUBSTRING() O. Loa, D. Yemanov (V.2.0.x) The built-in function SUBSTRING() can now take arbitrary expressions in its parameters. Formerly, the inbuilt SUBSTRING() function accepted only constants as its second and third arguments (start position and length, respectively). Now, those arguments can be anything that resolves to a value, including host parameters, function results, expressions, subqueries, etc. Tip
If your attempts to use this feature fail with invalid token errors, bear in mind that expression arguments often need to be enclosed in brackets!
Changes to Results Returned from SUBSTRING() (V.2.1.x) To conform with standards, the character length of the result of applying SUBSTRING() to a VARCHAR or CHAR is now a VARCHAR of the same character length declared for or deduced from the value in the first argument. In Firebird 2.0 and 1.5, the returned value was a CHAR with the same character length as the declared or implied value of the first argument, too. That implementation could become a bug in Firebird 2.0 under conditions where the input string was a CHAR and the FOR argument was presented as an expression whose result was not known at the point where memory was prepared to receive the result string. The V.2.1 change addresses that. It is not necessary to redefine any PSQL variables you have declared to receive the results from SUBSTRING(). It is still correct to declare its size just big enough to accommodate the actual data returned. Just be sure that any FOR argument that is an expression cannot resolve to an integer that is larger than the number of characters declared for your variable. 57
Examples 1. When an alias is present it must be used; or no alias at all is allowed. a. This query was allowed in FB1.5 and earlier versions:
SELECT RDB$RELATIONS.RDB$RELATION_NAME FROM RDB$RELATIONS R
but will now correctly report an error that the field "RDB$RELATIONS.RDB$RELATION_NAME" could not be found. Use this (preferred):
SELECT R.RDB$RELATION_NAME FROM RDB$RELATIONS R
or this statement:
SELECT RDB$RELATION_NAME FROM RDB$RELATIONS R
58
Data Manipulation Language (DML) b. The statement below will now correctly use the FieldID from the subquery and from the updating table:
UPDATE TableA SET FieldA = (SELECT SUM(A.FieldB) FROM TableA A WHERE A.FieldID = TableA.FieldID)
Note
In Firebird it is possible to provide an alias in an update statement. Although many other database vendors do not support it, this capability should help those developers who have requested it to make Firebird's SQL more interchangeable with SQL database products that do support it.
c.
This example did not run correctly in Firebird 1.5 and earlier:
SELECT RDB$RELATIONS.RDB$RELATION_NAME, R2.RDB$RELATION_NAME FROM RDB$RELATIONS JOIN RDB$RELATIONS R2 ON (R2.RDB$RELATION_NAME = RDB$RELATIONS.RDB$RELATION_NAME)
If RDB$RELATIONS contained 90 records, it would return 90 * 90 = 8100 records, but in Firebird 2 it will correctly return 90 records. 2. a. This would except with a syntax error in Firebird 1.5, but is possible in Firebird 2:
SELECT (SELECT RDB$RELATION_NAME FROM RDB$DATABASE) FROM RDB$RELATIONS
b.
Ambiguity checking in subqueries: the query below would run in Firebird 1.5 without reporting an ambiguity, but will report it in Firebird 2:
SELECT (SELECT FIRST 1 RDB$RELATION_NAME FROM RDB$RELATIONS R1 JOIN RDB$RELATIONS R2 ON (R2.RDB$RELATION_NAME = R1.RDB$RELATION_NAME)) FROM RDB$DATABASE
59
For the client, the call isc_dsql_sql_info with the parameter isc_info_sql_stmt_type returns isc_info_sql_stmt_select if the block has output parameters. The semantics of a call is similar to a SELECT query: the client has a cursor open, can fetch data from it, and must close it after use. isc_info_sql_stmt_exec_procedure if the block has no output parameters. The semantics of a call is similar to an EXECUTE query: the client has no cursor and execution continues until it reaches the end of the block or is terminated by a SUSPEND. The client should preprocess only the head of the SQL statement or use '?' instead of ':' as the parameter indicator because, in the body of the block, there may be references to local variables or arguments with a colon prefixed. Example The user SQL is
EXECUTE BLOCK (X INTEGER = :X) RETURNS (Y VARCHAR) AS DECLARE V INTEGER; BEGIN INSERT INTO T(...) VALUES (... :X ...); SELECT ... FROM T INTO :Y; SUSPEND; END
60
Derived Tables
A. Brinkman Implemented support for derived tables in DSQL (subqueries in FROM clause) as defined by SQL200X. A derived table is a set, derived from a dynamic SELECT statement. Derived tables can be nested, if required, to build complex queries and they can be involved in joins as though they were normal tables or views. Syntax Pattern
SELECT <select list> FROM <table reference list> <table reference list> ::= <table reference> [{<comma> <table reference>}...] <table reference> ::= <table primary> | <joined table> <table primary> ::= <table> [[AS] <correlation name>] | <derived table> <derived table> ::= <query expression> [[AS] <correlation name>] [<left paren> <derived column list> <right paren>] <derived column list> ::= <column name> [{<comma> <column name>}...]
61
Points to Note Every column in the derived table must have a name. Unnamed expressions like constants should be added with an alias or the column list should be used. The number of columns in the column list should be the same as the number of columns from the query expression. The optimizer can handle a derived table very efficiently. However, if the derived table is involved in an inner join and contains a subquery, then no join order can be established and performance will suffer.
ROWS Syntax
D. Yemanov ROWS syntax is used to limit the number of rows retrieved from a select expression. For an uppermost-level select statement, it would specify the number of rows to be returned to the host program. A more understandable alternative to the FIRST/SKIP clauses, the ROWS syntax accords with the latest SQL standard and brings some extra benefits. It can be used in unions, any kind of subquery and in UPDATE or DELETE statements. It is available in both DSQL and PSQL. Syntax Pattern
SELECT ... [ORDER BY <expr_list>] ROWS <expr1> [TO <expr2>]
Examples 1.
SELECT * FROM T1 UNION ALL SELECT * FROM T2 ORDER BY COL ROWS 10 TO 100
2.
SELECT COL1, COL2, ( SELECT COL3 FROM T3 ORDER BY COL4 DESC ROWS 1 ) FROM T4
3.
DELETE FROM T5 ORDER BY COL5 ROWS 1
Points to Note 1. When <expr2> is omitted, then ROWS <expr1> is semantically equivalent to FIRST <expr1>. When both <expr1> and <expr2> are used, then ROWS <expr1> TO <expr2> means the same as FIRST (<expr2> - <expr1> + 1) SKIP (<expr1> - 1) There is nothing that is semantically equivalent to a SKIP clause used without a FIRST clause.
2.
ii.
iii. The characterset/collation is used from the first character string data type in DTS. b. If all of the data types in DTS are exact numeric, then the result data type is exact numeric with scale equal to the maximum of the scales of the data types in DTS and the maximum precision of all data types in DTS. Note
NOTE :: Checking for precision overflows is done at run-time only. The developer should take measures to avoid the aggregation resolving to a precision overflow.
c.
If any data type in DTS is approximate numeric, then each data type in DTS shall be numeric else an error is thrown. If some data type in DTS is a date/time data type, then every data type in DTS shall be a date/time data type having the same date/time type.
d.
64
Data Manipulation Language (DML) e. If any data type in DTS is BLOB, then each data type in DTS shall be BLOB and all with the same sub-type.
Examples 1.
SELECT * FROM T1 JOIN T2 ON T1.NAME IS NOT DISTINCT FROM T2.NAME;
2.
SELECT * FROM T WHERE T.MARK IS DISTINCT FROM 'test';
Points to note
1. Because the DISTINCT predicate considers that two NULL values are not distinct, it never evaluates to the truth value UNKNOWN. Like the IS [NOT] NULL predicate, it can only be True or False.
65
Note
All such expressions evaluate to NULL. The change does not alter nullability-aware semantics of the engine, it simply relaxes the syntax restrictions a little.
Examples
Database: proc.fdb SQL> create table gnull(a int); SQL> insert into gnull values(null); SQL> insert into gnull values(1); SQL> select a from gnull order by a; A ============ <null> 1 SQL> select a from gnull order by a asc; A ============ <null> 1 SQL> select a from gnull order by a desc; A
66
SQL> select a from gnull order by a desc nulls last; A ============ 1 <null> SQL> select a from gnull order by a desc nulls first; A ============ <null> 1
67
or
DELETE ... FROM ... [PLAN <plan items>] [ORDER BY <value list>] [ROWS <value> [TO <value>]]
Examples
1. SELECT CURRENT_TIME FROM RDB$DATABASE; 2. SELECT CURRENT_TIME(3) FROM RDB$DATABASE; 3. SELECT CURRENT_TIMESTAMP(3) FROM RDB$DATABASE;
Note
1. 2. The maximum possible precision is 3 which means accuracy of 1/1000 second (one millisecond). This accuracy may be improved in the future versions. If no seconds precision is specified, the following values are implicit: 0 for CURRENT_TIME 3 for CURRENT_TIMESTAMP
68
These functions are really a form of external function that exists inside the database instead of being called from a dynamically loaded library. The following declarations are made automatically by the engine at database creation time: Declaration
DECLARE EXTERNAL FUNCTION RDB$GET_CONTEXT VARCHAR(80), VARCHAR(80) RETURNS VARCHAR(255) FREE_IT; DECLARE EXTERNAL FUNCTION RDB$SET_CONTEXT VARCHAR(80), VARCHAR(80), VARCHAR(255) RETURNS INTEGER BY VALUE;
Usage RDB$SET_CONTEXT and RDB$GET_CONTEXT set and retrieve the current value of a context variable. Groups of context variables with similar properties are identified by Namespace identifiers. The namespace determines the usage rules, such as whether the variables may be read and written to, and by whom. Note
Namespace and variable names are case-sensitive.
RDB$GET_CONTEXT retrieves current value of a variable. If the variable does not exist in namespace, the function returns NULL. RDB$SET_CONTEXT sets a value for specific variable, if it is writable. The function returns a value of 1 if the variable existed before the call and 0 otherwise. To delete a variable from a context, set its value to NULL. Pre-defined Namespaces A fixed number of pre-defined namespaces is available: 69
USER_SESSION Offers access to session-specific user-defined variables. You can define and set values for variables with any name in this context. USER_TRANSACTION Offers similar possibilities for individual transactions. SYSTEM Provides read-only access to the following variables: NETWORK_PROTOCOL :: The network protocol used by client to connect. Currently used values: TCPv4, WNET, XNET and NULL. CLIENT_ADDRESS :: The wire protocol address of the remote client, represented as a string. The value is an IP address in form "xxx.xxx.xxx.xxx" for TCPv4 protocol; the local process ID for XNET protocol; and NULL for any other protocol. DB_NAME :: Canonical name of the current database. It is either the alias name (if connection via file names is disallowed DatabaseAccess = NONE) or, otherwise, the fully expanded database file name. ISOLATION_LEVEL :: The isolation level of the current transaction. The returned value will be one of "READ COMMITTED", "SNAPSHOT", "CONSISTENCY". TRANSACTION_ID :: The numeric ID of the current transaction. The returned value is the same as would be returned by the CURRENT_TRANSACTION pseudo-variable. SESSION_ID :: The numeric ID of the current session. The returned value is the same as would be returned by the CURRENT_CONNECTION pseudo-variable. CURRENT_USER :: The current user. The returned value is the same as would be returned by the CURRENT_USER pseudo-variable or the predefined variable USER. CURRENT_ROLE :: Current role for the connection. Returns the same value as the CURRENT_ROLE pseudo-variable.
Notes To avoid DoS attacks against the Firebird Server, the number of variables stored for each transaction or session context is limited to 1000. Example of Use
set term ^; create procedure set_context(User_ID varchar(40), Trn_ID integer) as begin RDB$SET_CONTEXT('USER_TRANSACTION', 'Trn_ID', Trn_ID); RDB$SET_CONTEXT('USER_TRANSACTION', 'User_ID', User_ID); end ^
70
create table journal ( jrn_id integer not null primary key, jrn_lastuser varchar(40), jrn_lastaddr varchar(255), jrn_lasttransaction integer )^ CREATE TRIGGER UI_JOURNAL FOR JOURNAL BEFORE INSERT OR UPDATE as begin new.jrn_lastuser = rdb$get_context('USER_TRANSACTION', 'User_ID'); new.jrn_lastaddr = rdb$get_context('SYSTEM', 'CLIENT_ADDRESS'); new.jrn_lasttransaction = rdb$get_context('USER_TRANSACTION', 'Trn_ID'); end ^ commit ^ execute procedure set_context('skidder', 1) ^ insert into journal(jrn_id) values(0) ^ set term ;^
Since rdb$set_context returns 1 or zero, it can be made to work with a simple SELECT statement. Example
SQL> select rdb$set_context('USER_SESSION', 'Nickolay', 'ru') CNT> from rdb$database; RDB$SET_CONTEXT =============== 0
71
RDB$SET_CONTEXT =============== 0
Syntax rules The following schema describing the syntax rules should be helpful when composing plans.
PLAN ( { <stream_retrieval> | <sorted_streams> | <joined_streams> } ) <stream_retrieval> ::= { <natural_scan> | <indexed_retrieval> | <navigational_scan> } <natural_scan> ::= <stream_alias> NATURAL <indexed_retrieval> ::= <stream_alias> INDEX ( <index_name> [, <index_name> ...] ) <navigational_scan> ::= <stream_alias> ORDER <index_name> [ INDEX ( <index_name> [, <index_name> ...] ) ] <sorted_streams> ::= SORT ( <stream_retrieval> ) <joined_streams> ::= JOIN ( <stream_retrieval>, <stream_retrieval> [, <stream_retrieval> ...] ) | [SORT] MERGE ( <sorted_streams>, <sorted_streams> )
Details Natural scan means that all rows are fetched in their natural storage order. Thus, all pages must be read before search criteria are validated. Indexed retrieval uses an index range scan to find row ids that match the given search criteria. The found matches are combined in a sparse bitmap which is sorted by page numbers, so every data page will be read only once. After that the table pages are read and required rows are fetched from them. Navigational scan uses an index to return rows in the given order, if such an operation is appropriate. The index b-tree is walked from the leftmost node to the rightmost one.
72
Data Manipulation Language (DML) If any search criterion is used on a column specified in an ORDER BY clause, the navigation is limited to some subtree path, depending on a predicate. If any search criterion is used on other columns which are indexed, then a range index scan is performed in advance and every fetched key has its row id validated against the resulting bitmap. Then a data page is read and the required row is fetched. Note
Note that a navigational scan incurs random page I/O, as reads are not optimized.
A sort operation performs an external sort of the given stream retrieval. A join can be performed either via the nested loops algorithm (JOIN plan) or via the sort merge algorithm (MERGE plan). An inner nested loop join may contain as many streams as are required to be joined. All of them are equivalent. An outer nested loops join always operates with two streams, so you'll see nested JOIN clauses in the case of 3 or more outer streams joined. A sort merge operates with two input streams which are sorted beforehand, then merged in a single run. Examples
SELECT RDB$RELATION_NAME FROM RDB$RELATIONS WHERE RDB$RELATION_NAME LIKE 'RDB$%' PLAN (RDB$RELATIONS NATURAL) ORDER BY RDB$RELATION_NAME SELECT R.RDB$RELATION_NAME, RF.RDB$FIELD_NAME FROM RDB$RELATIONS R JOIN RDB$RELATION_FIELDS RF ON R.RDB$RELATION_NAME = RF.RDB$RELATION_NAME PLAN MERGE (SORT (R NATURAL), SORT (RF NATURAL))
Notes 1. A PLAN clause may be used in all select expressions, including subqueries, derived tables and view definitions. It can be also used in UPDATE and DELETE statements, because they're implicitly based on select expressions. If a PLAN clause contains some invalid retrieval description, then either an error will be returned or this bad clause will be silently ignored, depending on severity of the issue. ORDER <navigational_index> INDEX ( <filter_indices> ) kind of plan is reported by the engine and can be used in the user-supplied plans starting with FB 2.0.
2.
3.
Improvements in Sorting
A. Brinkman Some useful improvements have been made to SQL sorting operations: 73
2.
GROUP BY
SELECT RDB$RELATION_NAME AS ID, COUNT(*) FROM RDB$RELATION_FIELDS GROUP BY ID
Data Manipulation Language (DML) list of the ordering column or derived field. If a parameter is accepted by the parser, the output will undergo a dummy sort and the returned set will be unsorted.
2.
INSERT INTO EMPLOYEE (ID, NAME) VALUES (NEXT VALUE FOR S_EMPLOYEE, 'John Smith');
Note
1. Currently, increment ("step") values not equal to 1 (one) can be used only by calling the GEN_ID function. Future versions are expected to provide full support for SQL-99 sequence generators, which allows the required increment values to be specified at the DDL level. Unless there is a vital need to use a step value that is not 1, use of a NEXT VALUE FOR value expression instead of the GEN_ID function is recommended. GEN_ID(<name>, 0) allows you to retrieve the current sequence value, but it should never be used in insert/update statements, as it produces a high risk of uniqueness violations in a concurrent environment.
2.
Articles
SELECT Statement & Expression Syntax
Dmitry Yemanov About the semantics A select statement is used to return data to the caller (PSQL module or the client program) Select expressions retrieve parts of data that construct columns that can be in either the final result set or in any of the intermediate sets. Select expressions are also known as subqueries. Syntax rules
<select statement> ::= <select expression> [FOR UPDATE] [WITH LOCK]
75
<select expression> ::= <query specification> [UNION [{ALL | DISTINCT}] <query specification>] <query specification> ::= SELECT [FIRST <value>] [SKIP <value>] <select list> FROM <table expression list> WHERE <search condition> GROUP BY <group value list> HAVING <group condition> PLAN <plan item list> ORDER BY <sort value list> ROWS <value> [TO <value>] <table expression> ::= <table name> | <joined table> | <derived table> <joined table> ::= {<cross join> | <qualified join>} <cross join> ::= <table expression> CROSS JOIN <table expression> <qualified join> ::= <table expression> [{INNER | {LEFT | RIGHT | FULL} [OUTER]}] JOIN <table expression> ON <join condition> <derived table> ::= '(' <select expression> ')'
Conclusions FOR UPDATE mode and row locking can only be performed for a final dataset, they cannot be applied to a subquery Unions are allowed inside any subquery Clauses FIRST, SKIP, PLAN, ORDER BY, ROWS are allowed for any subquery Notes Either FIRST/SKIP or ROWS is allowed, but a syntax error is thrown if you try to mix the syntaxes An INSERT statement accepts a select expression to define a set to be inserted into a table. Its SELECT part supports all the features defined for select statments/expressions UPDATE and DELETE statements are always based on an implicit cursor iterating through its target table and limited with the WHERE clause. You may also specify the final parts of the select expression syntax to limit the number of affected rows or optimize the statement. Clauses allowed at the end of UPDATE/DELETE statements are PLAN, ORDER BY and ROWS.
Data Manipulation Language (DML) or buffer for such results and is mystified when a request returns a data type exception. The rules followed by the engine in determining the data type for an output column under these conditions are explained here. 1. 2. 3. Let DTS be the set of data types over which we must determine the final result data type. All of the data types in DTS shall be comparable. In the case that a. any of the data types in DTS is character string i. If all data types in DTS are fixed-length character strings, then the result is also a fixed-length character string; otherwise the result is a variable-length character string. The resulting string length, in characters, is equal to the maximum of the lengths, in characters, of the data types in DTS. ii. The character set and collation used are taken from the data type of the first character string in DTS.
b.
all of the data types in DTS are exact numeric the result data type is exact numeric with scale equal to the maximum of the scales of the data types in DTS and precision equal to the maximum precision of all data types in DTS.
c.
any data type in DTS is approximate numeric each data type in DTS must be numeric, otherwise an error is thrown.
d.
any data type in DTS is a date/time data type every data type in DTS must be a date/time type having the same date/time type, otherwise an error is thrown.
e.
any data type in DTS is BLOB each data type in DTS must be BLOB and all with the same sub-type.
In a database of ODS 10 or higher, that statement returns the string 'NOW'. We have had to learn to cast the date literal to get the result we want:
77
For a long timeprobably since IB 6 there has been an undocumented short expression syntax for casting not just the predefined date/time literals but any date literals. Actually, it is defined in the standard. Most of us were just not aware that it was available. It takes the form <data type> <date literal>. Taking the CAST example above, the short syntax would be as follows:
select TIMESTAMP 'NOW' from rdb$database
This short syntax can participate in other expressions. The following example illustrates a date/time arithmetic operation on a predefined literal:
update mytable set OVERDUE = 'T' where DATE 'YESTERDAY' - DATE_DUE > 10
78
Chapter 7
Quick Links
Domains in PSQL COLLATE in Stored Procedures WHERE CURRENT OF for Views ROW_COUNT Counts Rows Returned by SELECT Explicit Cursors Stored Procedure Arguments Can Take Defaults LEAVE <label> Flow Control Operator OLD Variables Now Read-only Stack Trace for PSQL Exceptions Call UDFs as Procedures
Domains in PSQL
Adriano dos Santos Fernandes (V.2.1) It is now possible to use a domain when declaring the data types of arguments and variables in PSQL modules. Depending on your requirements, you can declare the argument or variable using the domain identifier alone, in lieu of the native data type identifier, to have the variable inherit all of the attributes of the domain; or the data type of the domain, without inheriting CHECK constraints and the DEFAULT value (if declared in the domain), by including the TYPE OF keyword in the declaration (see the syntax below) Syntax
data_type ::= <builtin_data_type> | <domain_name> | TYPE OF <domain_name>
Examples
CREATE DOMAIN DOM AS INTEGER; CREATE PROCEDURE SP ( I1 TYPE OF DOM, I2 DOM)
79
Note
A new field RDB$VALID_BLR was added in RDB$PROCEDURES and RDB$TRIGGERS to indicate whether the procedure/trigger is valid after an ALTER DOMAIN operation. The value of RDB$VALID_BLR is shown in the ISQL commands SHOW PROCEDURE or SHOW TRIGGER.
80
See also its usage in the examples below for explicit PSQL cursors.
Explicit Cursors
D. Yemanov It is now possible to declare and use multiple cursors in PSQL. Explicit cursors are available in a DSQL EXECUTE BLOCK structure as well as in stored procedures and triggers. Syntax pattern
DECLARE [VARIABLE] <cursor_name> CURSOR FOR ( <select_statement> ); OPEN <cursor_name>; FETCH <cursor_name> INTO <var_name> [, <var_name> ...]; CLOSE <cursor_name>;
Examples 1.
DECLARE RNAME CHAR(31); DECLARE C CURSOR FOR ( SELECT RDB$RELATION_NAME FROM RDB$RELATIONS ); BEGIN OPEN C; WHILE (1 = 1) DO BEGIN FETCH C INTO :RNAME; IF (ROW_COUNT = 0) THEN LEAVE; SUSPEND; END CLOSE C; END
2.
DECLARE RNAME CHAR(31); DECLARE FNAME CHAR(31); DECLARE C CURSOR FOR ( SELECT RDB$FIELD_NAME FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME = :RNAME ORDER BY RDB$FIELD_POSITION ); BEGIN FOR SELECT RDB$RELATION_NAME
81
Note
Cursor declaration is allowed only in the declaration section of a PSQL block/procedure/trigger, as with any regular local variable declaration. Cursor names are required to be unique in the given context. They must not conflict with the name of another cursor that is "announced", via the AS CURSOR clause, by a FOR SELECT cursor. However, a cursor can share its name with any other type of variable within the same context, since the operations available to each are different. Positioned updates and deletes with cursors using the WHERE CURRENT OF clause are allowed. Attempts to fetch from or close a FOR SELECT cursor are prohibited. Attempts to open a cursor that is already open, or to fetch from or close a cursor that is already closed, will fail. All cursors which were not explicitly closed will be closed automatically on exit from the current PSQL block/procedure/trigger. The ROW_COUNT system variable can be used after each FETCH statement to check whether any row was returned.
83
Note
1. 2. The source and BLR for the argument defaults are stored in RDB$FIELDS. As was pointed out in a Tracker entry, the examples above should not be taken as a recommendation to use a SUSPEND statement to handle return values in an executable stored procedure. The author used SUSPEND here in order to illustrate the aspects of the new feature.
where <loop_statement> is one of: WHILE, FOR SELECT, FOR EXECUTE STATEMENT. Examples 1.
FOR SELECT COALESCE(RDB$SYSTEM_FLAG, 0), RDB$RELATION_NAME FROM RDB$RELATIONS ORDER BY 1 INTO :RTYPE, :RNAME
84
2.
CNT = 100; L1: WHILE (CNT >= 0) DO BEGIN IF (CNT < 50) THEN LEAVE L1; -- exists WHILE loop CNT = CNT - l; END
3.
STMT1 = 'SELECT RDB$RELATION_NAME FROM RDB$RELATIONS'; L1: FOR EXECUTE STATEMENT :STMT1 INTO :RNAME DO BEGIN STMT2 = 'SELECT RDB$FIELD_NAME FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME = '; L2: FOR EXECUTE STATEMENT :STMT2 || :RNAME INTO :FNAME DO BEGIN IF (RNAME = 'RDB$DATABASE') THEN LEAVE L1; -- exits the outer loop ELSE IF (RNAME = 'RDB$RELATIONS') THEN LEAVE L2; -- exits the inner loop ELSE SUSPEND; END END
Note
Note that LEAVE without an explicit label means interrupting the current (innermost) loop.
Note
NEW context variables are now read-only in AFTER-triggers as well.
SQL" INSERT INTO ERR VALUES (2, '2'); Statement failed, SQLCODE = -836 exception 3 -ID = 2 -At trigger 'ERR_BI'
87
88
Chapter 8
89
90
91
Chapter 9
with both performing a single record read. However, formerly, the first query required three indexed reads while the second one required just the expected single read. Now, they both resolve to a single read. The same optimization applies to the MAX() function when mapped to a DESC index.
For more details, please refer to the topic Query Plans Improvements in the DML chapter.
Optimizer Improvements
This section represents a collection of changes done in Firebird 2 to optimize many aspects of performance.
92
Enhancements to Indexing
252-byte index length limit is gone
A. Brinkman New and reworked index code is very fast and tolerant of large numbers of duplicates. The old aggregate key length limit of 252 bytes is removed. Now the limit depends on page size: the maximum size of the key in bytes is 1/4 of the page size (512 on 2048, 1024 on 4096, etc.) A 40-bit record number is included on non leaf-level pages and duplicates (key entries) are sorted by this number.
Expression Indexes
O. Loa, D. Yemanov, A. Karyakin Arbitrary expressions applied to values in a row in dynamic DDL can now be indexed, allowing indexed access paths to be available for search predicates that are based on expressions. Syntax Pattern
CREATE [UNIQUE] [ASC[ENDING] | DESC[ENDING]] INDEX <index name> ON <table name> COMPUTED BY ( <value expression> )
Examples 1.
95
2.
CREATE INDEX IDX2 ON T2 COMPUTED BY ( EXTRACT(YEAR FROM COL2) || EXTRACT(MONTH FROM COL2) ); COMMIT; /* */ SELECT * FROM T2 ORDER BY EXTRACT(YEAR FROM COL2) || EXTRACT(MONTH FROM COL2) -- PLAN (T2 ORDER IDX2)
Note
1. The expression used in the predicate must match exactly the expression used in the index declaration, in order to allow the engine to choose an indexed access path. The given index will not be available for any retrieval or sorting operation if the expressions do not match. Expression indices have exactly the same features and limitations as regular indices, except that, by definition, they cannot be composite (multi-segment).
2.
97
Chapter 10
Architecture
Firebird allows character sets and collations to be declared in any character field or variable declaration. The default character set can also be specified at database create time, to cause every CHAR/VARCHAR declaration that does not specifically include a CHARACTER SET clause to use this default. At attachment time you normally specify the character set that the client is to use to read strings. If no "client" (or "connection") character set is specified, character set NONE is assumed. Two special character sets, NONE and OCTETS, can be used in declarations. However, OCTETS cannot be used as a connection character set. The two sets are similar, except that the space character of NONE is ASCII 0x20, whereas the space character OCTETS is 0x00. NONE and OCTETS are special in the sense that they follow different rules from those applicable to other character sets regarding conversions. With other character sets, conversion is performed as CHARSET1->UNICODE->CHARSET2. With NONE/OCTETS the bytes are just copied: NONE/OCTETS->CHARSET2 and CHARSET1->NONE/ OCTETS.
Enhancements
Enhancements that the new system brings include:
Well-formedness checks
Some character sets (especially multi-byte) do not accept just any string. Now, the engine verifies that strings are well-formed when assigning from NONE/OCTETS and when strings sent by the client (the statement string and parameters). 98
Uppercasing
In Firebird 1.5.x, only the ASCII-equivalent characters are uppercased in any character set's default (binary) collation order, which is the one that is used if no collation is specified. For example,
isql SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> -q -ch create create insert insert insert insert dos850 database 'test.fdb'; table t (c char(1) character set dos850); into t values ('a'); into t values ('e'); into t values (''); into t values ('');
99
COLLATE clauses for BLOBs A DML COLLATE clause is now allowed with BLOBs. Example
select blob_column from table where blob_column collate unicode = 'foo';
Full equality comparisons between BLOBs Comparison can be performed on the entire content of a text BLOB.
Character set conversion for BLOBs Conversion between character sets is now possible when assigning to a BLOB from a string or another BLOB
INTL Plug-ins
Character sets and collations are installed using a manifest file. The manifest file should be put in the $rootdir/intl with a .conf extension. It is used to locate character sets and collations in the libraries. If a character set/collation is declared more than once, it is not loaded and the error is reported in the log. The file /intl/fbintl.conf is an example of a manifest file. The following snippet is an excerpt from / intl/fbintl.conf:
<intl_module fbintl> filename $(this)/fbintl </intl_module> <charset ISO8859_1> intl_module fbintl collation ISO8859_1 collation DA_DA collation DE_DE collation EN_UK collation EN_US collation ES_ES collation PT_BR collation PT_PT </charset> <charset WIN1250>
100
Note
The symbol $(this) is used to indicate the same directory as the manifest file and the library extension should be omitted.
101
Developments in V.2.1
The 2.1 release sees further capabilities implemented for 1. 2. 3. 4. 5. 6. 7. using ICU charsets through fbintl UNICODE collation (charset_UNICODE) being available for all fbintl charsets using collation attributes CREATE/DROP COLLATION statements SHOW COLLATION and collation extraction in ISQL Verifying that text blobs are well-formed Transliterating text blobs automatically
Registering a Character Set on the Server Using a text editor, register the module in intl/fbintl.conf, as follows.<charset intl_module collation </charset> NAME> fbintl NAME [REAL-NAME]
102
Registering a Character Set in a Database To register the module in a database, run the procedure sp_register_character_set, the source for which can be found in misc/intl.sql beneath your Firebird 2.1 root Using the Stored Procedure A Sample Here is the sample declaration in fbintl.conf:
<charset intl_module collation </charset> GB> fbintl GB GB18030
The stored procedure takes two arguments: a string that is the character set's identifier as declared in the configuration file and a smallint that is the maximum number of bytes a single character can occupy in the encoding. For our example:
execute procedure sp_register_character_set ('GB', 4);
Note
Specific attributes should be separated by semicolon and are case sensitive.
Examples
/* 1 */ CREATE COLLATION UNICODE_ENUS_CI FOR UTF8 FROM UNICODE CASE INSENSITIVE 'LOCALE=en_US'; /* 2 */ CREATE COLLATION NEW_COLLATION FOR WIN1252
103
Note
The character set name should be as in fbintl.conf (i.e. ISO8859_1 instead of ISO88591, for example).
DISABLE-COMPRESSIONS Disable compressions (aka contractions) changing the order of a group of characters. Valid for collations of narrow character sets. Format: DISABLE-COMPRESSIONS={0 | 1} Example DISABLE-COMPRESSIONS=1 DISABLE-EXPANSIONS Disable expansions changing the order of a character to sort as a group of characters. Valid for collations of narrow character sets. Format: DISABLE-EXPANSIONS={0 | 1} 104
International Language Support (INTL) Example DISABLE-EXPANSIONS=1 ICU-VERSION Specify what version of ICU library will be used. Valid values are the ones defined in the config file (intl/ fbintl.conf) in entry intl_module/icu_versions. Valid for UNICODE and UNICODE_CI. Format: ICU-VERSION={default | major.minor} Example ICU-VERSION=3.0 LOCALE Specify the collation locale. Valid for UNICODE and UNICODE_CI. Requires complete version of ICU libraries. Format: LOCALE=xx_XX Example LOCALE=en_US MULTI-LEVEL Uses more than one level for ordering purposes. Valid for collations of narrow character sets. Format: MULTI-LEVEL={0 | 1} Example MULTI-LEVEL=1 SPECIALS-FIRST Order special characters (spaces, symbols, etc) before alphanumeric characters. Valid for collations of narrow character sets. Format: SPECIALS-FIRST={0 | 1} Example SPECIALS-FIRST=1
Note
The attributes are stored at database creation time, so the changes do not apply to databases with ODS < 11.1.
The ES_ES_CI_AI collation was standardised to current usage. UTF-8 Case-insensitive collation for UTF-8. See feature request CORE-972
2.
In reads from text BLOBs, transliteration from the BLOB character set to the client character set was not being performed.
106
The rdb$check_metadata procedure will return all objects that are touched by it. If no exception is raised, your metadata is OK and you can go to the section Remove the upgrade procedures. Otherwise, the first bad object is the last one listed before the exception.
The rdb$fix_metadata procedure will return the same data as rdb$check_metadata, but it will change the metadata texts. Important
It should be run once!
107
Chapter 11
Administrative Features
Firebird is gradually adding new features to assist in the administration of databases. Firebird 2.1 sees the introduction of a new set of system tables through which administrators can monitor transactions and statements that are active in a database. These facilities employ a new v.2.1 DDL feature, Global Temporary Tables to provide snapshots.
Monitoring Tables
Dmitry Yemanov Firebird 2.1 introduces the ability to monitor server-side activity happening inside a particular database. The engine offers a set of so-called virtual tables that provides the user with a snapshot of the current activity within the given database. The word virtual means that the table data is not materialised until explicitly asked for. However, the metadata of the virtual table is stable and can be retrieved from the schema. Note
Virtual monitoring tables exist only in ODS 11.1 (and higher) databases, so a migration via backup/restore is required in order to use this feature.
The Concept
The key term of the monitoring feature is an activity snapshot. It represents the current state of the database, comprising a variety of information about the database itself, active attachments and users, transactions, prepared and running statements, and more. A snapshot is created the first time any of the monitoring tables is being selected from in the given transaction and it is preserved until the transaction ends, in order that multiple-table queries (e.g., master-detail ones) will always return a consistent view of the data. In other words, the monitoring tables always behave like a snapshot table stability (consistency) transaction, even if the host transaction has been started with a lower isolation level. To refresh the snapshot, the current transaction should be finished and the monitoring tables should be queried in a new transaction context.
Administrative Features
Metadata
MON$DATABASE (connected database) - MON$DATABASE_NAME (database pathname or alias) - MON$PAGE_SIZE (page size) - MON$ODS_MAJOR (major ODS version) - MON$ODS_MINOR (minor ODS version) - MON$OLDEST_TRANSACTION (OIT number) - MON$OLDEST_ACTIVE (OAT number) - MON$OLDEST_SNAPSHOT (OST number) - MON$NEXT_TRANSACTION (next transaction number) - MON$PAGE_BUFFERS (number of pages allocated in the cache) - MON$SQL_DIALECT (SQL dialect of the database) - MON$SHUTDOWN_MODE (current shutdown mode) 0: online 1: multi-user shutdown 2: single-user shutdown 3: full shutdown - MON$SWEEP_INTERVAL (sweep interval) - MON$READ_ONLY (read-only flag) - MON$FORCED_WRITES (sync writes flag) - MON$RESERVE_SPACE (reserve space flag) - MON$CREATION_DATE (creation date/time) - MON$PAGES (number of pages allocated on disk) - MON$BACKUP_STATE (current physical backup state) 0: normal 1: stalled 2: merge - MON$STAT_ID (statistics ID)
MON$ATTACHMENTS (connected attachments) - MON$ATTACHMENT_ID (attachment ID) - MON$SERVER_PID (server process ID) - MON$STATE (attachment state) 0: idle 1: active - MON$ATTACHMENT_NAME (connection string) - MON$USER (user name) - MON$ROLE (role name) - MON$REMOTE_PROTOCOL (remote protocol name) 109
Administrative Features - MON$REMOTE_ADDRESS (remote address) - MON$REMOTE_PID (remote client process ID) - MON$REMOTE_PROCESS (remote client process pathname) - MON$CHARACTER_SET_ID (attachment character set) - MON$TIMESTAMP (connection date/time) - MON$GARBAGE_COLLECTION (garbage collection flag) - MON$STAT_ID (statistics ID)
columns MON$REMOTE_PID and MON$REMOTE_PROCESS contains non-NULL values only if the client library is version 2.1 or higher column MON$REMOTE_PROCESS can contain a non-pathname value if an application has specified a custom process name via DPB column MON$GARBAGE_COLLECTION indicates whether GC is allowed for this attachment (as specified via the DPB in isc_attach_database). MON$TRANSACTIONS (started transactions) - MON$TRANSACTION_ID (transaction ID) - MON$ATTACHMENT_ID (attachment ID) - MON$STATE (transaction state) 0: idle (state after prepare, until execution begins) 1: active (state during execution and fetch. Idle state returns after cursor is closed) - MON$TIMESTAMP (transaction start date/time) - MON$TOP_TRANSACTION (top transaction) - MON$OLDEST_TRANSACTION (local OIT number) - MON$OLDEST_ACTIVE (local OAT number) - MON$ISOLATION_MODE (isolation mode) 0: consistency 1: concurrency 2: read committed record version 3: read committed no record version - MON$LOCK_TIMEOUT (lock timeout) -1: infinite wait 0: no wait N: timeout N - MON$READ_ONLY (read-only flag) - MON$AUTO_COMMIT (auto-commit flag) - MON$AUTO_UNDO (auto-undo flag) - MON$STAT_ID (statistics ID)
MON$TOP_TRANSACTION is the upper limit used by the sweeper transaction when advancing the global OIT. All transactions above this threshold are considered active. It is normally equivalent to the MON$TRANSACTION_ID but COMMIT RETAINING or ROLLBACK RETAINING will cause MON $TOP_TRANSACTION to remain unchanged (stuck) when the transaction ID is incremented. MON$AUTO_UNDO indicates the auto-undo status set for the transaction, i.e., whether a transaction-level savepoint was created. The existence of the transaction-level savepoint allows changes to be undone if ROLLBACK is called and the transaction is then just committed. If this savepoint does not
110
Administrative Features exist, or it does exist but the number of changes is very large, then an actual ROLLBACK is executed and the the transaction is marked in the TIP as dead. MON$STATEMENTS (prepared statements) - MON$STATEMENT_ID (statement ID) - MON$ATTACHMENT_ID (attachment ID) - MON$TRANSACTION_ID (transaction ID) - MON$STATE (statement state) 0: idle 1: active - MON$TIMESTAMP (statement start date/time) - MON$SQL_TEXT (statement text, if appropriate) - MON$STAT_ID (statistics ID) column MON$SQL_TEXT contains NULL for GDML statements columns MON$TRANSACTION_ID and MON$TIMESTAMP contain valid values for active statements only The execution plan and the values of parameters are not available MON$CALL_STACK (call stack of active PSQL requests) - MON$CALL_ID (call ID) - MON$STATEMENT_ID (top-level DSQL statement ID) - MON$CALLER_ID (caller request ID) - MON$OBJECT_NAME (PSQL object name) - MON$OBJECT_TYPE (PSQL object type) - MON$TIMESTAMP (request start date/time) - MON$SOURCE_LINE (SQL source line number) - MON$SOURCE_COLUMN (SQL source column number) - MON$STAT_ID (statistics ID) column MON$STATEMENT_ID groups call stacks by the top-level DSQL statement that initiated the call chain. This ID represents an active statement record in the table MON$STATEMENTS. columns MON$SOURCE_LINE and MON$SOURCE_COLUMN contain line/column information related to the PSQL statement currently being executed MON$IO_STATS (I/O statistics) - MON$STAT_ID (statistics ID) - MON$STAT_GROUP (statistics group) 0: database 1: attachment 2: transaction 3: statement 4: call - MON$PAGE_READS (number of page reads) - MON$PAGE_WRITES (number of page writes) - MON$PAGE_FETCHES (number of page fetches)
111
Administrative Features - MON$PAGE_MARKS (number of pages with changes pending) MON$RECORD_STATS (record-level statistics) - MON$STAT_ID (statistics ID) - MON$STAT_GROUP (statistics group) 0: database 1: attachment 2: transaction 3: statement 4: call - MON$RECORD_SEQ_READS (number of records read sequentially) - MON$RECORD_IDX_READS (number of records read via an index) - MON$RECORD_INSERTS (number of inserted records) - MON$RECORD_UPDATES (number of updated records) - MON$RECORD_DELETES (number of deleted records) - MON$RECORD_BACKOUTS (number of records where a new primary record version or a change to an existing primary record version is backed out due to rollback or savepoint undo) - MON$RECORD_PURGES (number of records where record version chain is being purged of versions no longer needed by OAT or younger transactions) - MON$RECORD_EXPUNGES (number of records where record version chain is being deleted due to deletions by transactions older than OAT)
Note
Textual descriptions of all state and mode values can be found in the system table RDB$TYPES.
Usage
Creation of a snapshot is usually quite a fast operation, but some delay could be expected under high load (especially in the Classic Server). For guidelines to minimising the impact of monitoring under such conditions, see Performance Guidelines, below. A valid database connection is required in order to retrieve the monitoring data. The monitoring tables return information about the attached database only. If multiple databases are being accessed on the server, each of them has to be connected to and monitored separately. The system variables CURRENT_CONNECTION and CURRENT_TRANSACTION could be used to select data about the caller's current connection and transaction respectively. These variables correspond to the ID columns of the appropriate monitoring tables. Examples 1. Retrieve IDs of all CS processes loading CPU at the moment
SELECT MON$SERVER_PID FROM MON$ATTACHMENTS
112
Administrative Features
WHERE MON$ATTACHMENT_ID <> CURRENT_CONNECTION AND MON$STATE = 1
2.
3.
4.
5.
113
Administrative Features
ON STMT.MON$STATEMENT_ID = HEAD.MON$STATEMENT_ID WHERE STMT.MON$ATTACHMENT_ID <> CURRENT_CONNECTION
Shared Memory
All server processes share some region of memory where the information about current activity is stored. The information consists of multiple variable-length items describing the details of various activities. All items belonging to a particular process are grouped into a single cluster, enabling them to be processed as a whole. Collection of the monitoring information and population of the tables do not happen in real time. Instead, server processes write their data into the shared memory only when explicitly asked to. Upon writing, the newer clusters supersede the old ones. Then, when the shared memory region is being read, the reading process scans all the clusters and performs garbage collection, removing clusters that belong to dead processes and compacting the shared memory space.
Notifications
Every server process has a flag that indicates its capability to react to someone's monitoring request as soon as it arrives. When some user connection runs a query against some monitoring table, the worker process of that connection sends a broadcast notification to other processes, requesting an up-to-date information. Those processes react to this request by updating their clusters inside the shared memory region and clearing their ready flags. Once every notified process has finished its update, the requesting process reads the shared memory region, filters the necessary tags according to its user permissions, transforms the internal representation into records and fields and populates the in-memory monitoring tables cache. 114
Administrative Features Any processes that have been idle since the last monitoring exchange have their ready flag clear, indicating that they have nothing to update in the shared memory. The clear flag means they will be ignored by the notification broadcast and will be exempt from making the next round trip. The ready flag is set as soon as something significant changes inside the process and the process starts responding to monitoring requests again.
Locking
While coordinating the write/read operations, the requester holds an exclusive lock that affects all user connections that are currently active as well as any connections with attachments in the process of being established. Multiple simultaneous monitoring requests are serialized.
2.
Sometimes, an out-of-memory condition can cause monitoring requests to fail, or cause other worker processes to swap. A major source of this problem is the fact that every record in MON$STATEMENTS has a blob MON$SQL_TEXT which is created for the duration of the monitoring transaction. In V.2.1.x, every blob occupies <page size> bytes of memory, even if its actual content is smaller. When the number of prepared statements in the system is huge, it becomes possible to exhaust memory and get this failure.
3.
Another possible source of this memory exhaustion could be the temporary (in practice, very short-lived) growth of the transaction pool into which the monitoring data are cached while the clusters are being merged into a single fragment. Note
There is no relief for this condition in v.2.1.3. However, it has been improved for v.2.5.0.
115
Administrative Features
For detailed information about using these context calls, refer to the v.2.0.1 release notes.
116
Chapter 12
Security
In this chapter are details of the changes to Firebird security that came with the release of Firebird 2 and its successors. Further changes and enhancements introduced in V.2.1 are highlighted.
Summary of Changes
Improving security has had a lot of focus in Firebird 2.0 development. The following is a summary of the major changes.
Security
Security
the lack of protection against remote brute-forcing of passwords on the server directly
Authentication
Firebird authentication checks a server-wide security database in order to decide whether a database or server connection request is authorised. The security database stores the user names and passwords of all authorised login identities.
Although this situation does not increase resistance to a brute-force attempt to crack the password, it does make "visual" analysis of a stolen password database much harder.
Security = ''". That worked due to another bug in the engine that left the SQL variable USER empty, not 'authenticator', as it might seem from engine's code. Once that bug was fixed, it was certainly possible to add the condition "USER = 'authenticator'". For the short term, that was OK, because the username is always converted to upper case. A better solution was found, that avoids making user authentication depend on an SQL trick. The result is that the non-SYSDBA user can see only his own login in any user-management tool (gsec, or any graphical interface that use the Services API). SYSDBA continues to have full access to manage users' accounts.
New security database structure The Firebird 2 security database is named security2.fdb. For user authentication it has a new table named RDB$USERS that stores the new hashed passwords. A view over this table replaces the old USERS table and enables users to change their own passwords. The DDL for the new structures can be found in Appendix C.
gsec in Firebird 2
Special measures were thus taken to make remote connection to the security database completely impossible. Don't be surprised if some old program fails on attempting direct access: this is by design. Users information may now be accessed only through the Services API and the equivalent internal access to services now implemented in the isc_user_* API functions.
Security Simply omitting the user and password parameters from the DPB/SPB will automatically cause Windows Trusted User authentication to be applied, in almost all cases. See the Environment section, below, for exceptions. Illustration Suppose you have logged in to the Windows server SRV as user 'John'. If you connect to server SRV with isql, without specifying a Firebird user name and password:
isql srv:employee
and do:
SQL> select CURRENT_USER from rdb$database;
SQL Privileges
Windows users can be granted rights to access database objects and roles in the same way as regular Firebird users, emulating the capability that has been always been available users of Unix and Linux hosted Firebird databases.
Administrators
If a local Adminstrator or a member of the built-in Domain Admins group connects to Firebird using trusted authentication, he/she will be connected as SYSDBA.
Security
Note
Trusted authentication can be coerced to override the environment variables if they are setrefer to the notes below.
Example
C:\Pr~\bin>isql srv:db -- log in using trusted authentication C:\Pr~\bin>set ISC_USER=user1 C:\Pr~\bin>set ISC_PASSWORD=12345 C:\Pr~\bin>isql srv:db -- log in as 'user1' from environment C:\Pr~\bin>isql -trust srv:db -- log in using trusted authentication
Important
Windows rules for full domain user names allow names longer than the maximum 31 characters allowed by Firebird for user names. The 31-character limit is enforced and, from V.2.1, logins passing longer names are disabled. This will remain the situation until the mapping of OS objects to database objects is implemented in a later Firebird version.
Security The main reason to restrict direct access to the security database was to protect it from access by old versions of client software. Fortuitously, it also minimizes the exposure of the embedded Classic on POSIX at the same time, since it is quite unlikely that the combination of an old client and the new server would be present on the production box.
An important security problem with Firebird still remains unresolved: the transmission of poorly encrypted passwords "in clear" across the network. It is not possible to resolve this problem without breaking old clients. To put it another way, a user who has set his/her password using a new secure method would be unable to use an older client to attach to the server. Taking this into account with plans to upgrade some aspects of the API in the next version, the decision was made not to change the password transmission method in Firebird 2.0. The immediate problem can be solved easily by using any IP-tunneling software (such as ZeBeDee) to move data to and from a Firebird server, for both 1.5 and 2.0. It remains the recommended way to access your remote Firebird server across the Internet.
Any user could view the server log through the Services API
Feature request CORE-1148 This was a minor security vulnerability. Regular users are now blocked from retrieving the server log using the Services API. Requests are explicitly checked to ensure that the authenticated user is SYSDBA.
Security database". It is not a bug: it is by design. A security database from an earlier Firebird version cannot be used directly in Firebird 2.0 or higher. The newly structured security database is named security2.fdb. In order to be able to use an old security database, it is necessary to run the upgrade script security_database.sql, that is in the ../upgrade sub-directory of your Firebird server installation. Note
A copy of the script appears in Appendix C.
2. 3. 4. 5. 6. 7.
Now you should be able to connect to the Firebird 2 server using your old logins and passwords.
Nullability of RDB$PASSWD
In pre-2.0 versions of Firebird it was possible to have a user with NULL password. From v.2.0 onward, the RDB $PASSWD field in the security database is constrained as NOT NULL. However, to avoid exceptions during the upgrade process, the field is created as nullable by the upgrade script. If you are really sure you have no empty passwords in the security database, you may modify the script yourself. For example, you may edit the line:
RDB$PASSWD RDB$PASSWD,
to be
RDB$PASSWD RDB$PASSWD NOT NULL,
124
Security
125
Chapter 13
Command-line Utilities
General Enhancements
Utilities Support for Database Triggers
(V. 2.1) A new parameter was added to gbak, nbackup and isql to suppress Database Triggers from running. It is available only to the database owner and SYSDBA:
gbak -nodbtriggers isql -nodbtriggers nbackup -T
Password Hiding
Alex Peshkov Command-line utilities that take a -password parameter are vulnerable to password sniffing, especially when the utility is run from a script. As a step towards hardening against this on POSIX platforms, the [PASSWORD] argument now displays the process list as an asterisk ( * ), where previously it showed in clear.
Firebird Services
New Command-line Utility fbsvcmgr
Alex Peshkov (V.2.1) The new utility fbsvcmgr provides a command-line interface to the Services API, enabling access to any service that is implemented in Firebird. Although there are numerous database administration tools around that surface the Services API through graphical interfaces, the new tool addresses the problem for admins needing to access remote Unix servers in broad networks through a text-only connection. Previously, meeting such a requirement needed a programmer.
Using fbsvcmgr
fbsvcmgr does not emulate the switches implemented in the traditional g* utilities. Rather, it is just a frontend through which the Services API functions and parameters can pass. Users therefore need to be familiar with the Services API as it stands currently. The API header fileibase.h, in the ../include directory of your Firebird installation should be regarded as the primary source of information about what is available, backed up by the InterBase 6.0 beta API Guide. 126
Command-line Utilities
Parameters Specify the Services Manager The first required parameter for a command line call is the Services Manager you want to connect to: For a local connection use the simple symbol service_mgr To attach to a remote host, use the format hostname:service_mgr Specify subsequent service parameter blocks (SPBs) Subsequent SPBs, with values if required, follow. Any SPB can be optionally prefixed with a single '-' symbol. For the long command lines that are typical for fbsvcmgr, use of the '-' improves the readability of the command line. Compare, for example, the following (each a single command line despite the line breaks printed here):
# fbsvcmgr service_mgr user sysdba password masterke action_db_stats dbname employee sts_hdr_pages
and
# fbsvcmgr service_mgr -user sysdba -password masterke -action_db_stats -dbname employee -sts_hdr_pages
SPB Syntax The SPB syntax that fbsvcmgr understands closely matches with what you would encounter in the ibase.h include file or the InterBase 6.0 API documentation, except that a slightly abbreviated form is used to reduce typing and shorten the command lines a little. Here's how it works. All SPB parameters have one of two forms: (1) isc_spb_VALUE or (2) isc_VALUE1_svc_VALUE2. For fbsvcmgr you just need to pick out the VALUE, VALUE1 or VALUE2 part[s] when you supply your parameter. Accordingly, for (1) you would type simply VALUE, while for (2) you would type VALUE1_VALUE2. For example:
isc_spb_dbname => dbname isc_action_svc_backup => action_backup isc_spb_sec_username => sec_username isc_info_svc_get_env_lock => info_get_env_lock
It is not realistic to attempt to describe all of the SPB parameters in release notes. In the InterBase 6.0 beta documentation it takes about 40 pages! The next section highlights some known differences between the operation of fbsvcmgr and what you might otherwise infer from the old beta documentation. 127
Command-line Utilities
fbsvcmgr Syntax Specifics Do's and Don'ts With fbsvcmgr you can perform a single actionand get its results if applicableor you can use it to retrieve multiple information items from the Services Manager. You cannot do both in a single command. For example,
# fbsvcmgr service_mgr -user sysdba -password masterke -action_display_user
...and...
# fbsvcmgr service_mgr -user sysdba -password masterke -info_server_version -info_implementation
raises an error:
Unknown switch -info_server_version
Undocumented Items The function isc_spb_rpr_list_limbo_trans was omitted from the IB6 beta documentation. It is supported in fbsvcmgr.
128
Command-line Utilities Support for New Services API Items in v.2.1 Two new items that were added to the Services API in Firebird 2.1 are supported by fbsvcmgr: isc_spb_trusted_auth (type it as trusted_auth) applies only to Windows. It forces Firebird to use Windows trusted authentication. isc_spb_dbname gives the ability to set a database name parameter (type as dbname) in all service actions related to accessing the security database from a remote client, equivalent to supplying the database switch to the gsec utility. Note
For gsec the -database switch is mostly used to specify a remote server you want to administer. In fbsvcmgr, the name of the server is already given in the first parameter (via the service_mgr symbol) so the [isc_spb_]dbname parameter is mostly unnecessary.
Documentation Bugs The format described for some parameters in the InterBase 6 beta documentation are buggy. When in trouble, treat ibase.h as the primary source for the correct form. Unsupported functions Everything to do with licensing was removed from the original InterBase 6 open source code and is therefore not supported either in Firebird or by fbsvcmgr. The old Config file view/modification functions have been unsupported since Firebird 1.5 and are not implemented by fbsvcmgr.
Backup Tools
Firebird 2 brings plenty of enhancements to backing up databases: a new utility for running on-line incremental backups and some improvements to gbak to avoid some of the traps that sometimes befall end-users. 129
Command-line Utilities
Nbak
The functional responsibilities of NBAK are: 1. 2. 3. 4. 5. to redirect writes to difference files when asked (ALTER DATABASE BEGIN BACKUP statement) to produce a GUID for the database snapshot and write it into the database header before the ALTER DATABASE BEGIN BACKUP statement returns to merge differences into the database when asked (ALTER DATABASE END BACKUP statement) to mark pages written by the engine with the current SCN [page scan] counter value for the database to increment SCN on each change of backup state
The backup state cycle is: nbak_state_normal -> nbak_state_stalled -> nbak_state_merge -> nbak_state_normal In normal state writes go directly to the main database files. In stalled state writes go to the difference file only and the main files are read-only. In merge state new pages are not allocated from difference files. Writes go to the main database files. Reads of mapped pages compare both page versions and return the version which is fresher, because we don't know if it is merged or not. Note
This merge state logic has one quirky part. Both Microsoft and Linux define the contents of file growth as undefined i.e., garbage, and both zero-initialize them. This is why we don't read mapped pages beyond the original end of the main database file and keep them current in difference file until the end of a merge. This is almost half of NBak fetch and write logic, tested by using modified PIO on existing files containing garbage.
NBackup
The functional responsibilities of NBackup are 130
Command-line Utilities 1. 2. to provide a convenient way to issue ALTER DATABASE BEGIN/END BACKUP to fix up the database after filesystem copy (physically change nbak_state_diff to nbak_state_normal in the database header) to create and restore incremental backups. Incremental backups are multi-level. That means if you do a Level 2 backup every day and a Level 3 backup every hour, each Level 3 backup contains all pages changed from the beginning of the day till the hour when the Level 3 backup is made.
3.
Backing Up Creating incremental backups has the following algorithm: 1. 2. 3. 4. 5. 6. Issue ALTER DATABASE BEGIN BACKUP to redirect writes to the difference file Look up the SCN and GUID of the most recent backup at the previous level Stream database pages having SCN larger than was found at step 2 to the backup file. Write the GUID of the previous-level backup to the header, to enable the consistency of the backup chain to be checked during restore. Issue ALTER DATABASE END BACKUP Add a record of this backup operation to RDB$BACKUP_HISTORY. Record current level, SCN, snapshot GUID and some miscellaneous stuff for user consumption.
Restoring Restore is simple: we reconstruct the physical database image for the chain of backup files, checking that the backup_guid of each file matches prev_guid of the next one, then fix it up (change its state in header to nbak_state_normal).
Usage
nbackup <options>
Valid Options
-L -N -F -B -R -U -P <database> Lock database for filesystem copy <database> Unlock previously locked database <database> Fixup database after filesystem copy <level> <database> [<filename>] Create incremental backup <database> [<file0> [<file1>...]] Restore incremental backup <user> User name <password> Password
131
Command-line Utilities
Note
1. 2. 3. <database> may specify a database alias incremental backup of multi-file databases is not supported yet "stdout" may be used as a value of <filename> for the -B option
Improvement in V.2.1.3
A. Peshkov In the Firebird 2.5 beta, an improvement was done for POSIX versions to address a problem whereby the full backup tool of nBackup would hog I/O resources when backing up large databases, bringing production work to a standstill. This improvement was backported to V.2.1.3. Now, nBackup tries to read from the operating system cache before attempting to read from disk, thus reducing the I/O load substantially. Note
The cost may be a 10 to 15 percent increase in the time taken to complete the full backup under high-load conditions.
User Manual
P. Vinkenoog A user manual for NBak/NBackup has been prepared. It can be downloaded from the documentation area at the Firebird website: www.firebirdsql.org/pdfmanual/ - the file name is Firebird-nbackup.pdf.
is a separate switch designed to make harder for the unsuspecting to overwrite a database accidentally, as could occur easily with the shortened form of the old switch:
-R[EPLACE_DATABASE]
In summary: 132
Command-line Utilities gbak -R (or gbak -r) now applies to the new -R[ECREATE_DATABASE] switch and will never overwrite an existing database if the O[VERWRITE] argument is absent The short form of the old gbak -R[EPLACE_DATABASE] is now -REP[LACE_DATABASE]. This switch does not accept the O[VERWRITE] argument. The -REP[LACE_DATABASE] switch should be considered as deprecated, i.e. it will become unavailable in some future Firebird release. This change means that, if you have any legacy batch or cron scripts that rely on gbak -r or gbak -R without modification, then the operation will except if the database exists. If you want to retain the ability of your script to overwrite your database unconditionally, you will need to modify the command to use either the new switch with the OVERWRITE argument or the new short form for the old -REPLACE_DATABASE switch.
New Switches
The following command-line switches were added: 133
Command-line Utilities
Some Features Even if isql is executing nested scripts, it will cease all execution and will return to the operating system when it detects an error. Nested scripts happen when a script A is used as isql input but in turn A contains an INPUT command to load script B an so on. Isql doesn't check for direct or indirect recursion, thus if the programmer makes a mistake and script A loads itself or loads script B that in turn loads script A again, isql will run until it exhaust memory or an error is returned from the database, at whose point -bail if activated will stop all activity. DML errors will be caught when being prepared or executed, depending on the type of error. In many cases, isql will return the line number of a DML statement that fails during execution of a script. (More about error line numbers ...) DDL errors will be caught when being prepared or executed by default, since isql uses AUTODDL ON by default. However, if AUTO DLL is OFF, the server only complains when the script does an explicit COMMIT and this may involve several SQL statements. The feature can be enabled/disabled interactively or from a script by means of the command
SET BAIL [ON | OFF]
As is the case with other SET commands, simply using SET BAIL will toggle the state between activated and deactivated. Using SET will display the state of the switch among many others. Even if BAIL is activated, it doesn't mean it will change isql behavior. An additional requirement should be met: the session should be non-interactive. A non-interactive session happens when the user calls isql in batch mode, giving it a script as input. Example
isql -b -i my_fb.sql -o results.log -m -m2
134
Command-line Utilities
Tip
However, if the user loads isql interactively and later executes a script with the input command, this is considered an interactive session even though isql knows it is executing a script.
Example
isql Use CONNECT or CREATE DATABASE to specify a database SQL> set bail; SQL> input my_fb.sql; SQL> ^Z
Whatever contents the script has, it will be executed completely, errors and all, even if the BAIL option is enabled.
Command-line Utilities The default switch for this parameter is -r. Roles provided in the command line are uppercased With -r2, the role is passed to the engine exactly as typed in the command line.
command in the isql shell. As is the case with other SET commands, simply using SET HEAD will toggle the state between activated and deactivated. 136
Command-line Utilities
Note
There is no command line option to toggle headings off.
Using SET will display the state of SET HEAD, along with other switches that can be toggled on/off in the isql shell.
Command-line Utilities With the addition of -b for bail as described in (1), the user is given the power to tell isql to stop executing scripts when an error happens, but you still need to echo the commands to the output file to discover which statement caused the failure. Now, the ability to signal the script-related line number of a failure enables the user to go to the script directly and find the offending statement. When the server provides line and column information, you will be told the exact line of DML in the script that caused the problem. When the server only indicates a failure, you will be told the starting line of the statement that caused the failure, related to the whole script. This feature works even if there are nested scripts, namely, if script SA includes script SB and SB causes a failure, the line number is related to SB. When SB is read completely, isql continues executing SA and then isql continues counting lines related to SA, since each file gets a separate line counter. A script SA includes SB when SA uses the INPUT command to load SB. Lines are counted according to what the underlying IO layer considers separate lines. For ports using EDITLINE, a line is what readline() provides in a single call. The line length limit of 32767 bytes remains unchanged.
Command-line Utilities
- normal state = online database - multi state = multi-user shutdown mode (the legacy one, unlimited attachments of SYSDBA/owner are allowed) - single state = single-user shutdown (only one attachment is allowed, used by the restore process) - full state = full/exclusive shutdown (no attachments are allowed) Note
Multi is the default state for -shut, normal is the default state for -online.
The modes can be switched sequentially: normal <-> multi <-> single <-> full Examples
gfix gfix gfix gfix -shut single -force 0 -shut full -force 0 -online single -online
139
Command-line Utilities
You cannot use -shut to bring a database one level more online and you cannot use -online to make a database more protected (an error will be thrown). These are prohibited:
gfix -shut single -force 0 gfix -shut multi -force 0 gfix -online gfix -online full gfix -shut -force 0 gfix -online single
140
Chapter 14
If you are already using functions from ib_udf and want to take advantage of null signaling (and null recognition) in some functions, you should connect to your desired database, run the script ../misc/upgrade/ib_udf_upgrade.sql that is in the Firebird directory, and commit afterwards. 141
Caution
It is recommended to do this when no other users are connected to the database.
The code in the listed functions in that script has been modified to recognize null only when NULL is signaled by the engine. Therefore, starting with FB v2, rtrim(), ltrim() and several other string functions no longer assume that an empty string means a NULL string. The functions won't crash if you don't upgrade: they will simply be unable to detect NULL. If you have never used ib_udf in your database and want to do so, you should connect to the database, run the script ../udf/ib_udf2.sql, preferably when no other users are connected, and commit afterwards. Note
Note the "2" at the end of the name. The original script for FB v1.5 is still available in the same directory.
IB_UDF_rand() vs IB_UDF_srand()
F. Schlottmann-Goedde In previous versions, the external function rand() sets the random number generator's starting point based on the current time and then generates the pseudo-random value.
srand((unsigned) time(NULL)); return ((float) rand() / (float) RAND_MAX);
The problem with this algorithm is that it will return the same value for two calls done within a second. To work around this issue, rand() was changed in Firebird 2.0 so that the starting point is not set explicitly. This ensures that different values will always be returned. In order to keep the legacy behaviour available in case somebody needs it, srand() has been introduced. It does exactly the same as the old rand() did. 142
IB_UDF_lower
The function IB_UDF_lower() in the IB_UDF library might conflict with the new internal function lower(), if you try to declare it in a database using the ib_udf.sql script from a previous Firebird version.
/* ib_udf.sql declaration that now causes conflict */ DECLARE EXTERNAL FUNCTION lower CSTRING(255) RETURNS CSTRING(255) FREE_IT ENTRY_POINT 'IB_UDF_lower' MODULE_NAME 'ib_udf';
The problem will be resolved in the latest version of the new ib_udf2.sql script, where the old UDF is declared using a quoted identifier.
/* New declaration in ib_udf2.sql */ DECLARE EXTERNAL FUNCTION "LOWER" CSTRING(255) NULL RETURNS CSTRING(255) FREE_IT ENTRY_POINT 'IB_UDF_lower' MODULE_NAME 'ib_udf';
Tip
It is preferable to use the internal function LOWER() than to call the UDF.
143
Chapter 15
trusted makes use of Windows trusted authentication which, under the right conditions, may be the most secure way to authenticate on Windows. native sets the traditional Firebird server authentication mode, requiring users to log in using a user name and password defined in the security database. mixed allows both.
RelaxedAliasChecking
V. Khorsun (V.2.1) RelaxedAliasChecking is a new configuration parameter added to permit a slight relaxation of the Firebird 2.0.x restrictions on mixing relation aliases and table names in a query. For example, with RelaxedAliasChecking set to true (=1) in firebird.conf, the following query will succeed in Firebird 2.1, whereas it would fail in v.2.0.x, or in v.2.1 with the parameter set to its default of 0:
SELECT ATABLE.FIELD1, B.FIELD2 FROM ATABLE A JOIN BTABLE B ON A.ID = BTABLE.ID
144
Caution
Understand that this is a temporary facility whose purpose is to provide some headspace for migrating systems using legacy code that exploited the tolerance of InterBase and older Firebird server versions to non-standard SQL usage. Don't enable this parameter if you have no offending code in your applications or PSQL modules. It is not intended as an invitation to write sloppy code! Regard it as a time-bomb. It will be permanently removed from a future release.
MaxFileSystemCache
V. Khorsun (V.2.1) Sets a threshold determining whether Firebird will allow the page cache to be duplicated to the filesystem cache or not. If this parameter is set to any (integer) value greater than zero, its effect depends on the current default size of the page cache: if the default page cache (in pages) is less than the value of MaxFileSystemCache (in pages) then filesystem caching is enabled, otherwise it is disabled. Note
This applies both when the page cache buffer size is set implicitly by the DefaultDBCachePages setting or explicitly as a database header attribute.
Thus, To disable filesystem caching always, set MaxFileSystemCache to zero To enable filesystem caching always, set MaxFileSystemCache an integer value that is sufficiently large to exceed the size of the database page cache. Remember that the effect of this value will be affected by subsequent changes to the page cache size. Important
The default setting for MaxFileSystemCache is 65536 pages, i.e. filesystem caching is enabled.
DatabaseGrowthIncrement
V. Khorsun (V.2.1) For better control of disk space preallocation, the new parameter DatabaseGrowthIncrement has been added to firebird.conf. It represents the upper limit for the size, in bytes, of the chunk of disk that will be requested for preallocation as pages for writes from the cache. Default: 134,217,728 bytes (128 MB). For background information, please refer to the topic Enlarge Disk Allocation Chunks in the chapter Global Improvements in Firebird 2.1. When the engine needs to initialize more disk space, it allocates a block that is 1/16th of the space already allocated, but not less than 128 KB and not greater than the DatabaseGrowthIncrement value. The DatabaseGrowthIncrement value can be raised to increase the maximum size of newly-allocated blocks to more than the default 128 MB. Set it to zero to disable preallocation. 145
Note
The lower limit of the block size is purposely hard-coded at 128 KB and cannot be reconfigured. Space is not preallocated for database shadow files. Preallocation is disabled for a database that has the No reserve option set.
ExternalFileAccess
A. Peshkov Modified in Firebird 2, to allow the first path cited in ExternalFilesAccess to be used as the default when a new external file is created.
LegacyHash
A. Peshkov This parameter enables you to configure Firebird 2 to reject an old DES hash always in an upgraded security database. If you don't use the security database upgrade procedure, this parameter does not affect Firebird operation. A DES hash cannot arrive in the new security2.fdb. Refer to the Security DB Upgrade Security section for instructions on upgrading your existing Firebird 1.5 security.fdb (or a renamed isc4.gdb) to the new security database layout. The default value is 1 (true).
Redirection
A. Peshkov Parameter for controlling redirection of remote requests. It controls the multi-hop capability that was broken in InterBase 6 and is restored in Firebird 2.
About Multi-hop
When you attach to some database using multiple hosts in the connection string, only the last host in this list is the one that opens the database. The other hosts act as intermediate gateways on port gds_db. Previously, when working, this feature was available unconditionally. Now, it can be configured. Remote redirection is turned off by default. Caution
If you are considering enabling multi-hop capability, please study the Warning text in the chapter on Security and in the documentation for this parameter in the firebird.conf file.
146
GCPolicy
V. Khorsun Garbage collection policy. It is now possible to choose the policy for garbage collection on SuperServer. The possible settings are cooperative, background and combined, as explained in the notes for GPolicy in firebird.conf. Not applicable to Classic, which supports only cooperative garbage collection.
OldColumnNaming
P. Reeves The parameter OldColumnNaming has been ported forward from Firebird 1.5.3. This parameter allows users to revert to pre-V1.5 column naming behaviour in SELECT expressions. The installation default is 0 (disabled). If it is enabled, the engine will not attempt to supply run-time identifiers, e.g. CONCATENATION for derived fields where the developer has neglected to provide identifiers. Important
This setting affects all databases on the server and will potentially produce exceptions or unpredicted results where mixed applications are implemented.
UsePriorityScheduler
A. Peshkov Setting this parameter to zero now disables switching of thread priorities completely. It affects only the Win32 SuperServer.
Renamed Parameters
SortMemBlockSize Changed to TempCacheBlockSize
D. Yemanov Considered more appropriate terminology.
148
Chapter 16
Russian Federation/Canada France Czech Republic France France Canada Greece U.S.A. U.S.A. Germany U.K. Russian Federation Spain
Paul Beach Pavel Cisar Philippe Makowski Paul Reeves Sean Leyne Dimitrios Ioannides Ann Harrison Jim Starkey Roman Rokytskyy Ryan Baldwin Evgeny Putilin Carlos Guzman Alvarez
149
Developer
Country
Major Tasks Developer and coordinator of .NET providers for Firebird until 2007
Jiri Cincura Alexander Potapchenko David Rushby (d.) Konstantin Kuznetsov Paul Vinkenoog Norman Dunbar Pavel Menshchikov Tomneko Hayashi Umberto (Mimmo) Masotti Olivier Mascia Oleg Loa Grzegorz Prokopski Erik Kunze Helen Borrie
Czech Republic Russia U.S.A. Russian Federation The Netherlands U.K. Russian Federation Japan Italy Belgium Russian Federation Hungary Germany Australia
Developer and coordinator of .NET providers from January 2008 Coordinator of ODBC/JDBC driver for Firebird Developer and coordinator of KInterbase Python interface for Firebird until his accidental death in July, 2007 Solaris Intel builds Coordinator, Firebird documentation project; documentation writer and tools developer/implementor Documentation writer Documentation translator Documentation translator Documentation translator IBPP C++ interface developer; re-implementor of Win32 installation services Contributor Debian builds SINIX-Z port; raw device enablement Release notes editor; Chief of Thought Police
150
ACOS
ACOS( <number> )
Returns the arc cosine of a number. Argument to ACOS must be in the range -1 to 1. Returns a value in the range 0 to PI.
ASCII_CHAR
ASCII_CHAR( <number> )
Returns the ASCII character with the specified code. The argument to ASCII_CHAR must be in the range 0 to 255. The result is returned in character set NONE.
ASCII_VAL
ASCII_VAL( <string> )
Returns the ASCII code of the first character of the specified string. 1. 2. Returns 0 if the string is empty Throws an error if the first character is multi-byte
ASIN
ASIN( <number> )
Returns the arc sine of a number. The argument to ASIN must be in the range -1 to 1. It returns a result in the range -PI/2 to PI/2.
ATAN
ATAN( <number> )
Returns the arc tangent of a number. Returns a value in the range -PI/2 to PI/2.
ATAN2
Returns the arc tangent of the first number / the second number. Returns a value in the range -PI to PI.
151
Function
Format
Description
BIN_AND
BIN_OR
BIN_SHL
Returns the result of a binary shift left operation performed on the arguments (first << second).
BIN_SHR
Returns the result of a binary shift right operation performed on the arguments (first >> second).
BIN_XOR
BIT_LENGTH
CEIL | CEILING
{ CEIL | CEILING }( <number> ) Returns a value representing the smallest integer that is greater than or equal to the input argument.
-- returns 3, -2
152
Function
Format
COS
COS( <number> )
Returns the cosine of a number. The angle is specified in radians and returns a value in the range -1 to 1.
COSH
COSH( <number> )
COT
COT( <number> )
Returns 1 / tan(argument).
DATEADD
See below
Returns a date/time/timestamp value increased (or decreased, when negative) by the specified amount of time. Format:
DATEADD( <number> <timestamp_part> TO <date_time> ) DATEADD( <timestamp_part>, <number>, <date_time> ) timestamp_part ::= { YEAR | MONTH | DAY | HOUR | MINUTE | SECOND | MILLISECOND }
1. YEAR, MONTH and DAY cannot be used with time values. 2. HOUR, MINUTE, SECOND and MILLISECOND cannot be used with date values. 3. All timestamp_part values can be used with timestamp values. Example
select dateadd(day, -1, current_date) as yesterday from rdb$database; /* or (expanded syntax) */
153
Function
Format
Description
DATEDIFF
See below
Returns an exact numeric value representing the interval of time from the first date/time/timestamp value to the second one. Format:
DATEDIFF( <timestamp_part> FROM <date_time> TO <date_time> ) DATEDIFF( <timestamp_part>, <date_time>, <date_time> ) timestamp_part ::= { YEAR | MONTH | DAY | HOUR | MINUTE | SECOND | MILLISECOND }
1. Returns a positive value if the second value is greater than the first one, negative when the first one is greater, or zero when they are equal. 2. Comparison of date with time values is invalid. 3. YEAR, MONTH, and DAY cannot be used with time values. 4. HOUR, MINUTE, SECOND and MILLISECOND cannot be used with date values. 5. All timestamp_part values can be used with timestamp values. Example
select datediff( DAY, (cast('TOMORROW' as date) -10), current_date) as datediffresult from rdb$database;
DECODE
See below
DECODE is a shortcut for a CASE ... WHEN ... ELSE expression. Format:
Example
select decode(state, 0, 'deleted', 1, 'active', 'unknown') from things;
EXP
EXP( <number> )
154
Function FLOOR
Description Returns a value representing the largest integer that is less than or equal to the input argument.
GEN_UUID
GEN_UUID() -- no arguments
HASH
HASH( <string> )
LEFT
Returns the substring of a specified length that appears at the start of a left-to-right string.
select left(name, char_length(name) - 10) from people where name like '% FERNANDES';
1. The first position in a string is 1, not 0. 2. If the <number> argument evaluates to a non-integer, banker's rounding is applied. LN LN( <number> ) Returns the natural logarithm of a number.
LOG
LOG10
LOG10( <number> )
LOWER
LOWER( <string> )
155
Function
Format
Description
SQL> create table t (c char(1) character set dos850); SQL> insert into t values ('A'); SQL> insert into t values ('E'); SQL> insert into t values ('');; SQL> insert into t values (''); SQL> select c, lower(c) from t; C LOWER ====== ====== A a E e
LPAD
LPAD(string1, length, string2) prepends string2 to the beginning of string1 until the length of the result string becomes equal to length.
1. If the second string is omitted the default value is one space. 2. If the result string would exceed the length, the second string is truncated. Example
select lpad(x, 10) from y;
MAXVALUE
MINVALUE
MOD
OCTET_LENGTH
156
Function OVERLAY
Description Returns string1 replacing the substring FROM start FOR length by string2. Format:
1. The first position in a string is 1, not 0. 2. If the <start> and/or <length > argument evaluates to a non-integer, banker's rounding is applied.
PI() -- no arguments
POSITION
See below
Returns the start position of the first string inside the second string, relative to the beginning of the outer string. In the second form, an offset position may be supplied so that the function will ignore any matches occuring before the offset position and return the first match following that.
select rdb$relation_name from rdb$relations where position('RDB$' IN rdb$relation_name) = 1; /* */ position ('be', 'To be or not to be', 10)
returns 17. The first occurrence of 'be' occurs within the offset and is ignored. POWER POWER( <number>, <number> ) POWER(X, Y) returns X to the power of Y.
157
Function
Format
Description
RAND
RAND() -- no argument
REPLACE
REVERSE
REVERSE( <value> )
Returns a string in reverse order. Useful function for creating an expression index that indexes strings from right to left.
create index people_email on people computed by (reverse(email)); select * from people where reverse(email) starting with reverse('.br');
RIGHT
Returns the substring, of the specified length, from the right-hand end of a string.
ROUND
If the scale (second parameter) is negative or is omitted, the integer part of the value is rounded. E.g., ROUND(123.456, -1) returns 120.000. RPAD RPAD( <string1>, <length> [, <string2> ] ) Appends <string2> to the end of <string1> until the length of the result string becomes equal to <length>. Example
select rpad(x, 10) from y;
158
Function
Format
Description
1. If the second string is omitted the default value is one space. 2. If the result string would exceed the length, the final application of <string2> will be truncated. SIGN SIGN( <number> ) Returns 1, 0, or -1 depending on whether the input value is positive, zero or negative, respectively.
SIN
SIN( <number> )
SINH
SINH( <number> )
SQRT
SQRT( <number> )
TAN
TAN( <number> )
TANH
TANH( <number> )
TRIM
See below
(V.2.0.x) Trims characters (default: blanks) from the left and/or right of a string.
TRIM <left paren> [ [ <trim specification> ] [ <trim character> ] FROM ] <value expression> <right paren> <trim specification> ::= LEADING | TRAILING | BOTH
159
Function 2. 3. 4.
Format
Description
If <trim character> is not specified, ' ' is assumed. If <trim specification> and/or <trim character> is specified, FROM should be specified. If <trim specification> and <trim character> is not specified, FROM should not be specified. Example A)
select rdb$relation_name, trim(leading 'RDB$' from rdb$relation_name) from rdb$relations where rdb$relation_name starting with 'RDB$';
Example B)
select trim(rdb$relation_name) || ' is a system table' from rdb$relations where rdb$system_flag = 1;
TRUNC
1) select trunc(x) from y; 2) select trunc(-2.8), trunc(2.8) from rdb$database; -- returns -2, 2 3) select trunc(987.65, 1), trunc(987.65, -1) from rdb$database; -- returns 987.60, 980.00
160
"
PT_BR
Russian language character set and dictio- O. Loa, A. nary collation. Karyakin Ukrainian language character set and dictionary collation. Bosnian language collation for WIN1250 character set. Czech language accent-insensitive collation for WIN1250 character set Czech language case- and accent-insensitive collation for WIN1250 character set Brazil Portuguese collation for WIN1252 character set. Latvian dictionary collation. Lithuanian dictionary collation. Estonian dictionary collation. Vietnamese language subset of charset WIN1258. O. Loa, A. Karyakin F. Hasovic I. Prenosil, A. dos Santos Fernandes I. Prenosil, A. dos Santos Fernandes A. dos Santos Fernandes, P. H. Albanez O. Loa, A. Karyakin O. Loa, A. Karyakin O. Loa, A. Karyakin Nguyen The Phuong, A. dos Santos Fernandes
UTF8
UCS_BASIC
Unicode 4.0 support with UTF8 character A. dos Santos Ferset and UCS_BASIC collation. nandes
161
Description
Implemented By
Unicode 4.0 support with UTF8 character A. dos Santos Ferset and UNICODE collation. nandes Unicode 4.0 support with UTF8 character A. dos Santos Ferset and case-insensitive collation. nandes (V.2.1) French language case-insensitive and accent-insensitive collation. A. dos Santos Fernandes A. dos Santos Fernandes (Not known)
CP943C_UNICODE (V.2.1) Japanese character set. TIS620_UNICODE (V.2.1) Thai character set, single byte.
162
163
164
165
166
167
168
-- 4. create new objects in database CREATE DOMAIN RDB$COMMENT AS BLOB SUB_TYPE TEXT SEGMENT SIZE 80 CHARACTER SET UNICODE_FSS; CREATE DOMAIN RDB$NAME_PART AS VARCHAR(32) CHARACTER SET UNICODE_FSS DEFAULT _UNICODE_FSS ''; CREATE DOMAIN RDB$GID AS INTEGER; CREATE DOMAIN RDB$PASSWD AS VARCHAR(64) CHARACTER SET BINARY; CREATE DOMAIN RDB$UID AS INTEGER; CREATE DOMAIN RDB$USER_NAME AS VARCHAR(128) CHARACTER SET UNICODE_FSS; CREATE DOMAIN RDB$USER_PRIVILEGE AS INTEGER; COMMIT;
CREATE TABLE RDB$USERS ( RDB$USER_NAME RDB$USER_NAME NOT NULL PRIMARY KEY, /* local system user name for setuid for file permissions */ RDB$SYS_USER_NAME RDB$USER_NAME, RDB$GROUP_NAME RDB$USER_NAME, RDB$UID RDB$UID, RDB$GID RDB$GID, RDB$PASSWD RDB$PASSWD, /* SEE NOTE BELOW */ /* Privilege level of user mark a user as having DBA privilege */ RDB$PRIVILEGE RDB$USER_PRIVILEGE, RDB$COMMENT RDB$FIRST_NAME RDB$MIDDLE_NAME RDB$LAST_NAME COMMIT; RDB$COMMENT, RDB$NAME_PART, RDB$NAME_PART, RDB$NAME_PART);
CREATE VIEW USERS (USER_NAME, SYS_USER_NAME, GROUP_NAME, UID, GID, PASSWD, PRIVILEGE, COMMENT, FIRST_NAME, MIDDLE_NAME, LAST_NAME, FULL_NAME) AS SELECT RDB$USER_NAME, RDB$SYS_USER_NAME, RDB$GROUP_NAME, RDB$UID, RDB$GID, RDB$PASSWD, RDB$PRIVILEGE, RDB$COMMENT,
169
Note
This field should be constrained as NOT NULL. For information about this, see Nullability of RDB$PASSWD in the Security chapter.
170