* get_typdefault * Given a type OID, return the type's default value, if any. * * The result is a palloc'd expression node tree, or NULL if there * is no defined default for the datatype. * * NB: caller should be prepared to coerce result to correct datatype; * the returned expression tree might produce something of the wrong type. */
| 3046 | * the returned expression tree might produce something of the wrong type. |
| 3047 | */ |
| 3048 | Node * |
| 3049 | get_typdefault(Oid typid) |
| 3050 | { |
| 3051 | HeapTuple typeTuple; |
| 3052 | Form_pg_type type; |
| 3053 | Datum datum; |
| 3054 | bool isNull; |
| 3055 | Node *expr; |
| 3056 | |
| 3057 | typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid)); |
| 3058 | if (!HeapTupleIsValid(typeTuple)) |
| 3059 | elog(ERROR, "cache lookup failed for type %u", typid); |
| 3060 | type = (Form_pg_type) GETSTRUCT(typeTuple); |
| 3061 | |
| 3062 | /* |
| 3063 | * typdefault and typdefaultbin are potentially null, so don't try to |
| 3064 | * access 'em as struct fields. Must do it the hard way with |
| 3065 | * SysCacheGetAttr. |
| 3066 | */ |
| 3067 | datum = SysCacheGetAttr(TYPEOID, |
| 3068 | typeTuple, |
| 3069 | Anum_pg_type_typdefaultbin, |
| 3070 | &isNull); |
| 3071 | |
| 3072 | if (!isNull) |
| 3073 | { |
| 3074 | /* We have an expression default */ |
| 3075 | expr = stringToNode(TextDatumGetCString(datum)); |
| 3076 | } |
| 3077 | else |
| 3078 | { |
| 3079 | /* Perhaps we have a plain literal default */ |
| 3080 | datum = SysCacheGetAttr(TYPEOID, |
| 3081 | typeTuple, |
| 3082 | Anum_pg_type_typdefault, |
| 3083 | &isNull); |
| 3084 | |
| 3085 | if (!isNull) |
| 3086 | { |
| 3087 | char *strDefaultVal; |
| 3088 | |
| 3089 | /* Convert text datum to C string */ |
| 3090 | strDefaultVal = TextDatumGetCString(datum); |
| 3091 | /* Convert C string to a value of the given type */ |
| 3092 | datum = OidInputFunctionCall(type->typinput, strDefaultVal, |
| 3093 | getTypeIOParam(typeTuple), -1); |
| 3094 | /* Build a Const node containing the value */ |
| 3095 | expr = (Node *) makeConst(typid, |
| 3096 | -1, |
| 3097 | type->typcollation, |
| 3098 | type->typlen, |
| 3099 | datum, |
| 3100 | false, |
| 3101 | type->typbyval); |
| 3102 | pfree(strDefaultVal); |
| 3103 | } |
| 3104 | else |
| 3105 | { |
no test coverage detected