PostgreSQL 的 int2 与 smallint 类型
            时间:2015-10-28 21:20:58  
            收藏:0  
            阅读:5064
        
        
        工作需要,今天调查了一下 smallint 的类型实现,首先打开 pg_type 搜索 smallint,没找到。文档说明 smallint 的别名是 int2,查找发现 BKI 定义是 int2,也就是2字节整数,跟印象中不一样。
打开 gram.y,发现确实有一个 smallint 向 int2 的同义词变换,打开一个库查看初始化之后的定义,仍然是 int2,psql 中查看表结构定义,并没有显示为 int2,而是 smallint,跟随代码看看这是怎么做到的。
gram.y 中的代码,不仅仅是 int2,还有 int4 float4 等等
Numeric:	INT_P
				{
					$$ = SystemTypeName("int4");
					$$->location = @1;
				}
			| INTEGER
				{
					$$ = SystemTypeName("int4");
					$$->location = @1;
				}
			| SMALLINT
				{
					$$ = SystemTypeName("int2");
					$$->location = @1;
				}
			| BIGINT
				{
					$$ = SystemTypeName("int8");
					$$->location = @1;
				}
答案很简单,这必然是产生了一个 int2 到 smallint的转换,我们直接在代码中区分大小写搜索 "smallint"。
src/backend/utils/adt/format_type.c 找到如下定义:
case FLOAT4OID:
			buf = pstrdup("real");
			break;
		case FLOAT8OID:
			buf = pstrdup("double precision");
			break;
		case INT2OID:
			buf = pstrdup("smallint");
			break;
上述定义在函数 format_type_internal 中
看明白到底是怎么回事,但感觉。。。莫名其妙,无法理解。
可能是历史原因吧
原文:http://my.oschina.net/quanzl/blog/523279
            评论(0)
        
        
        