#include "postgres.h" #include "access/genam.h" #include "access/heapam.h" #include "miscadmin.h" #include "storage/lmgr.h" #include "storage/bufmgr.h" #include "catalog/namespace.h" #include "utils/lsyscache.h" #include "utils/builtins.h" #include #include #include #include #include #include #include #include #include "utils/regproc.h" #include "utils/varlena.h" #ifdef PG_MODULE_MAGIC PG_MODULE_MAGIC; #endif PG_FUNCTION_INFO_V1(fasttruncate); Datum fasttruncate(PG_FUNCTION_ARGS); Datum fasttruncate(PG_FUNCTION_ARGS) { text *name=PG_GETARG_TEXT_P(0); char *relname; List *relname_list; RangeVar *relvar; Oid relOid; Relation rel; bool makeanalyze = false; relname = palloc( VARSIZE(name) + 1); memcpy(relname, VARDATA(name), VARSIZE(name)-VARHDRSZ); relname[ VARSIZE(name)-VARHDRSZ ] = '\0'; relname_list = stringToQualifiedNameList(relname, NULL); relvar = makeRangeVarFromNameList(relname_list); relOid = RangeVarGetRelid(relvar, AccessExclusiveLock, false); if ( get_rel_relkind(relOid) != RELKIND_RELATION ) elog(ERROR,"Relation isn't a ordinary table"); rel = table_open(relOid, NoLock); if ( !isTempNamespace(get_rel_namespace(relOid)) ) elog(ERROR,"Relation isn't a temporary table"); heap_truncate(list_make1_oid(relOid)); if ( rel->rd_rel->relpages > 0 || rel->rd_rel->reltuples > 0 ) makeanalyze = true; /* * heap_truncate doesn't unlock the table, * so we should unlock it. */ table_close(rel, AccessExclusiveLock); if ( makeanalyze ) { VacuumParams params = {0}; VacuumRelation *rel; MemoryContext vac_context; MemoryContext old_context; BufferAccessStrategy bstrategy; params.options = VACOPT_ANALYZE; params.freeze_min_age = -1; params.freeze_table_age = -1; params.multixact_freeze_min_age = -1; params.multixact_freeze_table_age = -1; params.is_wraparound = false; params.log_vacuum_min_duration = -1; params.log_analyze_min_duration = -1; params.index_cleanup = VACOPTVALUE_UNSPECIFIED; params.truncate = VACOPTVALUE_UNSPECIFIED; params.toast_parent = InvalidOid; params.max_eager_freeze_failure_rate = vacuum_max_eager_freeze_failure_rate; params.nworkers = 0; rel = makeNode(VacuumRelation); rel->relation = relvar; rel->oid = relOid; rel->va_cols = NULL; vac_context = AllocSetContextCreate(PortalContext, "Vacuum", ALLOCSET_DEFAULT_SIZES); old_context = MemoryContextSwitchTo(vac_context); bstrategy = GetAccessStrategy(BAS_VACUUM); MemoryContextSwitchTo(old_context); vacuum(list_make1(rel), ¶ms, bstrategy, vac_context, false); MemoryContextDelete(vac_context); } PG_RETURN_VOID(); }