@@ -75,6 +75,13 @@ var nonIndexJSONHistograms = settings.RegisterBoolSetting(
75
75
true ,
76
76
settings .WithPublic )
77
77
78
+ var automaticJobCheckBeforeCreatingJob = settings .RegisterBoolSetting (
79
+ settings .ApplicationLevel ,
80
+ "sql.stats.automatic_job_check_before_creating_job.enabled" ,
81
+ "set to true to perform the autostats job check before creating the job, instead of in the same " +
82
+ "transaction as creating the job" ,
83
+ true )
84
+
78
85
const nonIndexColHistogramBuckets = 2
79
86
80
87
// StubTableStats generates "stub" statistics for a table which are missing
@@ -146,18 +153,29 @@ func (n *createStatsNode) runJob(ctx context.Context) error {
146
153
}
147
154
details := record .Details .(jobspb.CreateStatsDetails )
148
155
149
- if n .Name != jobspb .AutoStatsName && n .Name != jobspb .AutoPartialStatsName {
156
+ jobCheckBefore := automaticJobCheckBeforeCreatingJob .Get (n .p .ExecCfg ().SV ())
157
+ if n .Name == jobspb .AutoStatsName || n .Name == jobspb .AutoPartialStatsName {
158
+ if jobCheckBefore {
159
+ // Don't start the job if there is already a CREATE STATISTICS job running.
160
+ // (To handle race conditions we check this again after the job starts,
161
+ // but this check is used to prevent creating a large number of jobs that
162
+ // immediately fail).
163
+ if err := checkRunningJobs (
164
+ ctx , nil /* job */ , n .p , n .Name == jobspb .AutoPartialStatsName , n .p .ExecCfg ().JobRegistry ,
165
+ details .Table .ID ,
166
+ ); err != nil {
167
+ return err
168
+ }
169
+ }
170
+ } else {
150
171
telemetry .Inc (sqltelemetry .CreateStatisticsUseCounter )
151
172
}
152
173
153
174
var job * jobs.StartableJob
154
175
jobID := n .p .ExecCfg ().JobRegistry .MakeJobID ()
155
176
if err := n .p .ExecCfg ().InternalDB .Txn (ctx , func (ctx context.Context , txn isql.Txn ) (err error ) {
156
- if n .Name == jobspb .AutoStatsName || n .Name == jobspb .AutoPartialStatsName {
177
+ if ( n .Name == jobspb .AutoStatsName || n .Name == jobspb .AutoPartialStatsName ) && ! jobCheckBefore {
157
178
// Don't start the job if there is already a CREATE STATISTICS job running.
158
- // (To handle race conditions we check this again after the job starts,
159
- // but this check is used to prevent creating a large number of jobs that
160
- // immediately fail).
161
179
if err := checkRunningJobsInTxn (
162
180
ctx , n .p .EvalContext ().Settings , jobspb .InvalidJobID , txn ,
163
181
); err != nil {
0 commit comments