* Make an expression tree for the default value for a column. * * If there is no default, return a NULL instead. */
| 1248 | * If there is no default, return a NULL instead. |
| 1249 | */ |
| 1250 | Node * |
| 1251 | build_column_default(Relation rel, int attrno) |
| 1252 | { |
| 1253 | TupleDesc rd_att = rel->rd_att; |
| 1254 | Form_pg_attribute att_tup = TupleDescAttr(rd_att, attrno - 1); |
| 1255 | Oid atttype = att_tup->atttypid; |
| 1256 | int32 atttypmod = att_tup->atttypmod; |
| 1257 | Node *expr = NULL; |
| 1258 | Oid exprtype; |
| 1259 | |
| 1260 | if (att_tup->attidentity) |
| 1261 | { |
| 1262 | NextValueExpr *nve = makeNode(NextValueExpr); |
| 1263 | |
| 1264 | nve->seqid = getIdentitySequence(RelationGetRelid(rel), attrno, false); |
| 1265 | nve->typeId = att_tup->atttypid; |
| 1266 | |
| 1267 | return (Node *) nve; |
| 1268 | } |
| 1269 | |
| 1270 | /* |
| 1271 | * If relation has a default for this column, fetch that expression. |
| 1272 | */ |
| 1273 | if (att_tup->atthasdef) |
| 1274 | { |
| 1275 | if (rd_att->constr && rd_att->constr->num_defval > 0) |
| 1276 | { |
| 1277 | AttrDefault *defval = rd_att->constr->defval; |
| 1278 | int ndef = rd_att->constr->num_defval; |
| 1279 | |
| 1280 | while (--ndef >= 0) |
| 1281 | { |
| 1282 | if (attrno == defval[ndef].adnum) |
| 1283 | { |
| 1284 | /* Found it, convert string representation to node tree. */ |
| 1285 | expr = stringToNode(defval[ndef].adbin); |
| 1286 | break; |
| 1287 | } |
| 1288 | } |
| 1289 | } |
| 1290 | if (expr == NULL) |
| 1291 | elog(ERROR, "default expression not found for attribute %d of relation \"%s\"", |
| 1292 | attrno, RelationGetRelationName(rel)); |
| 1293 | } |
| 1294 | |
| 1295 | /* |
| 1296 | * No per-column default, so look for a default for the type itself. But |
| 1297 | * not for generated columns. |
| 1298 | */ |
| 1299 | if (expr == NULL && !att_tup->attgenerated) |
| 1300 | expr = get_typdefault(atttype); |
| 1301 | |
| 1302 | if (expr == NULL) |
| 1303 | return NULL; /* No default anywhere */ |
| 1304 | |
| 1305 | /* |
| 1306 | * Make sure the value is coerced to the target column type; this will |
| 1307 | * generally be true already, but there seem to be some corner cases |
no test coverage detected