728x90

안녕하세요. Informix에는 연도별 주차를 계산하는 기능이 없어서 찾아보다가 다른 코드를 보고 따라서 만들어 보았습니다. 주차에 대한 개념이 없다보니 커뮤니티와 블로그, 위키 자료들을 참고했는데요. 일반적으로 쓰이는 형태가 ISO 8601 표준이라고 합니다.

ISO 8601에 따르면 1주차에 대한 정의는 아래와 같습니다.

  • 시작 연도의 첫 번째 목요일이 포함된 주
  • 1월 4일이 있는 주
  • 시작 연도에 일의 대부분(4일 이상)이 있는 첫 번째 주
  • 12월 29일 - 1월 4일 기간의 월요일로 시작하는 주

아래와 같이 다양한 DBMS에서 함수를 사용하여 특정일자에 대한 주차를 구할 수 있습니다만.. Informix는 자체 기능이 제공되지 않아서 아쉽군요.

DBMS 제공함수 사용예시
Oracle TO_CHAR TO_CHAR(DATE '2021-08-25' , 'IW')
Db2 TO_CHAR TO_CHAR(DATE '2021-08-25' , 'IW')
MySQL WEEK WEEK('2021-08-25', 3);
MariaDB WEEK WEEK('2021-08-25', 3);
SQL Server DATEPART DATEPART(ISOWK,'2021-08-25')
PostgreSQL DATE_PART / EXTRACT DATE_PART('WEEK', '2021-08-25'::DATE)
EXTRACT('WEEK' FROM '2021-08-25'::DATE)
Sybase DATEPART DATEPART(CWK, '8/25/2021')

Informix에는 기본 내장된 함수가 없기 때문에 계산 방식에 대해서 조사를 했습니다.

위에서 상술된 조건을 만족해야하고, Informix에서 datetime 을 일자로 변환하여 계산하는 등의 몇가지 시행착오가 있었습니다.

create function weeknum ( dt varchar(10) )
returning int;
define wknum int;
select trunc(((to_date(dt, '%Y-%m-%d') - yearstart)::interval day(3) to day::varchar(12)::integer) / 7) + 1
into wknum
from
(
select case when nextyr <= to_date(dt, '%Y-%m-%d') then nextyr
            when curryr <= to_date(dt, '%Y-%m-%d') then curryr
            else prioryr 
       end yearstart
from 
(
select  
        mdy(1,1,1753) + trunc(((jan4 - 1 units year - mdy(1,1,1900) + 53690 units day)::varchar(12)::integer) / 7) * 7  units day prioryr,
        mdy(1,1,1753) + trunc(((jan4                - mdy(1,1,1900) + 53690 units day)::varchar(12)::integer) / 7) * 7  units day curryr,
        mdy(1,1,1753) + trunc(((jan4 + 1 units year - mdy(1,1,1900) + 53690 units day)::varchar(12)::integer) / 7) * 7  units day nextyr
from (
select mdy(1,1,1900) + (extend (to_date(dt, '%Y-%m-%d'), year to year) - mdy (1,1,1900))::varchar(12)::integer units year + 3 units day jan4 from dual
)
)
);
return wknum;
end function;

 

아래와 같은 방식으로 Informix에서 특정 일자에 대한 주차를 구할 수 있습니다. 위 함수를 수정하면 쿼리형태로도 사용 가능할 것 같습니다.

> select weeknum ('2021-08-25') from sysmaster:sysdual;
(expression)
          34

 

https://en.wikipedia.org/wiki/ISO_8601

https://en.wikipedia.org/wiki/ISO_week_date

https://www.toolbox.com/tech/oracle/question/how-the-week-number-is-being-derived-121815/

https://www.sqlteam.com/forums/topic.asp?TOPIC_ID=60515 

http://www.whitemiceconsulting.com/informixintervaltips201609

https://www.sqlservercentral.com/articles/a-simple-formula-to-calculate-the-iso-week-number

https://4js.com/online_documentation/fjs-fgl-3.00.05-manual-html/c_fgl_odiagmsv_005.html

 

728x90
728x90

14.10.xC6 버전부터 Round robin 방식으로 분할된 테이블의 개선된 기능을 소개드립니다.

Round robin 분할 방식로 구성된 테이블은 데이터가 지정된 DBspace를 순환하며 입력됩니다.

-- Round robin 분할 테이블에 데이터 입력
> create table test (a int) fragment by round robin in dbs1,dbs2;
Table created.
> insert into test select level from sysmaster:sysdual connect by level <= 5000;
5000 row(s) inserted.
-- 분할된 파티션 별 데이터 건수 확인
$ oncheck -pt demo:test | egrep 'partition|rows'
                  Table fragment partition dbs1 in DBspace dbs1
    Number of rows                 2500
                  Table fragment partition dbs1 in DBspace dbs2  
    Number of rows                 2500

위와 같은 상태에서 새로운 DBspace를 round robin 스키마에 추가하면, 기존 데이터는 이동하지 않고 새로 입력되는 데이터는 기존처럼 DBspace를 순환하며 입력됩니다.

-- Round robin 분할 테이블에 새로운 DBspace 추가
> alter fragment on table test add  dbs3;
Alter fragment completed.
> insert into test select level from sysmaster:sysdual connect by level <= 3;
3 row(s) inserted.
-- 분할된 파티션 별 데이터 건수 확인
$ oncheck -pt demo:test | egrep 'partition|rows'
                  Table fragment partition dbs1 in DBspace dbs1
    Number of rows                 2501
                  Table fragment partition dbs2 in DBspace dbs2
    Number of rows                 2501
                  Table fragment partition dbs3 in DBspace dbs3
    Number of rows                 1

14.10.xC6 버전부터는 Round robin 방식으로 구성된 테이블에 데이터가 입력될 경우, 가장 데이터 건수가 적은 파티션에 우선적으로 입력됩니다.

-- Round robin 분할 테이블에 데이터 입력
> create table test (a int) fragment by round robin in datadbs1,datadbs2;
Table created.
> insert into test select level from sysmaster:sysdual connect by level <= 5000;
5000 row(s) inserted.
-- Round robin 분할 테이블에 새로운 DBspace 추가
> alter fragment on table test add datadbs3;
Alter fragment completed.
> insert into test select level from sysmaster:sysdual connect by level <= 3;
3 row(s) inserted.
-- 분할된 파티션 별 데이터 건수 확인
$ oncheck -pt demo:test | egrep 'partition|rows'
                  Table fragment partition datadbs1 in DBspace datadbs1
    Number of rows                 2500
                  Table fragment partition datadbs2 in DBspace datadbs2
    Number of rows                 2500
                  Table fragment partition datadbs3 in DBspace datadbs3
    Number of rows                 3

 

파티션 별로 데이터량을 균등하게 유지하는 측면에서 좋은 기능인 것 같습니다. UPDATE 문장으로는 데이터가 이동하지 않더군요. 참고하시길 바랍니다.

 

728x90
728x90

최근에 공개된 Informix 14.10.xC6 버전에서 QUERY TIMEOUT 기능이 추가되었습니다.

아직 IBM Documentation에 설명된 내용이 없어서 며칠전에 있었던 Webinar의 내용을 참고해서 정리해보겠습니다.

 

QUERY TIMEOUT은 쿼리가 실행되는 시간을 제한하는 기능으로, OS 또는 DB 세션 환경 변수로 설정할 수 있습니다. onstat 명령에서 -g ses 과 -g sql 옵션을 사용하면 QUERY TIMEOUT 설정 값과 수행시간이 추가로 표시됩니다.

 

아래는 onstat -g sql의 출력결과입니다. Current SQL Statement 부분에만 표시됩니다. 기존에 보이는 내용에 추가로 QUERY_TIMEOUT setting과 Clock time elapsed 에 대한 정보가 표시되네요. QUERY_TIMEOUT 설정여부와 관계없이 항상 보입니다.

IBM Informix Dynamic Server Version 14.10.FC6 -- On-Line -- Up 3 days 22:36:44 -- 2664076 Kbytes
2021-06-26 09:00:13
Sess       SQL            Current            Iso Lock       SQL  ISAM F.E.
Id         Stmt type      Database           Lvl Mode       ERR  ERR  Vers  Explain
98         SELECT         stores_demo        CR  Not Wait   0    0    9.24  Off 
Current statement name : slctcur
Current SQL statement (3) :
  select * from systables, syscolumns, sysindexes
  QUERY_TIMEOUT setting: 00:00:20
  Clock time elapsed   : 00:00:15

위 내용은 QUERY_TIMEOUT을 20초로 설정한 예시인데, 쿼리 실행시간이 20초를 초과하면 아래와 같이 해당 문장이 중단됩니다. Ctrl + C 키를 누른 것과 동일한 효과입니다. 내부적으로 중단 처리 과정에서 설정된 값(20초)을 초과할 수 있다고 하네요.

...
levels           2
leaves           5.000000000000
nunique          113.0000000000
clust            10.00000000000
  213: Statement timed out or interrupted by user.
  157: ISAM error: Interrupted ISAM call
Error in line 1
Near character position 46

QUERY_TIMEOUT 설정은 아래와 같이 DML(update/insert/delete) 문장에는 적용되지 않네요.

설정된 시간을 초과해도 계속 수행됨을 알 수 있습니다.

IBM Informix Dynamic Server Version 14.10.FC6 -- On-Line -- Up 4 days 10:36:43 -- 2664076 Kbytes
2021-06-26 21:00:12
Sess       SQL            Current            Iso Lock       SQL  ISAM F.E.
Id         Stmt type      Database           Lvl Mode       ERR  ERR  Vers  Explain
106        SELECT INTO    sysmaster          CR  Not Wait   0    0    9.24  Off 
Current SQL statement (3) :
  select * from systabinfo, sysvplst, sysrawdsk into temp ttt
  QUERY_TIMEOUT setting: 00:00:20
  Clock time elapsed   : 00:02:25

 

공식적인 문서가 곧 나오겠지만, 현재까지 제가 확인한 바로는 QUERY_TIMEOUT 설정은 SELECT 문장에만 적용되는 것 같습니다. 잘못된 내용이나 추가로 확인한 부분에 대해서는 업데이트 하겠습니다.

 

728x90
728x90

안녕하세요. 오늘은 인포믹스의 AUTOLOCATE 기능에 대해 정리해보겠습니다.

인포믹스 12.10.xC3 버전부터 AUTOLOCATE라는 기능을 제공합니다. 이 기능은 테이블이나 인덱스의 배치 및 분할(fragmentation)을 자동화할 수 있습니다.

 

분할방식은 라운드 로빈(round-robin)으로 이뤄지고 AUTOLOCATE에 지정한 값의 수만큼 분할(fragment)이 생성됩니다.

인덱스의 경우는 라운드 로빈 방식으로 구성될 수 없으므로 적절한 페이지 크기의 단일 dbspace에 배치됩니다.

 

 

AUTOLOCATE 기능으로 테이블이나 인덱스가 배치될때 기본적으로는 모든 dbspace를 사용하는데, 사용자가 저장될 dbspace를 지정할 수도 있습니다. sysadmin 데이터베이스의 프로시저를 사용하여 autolocate database 옵션을 사용하면 됩니다. 지정한 dbspace 목록은 sysautolocate 카탈로그 테이블에서 확인할 수 있습니다.

 

사족으로 sysautolocate는 sysmaster 데이터베이스가 아닌 지정한 데이터베이스 별로 확인해야합니다. 저도 오늘에야 알게된 사실인데 IBM Community의 Benjamin Thompson의 답변으로 확인을 했습니다.

$ onmode -wf AUTOLOCATE=3
Value for AUTOLOCATE (3) was saved in config file.
Value of AUTOLOCATE has been changed to 3.
$ export DB_LOCALE=ko_kr.ksc
$ export CLIENT_LOCALE=ko_kr.ksc
$ dbaccess sysadmin -
Database selected.
> EXECUTE FUNCTION task("create database","demo","datadbs1","ko_kr.ksc");
(expression) Database demo created
1 row(s) retrieved.
> EXECUTE FUNCTION task("autolocate database", "demo", "datadbs1,datadbs2");
(expression) OK
$ echo "select dbsnum,dbsname[1,10],pagesize,flags from sysautolocate" | dbaccess demo
Database selected.
     dbsnum dbsname    pagesize       flags
          5 datadbs2       2048           1
          0 *                 0           2
          4 datadbs1       2048           1

위와 같이 설정한 상태에서 특정 테이블을 생성해보면 아래와 같이 datadbs1, datadbs2 두개의 dbspace에 자동으로 분할되어 생성된 것을 확인할 수 있습니다.

$ dbaccess demo -
Database selected.
> create table test (a int);
Table created.
$ dbschema -d demo -t test -ss
DBSCHEMA Schema Utility       INFORMIX-SQL Version 14.10.FC5
{ TABLE "informix".test row size = 4 number of columns = 1 index size = 0 }
create table "informix".test
  (
    a integer
  )
  fragment by round robin partition datadbs1_1 in datadbs1, partition datadbs2_2
    in datadbs2, partition datadbs1_3 in datadbs1
  extent size 8 next size 16 lock mode row;

최근에는 이런 기능들을 활용해서 일반 테이블은 AUTOLOCATE 설정을 따르게 하고, 대용량 테이블의 경우는 INTERVAL에 의한 분할 방식으로 구성하려고 하는 편입니다.

 

 

https://www.ibm.com/docs/en/informix-servers/14.10?topic=parameters-autolocate-configuration-parameter

 

728x90
728x90

Troubleshooting is a systematic approach to solving a problem. The goal of troubleshooting is to determine why something does not work as expected and how to resolve the problem. Certain common techniques can help with the task of troubleshooting.

The first step in the troubleshooting process is to describe the problem completely. Problem descriptions help you and the IBM® technical-support representative know where to start to find the cause of the problem. This step includes asking yourself basic questions:

  • What are the symptoms of the problem?
  • Where does the problem occur?
  • When does the problem occur?
  • Under which conditions does the problem occur?
  • Can the problem be reproduced?

The answers to these questions typically lead to a good description of the problem, which can then lead you to a problem resolution.

What are the symptoms of the problem?

When starting to describe a problem, the most obvious question is "What is the problem?" This question might seem straightforward; however, you can break it down into several more-focused questions that create a more descriptive picture of the problem. These questions can include:

  • Who, or what, is reporting the problem?
  • What are the error codes and messages?
  • How does the system fail? For example, is it a loop, hang, crash, performance degradation, or incorrect result?

Where does the problem occur?

Determining where the problem originates is not always easy, but it is one of the most important steps in resolving a problem. Many layers of technology can exist between the reporting and failing components. Networks, disks, and drivers are only a few of the components to consider when you are investigating problems.

The following questions help you to focus on where the problem occurs to isolate the problem layer:

  • Is the problem specific to one platform or operating system, or is it common across multiple platforms or operating systems?
  • Is the current environment and configuration supported?
  • Do all users have the problem?
  • (For multi-site installations.) Do all sites have the problem?

If one layer reports the problem, the problem does not necessarily originate in that layer. Part of identifying where a problem originates is understanding the environment in which it exists. Take some time to completely describe the problem environment, including the operating system and version, all corresponding software and versions, and hardware information. Confirm that you are running within an environment that is a supported configuration; many problems can be traced back to incompatible levels of software that are not intended to run together or have not been fully tested together.

When does the problem occur?

Develop a detailed timeline of events leading up to a failure, especially for those cases that are one-time occurrences. You can most easily develop a timeline by working backward: Start at the time an error was reported (as precisely as possible, even down to the millisecond), and work backward through the available logs and information. Typically, you need to look only as far as the first suspicious event that you find in a diagnostic log.

To develop a detailed timeline of events, answer these questions:

  • Does the problem happen only at a certain time of day or night?
  • How often does the problem happen?
  • What sequence of events leads up to the time that the problem is reported?
  • Does the problem happen after an environment change, such as upgrading or installing software or hardware?

Responding to these types of questions can give you a frame of reference in which to investigate the problem.

Under which conditions does the problem occur?

Knowing which systems and applications are running at the time that a problem occurs is an important part of troubleshooting. These questions about your environment can help you to identify the root cause of the problem:

  • Does the problem always occur when the same task is being performed?
  • Does a certain sequence of events need to happen for the problem to occur?
  • Do any other applications fail at the same time?

Answering these types of questions can help you explain the environment in which the problem occurs and correlate any dependencies. Remember that just because multiple problems might have occurred around the same time, the problems are not necessarily related.

Can the problem be reproduced?

From a troubleshooting standpoint, the ideal problem is one that can be reproduced. Typically, when a problem can be reproduced you have a larger set of tools or procedures at your disposal to help you investigate. Consequently, problems that you can reproduce are often easier to debug and solve.

However, problems that you can reproduce can have a disadvantage: If the problem is of significant business impact, you do not want it to recur. If possible, re-create the problem in a test or development environment, which typically offers you more flexibility and control during your investigation.

  • Can the problem be re-created on a test system?
  • Are multiple users or applications encountering the same type of problem?
  • Can the problem be re-created by running a single command, a set of commands, or a particular application?

출처 : https://www.ibm.com/docs/en/informix-servers/12.10?topic=support-techniques-troubleshooting-problems

728x90
728x90

You can perform routine administrative tasks that can prevent assertion failures or help prepare for recovering from assertion failures.

To prevent assertion failures on Informix®, perform the following tasks regularly:

Table 1. Preventing assertion failuresPrevention taskPurpose

Test your applications thoroughly in a realistic environment before releasing your applications into production. Applications can trigger assertion failures.Make sure that you have allocated enough resources: for example, physical and logical logs and shared memory.
Check and repair the consistency of your data.Run the following oncheck commands to check your system:
  • oncheck -cD: Data pages
  • oncheck -cI: Index pages
  • oncheck -cr: Reserved pages
  • oncheck -ce: Chunk-free list
  • oncheck -cc: System catalog tables
  • oncheck -pe: Physical information about chunks
Diagnosing and repairing consistency problems quickly can prevent major problems like data loss and assertion failures.
Upgrade to the latest major and fix pack release. Assertion failures can be caused by product defects. You can avoid many product defects by upgrading to the most current release.
Update statistics.When you change a table or indexing schema, update statistics to update the dictionary cache. By default, statistics are updated automatically by the Scheduler. You can customize automatic statistics updating for your system. Queries that use stale statistics can use too many resources and cause assertion failures. Stale statistics can also have a negative affect on query performance.Always update statistics after upgrading.

To prepare for assertion failures on Informix, perform the following tasks regularly:

Table 2. Preparing for assertion failuresPreparation taskPurpose

Back up your data and logical logs.You can use the ON-Bar utility or the ontape utility to back up your data and logical logs. The ON-Bar utility requires a storage manager. If data loss occurs, you can recover your data and recent transactions.
Back up your database and storage space schema information.Run the following commands to back up your schema information:
  • dbschema -ss -d database_name > dbschema_ss_database_name.out: Saves the schema information about the specified database in a file.
  • dbschema -c > dbschema_c.out: Saves the commands to reproduce storage spaces, chunks, physical logs, and logical logs in a file.
In a catastrophic failure, you can recreate your system.

 

출처 : https://www.ibm.com/docs/en/informix-servers/14.10?topic=failures-prevent-prepare-assertion

728x90
728x90

얼마전에 고객사 인포믹스에서 243 오류(Could not position within a table table-name)가 발생해서 onmode -I 명령으로 동일한 오류가 발생했을 때 진단 정보를 수집하도록 설정해두었습니다. 

 

그런데 진단 정보를 수집하는 설정 상태를 확인하는 방법이 있는지 알고싶어 IBM Community에 질문 글을 썼습니다.

onmode -I 명령을 수행하면 아래와 같이 인포믹스 온라인 로그에 메시지가 표시되기는 하지만 현재 설정되었는지 여부를 확인하는 방법을 알고 싶었습니다.

11:55:15  Verbose error trapping set, errno = 243, session_id = -1

 

질문 글을 올리고 금방 답변을 받았는데.. onstat 명령에 숨겨진 옵션이 있더군요.

$ onmode -I 243
$ onstat -g ras
IBM Informix Dynamic Server Version 11.70.FC9 -- On-Line -- Up 01:07:23 -- 23486904 Kbytes
 Diagnostics           Current Settings
 AFCRASH               0x00002481
 AFFAIL                0x00000401
 AFWARN                0x00000401
 AFDEBUG               0
 AFLINES               0
 BLOCKTIMEOUT          3600
 Block Status          Unblocked
 CCFLAGS               0x00000000
 CCFLAGS2              0x00000200
 DUMPCORE              0
 DUMPGCORE             0
 DUMPSHMEM             1
 DUMPCNT               1
 DUMPDIR               /work1/informix/ids1150fc6/tmp
 RHEAD_T               0x00000000541c3800
 SYSALARMPROGRAM       /work1/informix/ids1150fc6/etc/evidence.sh
 LTXHWM                70%
 LTXEHWM               80%
 DYNAMIC_LOGS          2
Traperror info:
 Errno          Session(s)
 243            All

onstat -g ras 명령의 출력 결과입니다. -g ras 옵션은 onstat 도움말과 IBM의 매뉴얼에 설명되지 않은 숨겨진 옵션입니다. 결과의 Traperror info 부분에서 현재 에러번호(Errno)와 특정 세션번호에 대해 진단 정보를 수집하도록 설정되어 있음을 확인할 수 있습니다.

728x90
728x90

안녕하세요. CURSOR Service Distribution의 2021년 1분기 뉴스레터에서 꽤 유용한 정보를 발견해서 정리해보려고 합니다. 참고로 CURSOR Service Distribution은 독일에서 Informix와 Db2에 대한 서비스를 제공하는 회사입니다.

 

인포믹스에서 테이블을 정의할 때 Smart Blob (데이터 유형 BLOB 또는 CLOB) 컬럼에 대해 스토리지 공간 (SBSpace)을 지정할 수 있습니다. 저장 위치를 ​​지정하지 않으면 $ONCONFIG의 SBSPACE 및 SYSSBSPACE에 설정한 값이 사용되죠.  여러개의 SBSpace를 저장 위치로 지정하면 row별로 SBSpace에 분산되는데, 정확한 저장 위치를 SQL 쿼리로 확인할 수 있다고 합니다.

 

SBSpace 위치를 확인하는 SQL 쿼리를 사용할 때는 Little Endian (Linux, Windows)과 Big Endian (AIX, SPARC Solaris..) 시스템을 구분해서 작성해야 한다네요.

 

Big Endian 시스템에서 SBSpace 번호를 확인하는 방법은 비교적 간단합니다.

("0x" || substr(<sblob_column>::lvarchar,17,8))::INT

Little Endian의 경우 좀 복잡해집니다.

("0x"|| substr(<sblob_column>::lvarchar,23,2)
     || substr(<sblob_column>::lvarchar,21,2)
     || substr(<sblob_column>::lvarchar,19,2)
     || substr(<sblob_column>::lvarchar,17,2))::INT

아래는 리눅스 환경에서의 테스트를 위한 SQL문장입니다. AIX같은 Big Endian에서는 쿼리 내용을 수정해야겠죠.

-- 테이블 생성
create table blob_test (
objekt_nr int,
doc blob
) put doc in (sbdbs,sbdbs2)
;
-- 샘플 데이터 입력
insert into blob_test values (42, filetoblob("/etc/passwd","server"));
insert into blob_test values (43, filetoblob("/etc/hosts","server"));
insert into blob_test values (44, filetoblob("/etc/services","server"));
-- 각 row별 BLOB 데이터가 저장된 SBSpace 확인
select objekt_nr , 
       ("0x"||substr(doc::lvarchar,23,2)
            ||substr(doc::lvarchar,21,2)
            ||substr(doc::lvarchar,19,2)
            ||substr(doc::lvarchar,17,2))::INT as space_nr,
       (select name::char(40)
          from sysmaster:sysdbspaces 
         where dbsnum = ("0x"||substr(doc::lvarchar,23,2)
                             ||substr(doc::lvarchar,21,2)
                             ||substr(doc::lvarchar,19,2)
                             ||substr(doc::lvarchar,17,2))::INT) as spacename
  from blob_test
 where doc is not null;

 

아래는 제가 AIX에서 테스트 해본 결과입니다.

> dbaccess stores_demo -
select objekt_nr , 
       ("0x" || substr(doc::lvarchar,17,8))::INT as space_nr,
       (select name::char(40)
       from sysmaster:sysdbspaces 
       where dbsnum = ("0x" || substr(doc::lvarchar,17,8))::INT) as spacename
  from blob_test
 where doc is not null;
   objekt_nr    space_nr spacename
         42          11 sbspace1
         43          15 sbspace2
         44          11 sbspace1
3 row(s) retrieved.

 

이 쿼리는 공식적으로 문서화되지 않았기 때문에 향후에 변경될 가능성이 있다고 합니다.

제가 테스트한 버전은 12.1과 14.1입니다. SQL 사용전에 맞는 정보가 표시되는지 테스트는 해보시기 바랍니다.

 

 

www.cursor-distribution.de/de/ibm-software/informix-fuer-administratoren/informix-newsletter-ibm/send/434-informix-newsletter/6364-informix-nl-2021q1

 

 

728x90
728x90

Informix에서 DECIMAL 형식으로 정의된 컬럼의 길이를 확인하는 방법을 정리해보겠습니다. 컬럼 정보는 syscolumns 카탈로그 테이블에서 참조할 수 있는데, 컬럼의 길이는 collength 컬럼의 값으로 확인할 수 있습니다.

DECIMAL이나 MONEY 형식의 경우 전체 자릿수(precision), 소수 자릿수(scale)로 정의되는데 각 자릿수에 대해서 표시하는 컬럼은 없습니다. 이 정보를 나타내는 카탈로그 테이블이 있는지 IBM Community에 자문을 구했습니다.

 

먼저 Jonathan의 답변에 의하면 precision과 scale에 해당하는 값을 보여주는 컬럼은 없고 syscolumns 테이블의 collength 값을 16진수로 변환하여 확인할 수 있다고 합니다. 

$ dbaccess stores_demo -
Database selected.
> SELECT t.tabid, t.tabname, c.colno, c.colname, c.coltype, c.collength, HEX(c.collength)
> FROM "informix".systables AS t
> JOIN "informix".syscolumns AS c ON t.tabid = c.tabid
> WHERE c.coltype IN (5, 8, 261, 264);
tabid         102
tabname       orders
colno         8
colname       ship_weight
coltype       5
collength     2050
(expression)  0x00000802
tabid         102
tabname       orders
colno         9
colname       ship_charge
coltype       8
collength     1538
(expression)  0x00000602
...

coltype의 조건인 5, 8, 261, 264는 DECIMAL과 MONEY 형식을 참조하기 위한 것입니다. IBM Knowledge Center 내용에 따르면 collength 값을 16진수로 변환했을때의 가장 낮은 byte 주소가 precision, 다음으로 낮은 주소가 scale에 해당하는 값이라고 하네요.

The next example displays the data type and column length of the columns of the orders table in hexadecimal format. For MONEY and DECIMAL columns, you can then determine the precision and scale from the lowest and next-to-the-lowest bytes.

위의 orders 테이블의 경우를 예를 들면 ship_weight 컬럼의 collength 값 2050을 16진수로 변환하면 '0x00000802' 입니다. 16진수는 한자리가 4bit이므로 가장 낮은 byte 주소는 '08' 입니다. 그 다음은 '02' 이므로 최종적으로 DECIMAL(8,2) 형식의 컬럼이라는 것을 알 수 있습니다.

 

형식을 확인하는 방법은 알았는데 카탈로그 테이블의 값을 사용하여 쿼리 결과로 표시할 수 있으면 편리할 것 같다는 생각이 듭니다. 저는 16진수 문자열을 SUBSTR 함수를 사용해서 precision, scale에 해당하는 해당 16진수 부분을 BIGINT로 형변환하는 식으로 구했는데요. Art Kagel씨의 답변에 따르면 decimal.h 파일에 힌트가 있군요.

#define PRECTOT(x)      (((x)>>8) & 0xff)
#define PRECDEC(x)      ((x) & 0xff)

연산자 '>>' 와 '&' 는 C프로그램에서 비트연산을 의미합니다. '>>'의 경우 비트 우측 시프트 연산, '&'는 비트 AND 연산인데요. '& 0xff'는 최하위 8비트를 추출하기 위한, 소위 마스킹이라고도 합니다.

앞서 제가 구한 방법과 비슷하다고도 할 수 있습니다. precision의 경우 '0x00000802'를 비트 우측 시프트 연산으로 8비트 만큼 이동하게 되면 '0x00000008' 이 되고 다시 '0xff' 와 비트 AND 연산을 하면 '08' 을 추출하게 되니까요. 비트 이동 없이 '0xff'와 비트 AND 연산을 하면 2가 됩니다.

그런데 오라클이나 MySQL, PostgreSQL은 비트 연산자가 존재하는데 Informix에는 비트 시프트 연산 기능이 존재하는지 문서에 나오질 않는군요. 그래서 IBM Community에 Informix에 비트 시프트 연산 기능이 있는지 추가로 질문해서 Andreas의 답변으로 ifx_bit_rightshift 함수가 존재한다는 것을 알게 되었습니다.

SELECT t.tabid, t.tabname, c.colno, c.colname, c.coltype, c.collength, HEX(c.collength),
       decode(bitand(c.coltype, "0xff"), 5, "decimal", 8, "money", "<...>") || "(" ||
        ifx_bit_rightshift(c.collength, 8) || "," || bitand(c.collength, "0xff") || ")"
        as type
  FROM "informix".systables AS t
  JOIN "informix".syscolumns AS c ON t.tabid = c.tabid
 WHERE c.coltype IN (5, 8, 261, 264);

물론 ifx_bit_leftshift 함수도 존재하네요. BITAND, BITXOR 같은 함수는 매뉴얼에 나와있는데 비트 시프트 함수들은 문서화되지 않았거나 숨겨진 기능 같습니다. 자주 쓰이진 않겠지만 경우에 따라서 유용할 듯 합니다.

 

www.ibm.com/support/knowledgecenter/SSGU8G_14.1.0/com.ibm.sqls.doc/ids_sqs_1516.htm

 

728x90
728x90

인포믹스에서 함수 인덱스를 찾는 방법에 대한 질문이 있어서 찾아보았습니다.

우선 카탈로그 테이블인 sysindexes 부터 살펴보니 함수 인덱스임을 표시하는 컬럼은 없었습니다.

그래서 sysindexes 테이블의 함수 인덱스 정보가 다른 인덱스와 차이가 있는지 확인해봤습니다.

 

먼저 테이블과 함수 인덱스를 만들었습니다. 내용은 IBM 문서를 참고했습니다.

www.ibm.com/developerworks/data/library/techarticle/dm-0712wilcox/index.html

$ dbaccess stores_demo -
Database selected.
> CREATE TABLE circles ( radius FLOAT );
Table created.
> CREATE FUNCTION circleArea( radius FLOAT ) RETURNS float
>     WITH (NOT VARIANT);
>
>     RETURN 3.14159 * radius * radius;
> END FUNCTION;
Routine created.
> CREATE INDEX areaOfCircleIndex on circles( circleArea( radius ) );
Index created.

 

해당 인덱스에 대한 sysindexes 테이블의 정보를 확인해보았습니다.

> select * from sysindexes where idxname='areaofcircleindex';
idxname    areaofcircleindex
owner      informix
tabid      162
idxtype    D
clustered
part1      0
part2      0
part3      0
part4      0
part5      0
part6      0
part7      0
part8      0
part9      0
part10     0
part11     0
part12     0
part13     0
part14     0
part15     0
part16     0
levels     1
leaves     1.000000000000
nunique    0.00
clust      0.00
1 row(s) retrieved.

특이하게도 일반 인덱스와 달리 part1 값이 0으로 표시됩니다. 인덱스를 만들 때 컬럼 순서를 바꾸고 일반 컬럼과 혼용해도 동일한 결과를 보여줍니다. 그럼 part1 값이 0이면 함수 인덱스인가? 라는 생각이 들어서 정말 그런지 실행해보았습니다.

> select owner, idxname from sysindexes where tabid > 99 and idxname[1,1] <> ' ' and part1 = 0;
owner    informix
idxname  ucnameindex
owner    informix
idxname  ts_data_location_spix
owner    informix
idxname  areaofcircleindex
3 row(s) retrieved.

 

데모용 데이터베이스인 stores_demo에서 수행해보니 opclass에 대한 인덱스와 함수 인덱스 두개가 보입니다. 정확히 함수 인덱스만 나오는 것은 아니고 일반적인 타입의 인덱스는 제외되는 것 같습니다. 어설프지만 확인은 가능하네요.

그래서 좀 더 정확한 방법에 대한 조언을 구하기위해 IBM Community에 질문을 올렸습니다. 바로 Art Kagel씨와 Paul Watson씨가 명쾌한 답을 주시는군요. 답은 sysindices 카탈로그 테이블에 있었습니다.

> select idxname from sysindices where indexkeys::lvarchar matches '*<[0-9]*>*';
idxname  ucnameindex
idxname  areaofcircleindex
2 row(s) retrieved.
> select idxname, indexkeys from sysindices where indexkeys::lvarchar matches '*<[0-9]*>*';
idxname    ucnameindex
indexkeys  2 [1], <1757>(3) [1], 1 [1]
idxname    areaofcircleindex
indexkeys  <1758>(1) [1]
2 row(s) retrieved.

sysindices 테이블의 indexkeys 컬럼 값에 함수 인덱스에 대한 정보가 있더군요. opclass에 대한 정보도 있는데 이부분은 저도 잘은 모르고 이 내용과는 벗어나는 내용이라 넘어가겠습니다. indexkeys 컬럼에도 딱 이 인덱스가 함수 인덱스다! 라고 알려주는 플래그 값이 있는건 아니지만, 함수 인덱스인 경우 <> 사이에 procid 값 정보가 있습니다. 이 정보로 인덱스가 함수 인덱스임을 알 수 있는 것입니다.

아래는 IBM Knowledge Center의 sysindices 테이블에 대한 설명입니다.


The fields within the indexkeys columns have the following significance:

  • The procid (as in sysprocedures) exists only for a functional index on return values of a function defined on columns of the table.
  • The list of columns (col1, col2, ... , coln) in the second field identifies the columns on which the index is defined. The maximum is language-dependent: up to 341 for an SPL or Java™ UDR; up to 102 for a C UDR.
  • The opclassid identifies the secondary access method that the database server used to build and to search the index. This is the same as the sysopclasses.opclassid value for the access method.
  •  

IBM Community에서 좋은 것을 배웠네요.

728x90

+ Recent posts