Skip to content

Commit 2c20445

Browse files
leosvelperezFrozenPandaz
authored andcommitted
fix(core): create all tables upfront when creating the database (#33843)
Create all the tables upfront when creating the database. This prevents some issues in some scenarios where a missing table is reported. (cherry picked from commit ed09ee1)
1 parent f16d879 commit 2c20445

File tree

7 files changed

+65
-104
lines changed

7 files changed

+65
-104
lines changed

packages/nx/src/native/cache/cache.rs

Lines changed: 11 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,15 @@ use crate::native::cache::file_ops::_copy;
1414
use crate::native::db::connection::NxDbConnection;
1515
use crate::native::utils::Normalize;
1616

17+
pub const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS cache_outputs (
18+
hash TEXT PRIMARY KEY NOT NULL,
19+
code INTEGER NOT NULL,
20+
size INTEGER NOT NULL,
21+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
22+
accessed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
23+
FOREIGN KEY (hash) REFERENCES task_details (hash)
24+
);";
25+
1726
#[napi(object)]
1827
#[derive(Default, Clone, Debug)]
1928
pub struct CachedResult {
@@ -29,7 +38,6 @@ pub struct NxCache {
2938
workspace_root: PathBuf,
3039
cache_path: PathBuf,
3140
db: External<NxDbConnection>,
32-
link_task_details: bool,
3341
max_cache_size: i64,
3442
}
3543

@@ -40,7 +48,6 @@ impl NxCache {
4048
workspace_root: String,
4149
cache_path: String,
4250
db_connection: External<NxDbConnection>,
43-
link_task_details: Option<bool>,
4451
max_cache_size: Option<i64>,
4552
) -> anyhow::Result<Self> {
4653
let cache_path = PathBuf::from(&cache_path);
@@ -50,44 +57,13 @@ impl NxCache {
5057

5158
let max_cache_size = max_cache_size.unwrap_or(0);
5259

53-
let r = Self {
60+
Ok(Self {
5461
db: db_connection,
5562
workspace_root: PathBuf::from(workspace_root),
5663
cache_directory: cache_path.to_normalized_string(),
5764
cache_path,
58-
link_task_details: link_task_details.unwrap_or(true),
5965
max_cache_size,
60-
};
61-
62-
r.setup()?;
63-
64-
Ok(r)
65-
}
66-
67-
fn setup(&self) -> anyhow::Result<()> {
68-
let query = if self.link_task_details {
69-
"CREATE TABLE IF NOT EXISTS cache_outputs (
70-
hash TEXT PRIMARY KEY NOT NULL,
71-
code INTEGER NOT NULL,
72-
size INTEGER NOT NULL,
73-
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
74-
accessed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
75-
FOREIGN KEY (hash) REFERENCES task_details (hash)
76-
);
77-
"
78-
} else {
79-
"CREATE TABLE IF NOT EXISTS cache_outputs (
80-
hash TEXT PRIMARY KEY NOT NULL,
81-
code INTEGER NOT NULL,
82-
size INTEGER NOT NULL,
83-
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
84-
accessed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
85-
);
86-
"
87-
};
88-
89-
self.db.execute(query, []).map_err(anyhow::Error::from)?;
90-
Ok(())
66+
})
9167
}
9268

9369
#[napi]

packages/nx/src/native/db/initialize.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1+
use crate::native::cache::cache::SCHEMA as CACHE_SCHEMA;
12
use crate::native::db::connection::NxDbConnection;
3+
use crate::native::tasks::details::SCHEMA as TASK_DETAILS_SCHEMA;
4+
use crate::native::tasks::running_tasks_service::SCHEMA as RUNNING_TASKS_SCHEMA;
5+
use crate::native::tasks::task_history::SCHEMA as TASK_HISTORY_SCHEMA;
26
use rusqlite::vtab::array;
37
use rusqlite::{Connection, OpenFlags};
48
use std::fs::{File, remove_file};
@@ -57,6 +61,7 @@ pub(super) fn initialize_db(nx_version: String, db_path: &Path) -> anyhow::Resul
5761
Err(s) if s.to_string().contains("metadata") => {
5862
configure_database(&c)?;
5963
create_metadata_table(&mut c, &nx_version)?;
64+
create_all_tables(&mut c)?;
6065
c
6166
}
6267
reason => {
@@ -108,6 +113,24 @@ fn create_metadata_table(c: &mut NxDbConnection, nx_version: &str) -> anyhow::Re
108113
Ok(())
109114
}
110115

116+
fn create_all_tables(c: &mut NxDbConnection) -> anyhow::Result<()> {
117+
debug!("Creating all database tables");
118+
119+
c.transaction(|conn| {
120+
// Order matters: tables with no FK dependencies first
121+
conn.execute_batch(TASK_DETAILS_SCHEMA)?;
122+
conn.execute_batch(RUNNING_TASKS_SCHEMA)?;
123+
124+
// Tables with FK dependencies
125+
conn.execute_batch(TASK_HISTORY_SCHEMA)?;
126+
conn.execute_batch(CACHE_SCHEMA)?;
127+
128+
Ok(())
129+
})?;
130+
131+
Ok(())
132+
}
133+
111134
fn open_database_connection(db_path: &Path) -> anyhow::Result<NxDbConnection> {
112135
let conn = Connection::open_with_flags(
113136
db_path,

packages/nx/src/native/index.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ export declare class ImportResult {
6969

7070
export declare class NxCache {
7171
cacheDirectory: string
72-
constructor(workspaceRoot: string, cachePath: string, dbConnection: ExternalObject<NxDbConnection>, linkTaskDetails?: boolean | undefined | null, maxCacheSize?: number | undefined | null)
72+
constructor(workspaceRoot: string, cachePath: string, dbConnection: ExternalObject<NxDbConnection>, maxCacheSize?: number | undefined | null)
7373
get(hash: string): CachedResult | null
7474
put(hash: string, terminalOutput: string, outputs: Array<string>, code: number): void
7575
applyRemoteCacheResults(hash: string, result: CachedResult, outputs?: Array<string> | undefined | null): void

packages/nx/src/native/tasks/details.rs

Lines changed: 8 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,13 @@ use napi::bindgen_prelude::*;
33
use rusqlite::params;
44
use tracing::trace;
55

6+
pub const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS task_details (
7+
hash TEXT PRIMARY KEY NOT NULL,
8+
project TEXT NOT NULL,
9+
target TEXT NOT NULL,
10+
configuration TEXT
11+
);";
12+
613
#[napi(object)]
714
#[derive(Default, Clone, Debug)]
815
pub struct HashedTask {
@@ -21,25 +28,7 @@ pub struct TaskDetails {
2128
impl TaskDetails {
2229
#[napi(constructor)]
2330
pub fn new(db: External<NxDbConnection>) -> anyhow::Result<Self> {
24-
let r = Self { db };
25-
26-
r.setup()?;
27-
28-
Ok(r)
29-
}
30-
31-
fn setup(&self) -> anyhow::Result<()> {
32-
self.db.execute(
33-
"CREATE TABLE IF NOT EXISTS task_details (
34-
hash TEXT PRIMARY KEY NOT NULL,
35-
project TEXT NOT NULL,
36-
target TEXT NOT NULL,
37-
configuration TEXT
38-
);",
39-
params![],
40-
)?;
41-
42-
Ok(())
31+
Ok(Self { db })
4332
}
4433

4534
#[napi]

packages/nx/src/native/tasks/running_tasks_service.rs

Lines changed: 9 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,13 @@ use std::ffi::OsString;
77
use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System};
88
use tracing::debug;
99

10+
pub const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS running_tasks (
11+
task_id TEXT PRIMARY KEY NOT NULL,
12+
pid INTEGER NOT NULL,
13+
command TEXT NOT NULL,
14+
cwd TEXT NOT NULL
15+
);";
16+
1017
#[napi]
1118
struct RunningTasksService {
1219
db: External<NxDbConnection>,
@@ -17,14 +24,10 @@ struct RunningTasksService {
1724
impl RunningTasksService {
1825
#[napi(constructor)]
1926
pub fn new(db: External<NxDbConnection>) -> anyhow::Result<Self> {
20-
let s = Self {
27+
Ok(Self {
2128
db,
2229
added_tasks: Default::default(),
23-
};
24-
25-
s.setup()?;
26-
27-
Ok(s)
30+
})
2831
}
2932

3033
#[napi]
@@ -115,21 +118,6 @@ impl RunningTasksService {
115118
debug!("Removed {} from running tasks", task_id);
116119
Ok(())
117120
}
118-
119-
fn setup(&self) -> anyhow::Result<()> {
120-
self.db.execute_batch(
121-
"
122-
CREATE TABLE IF NOT EXISTS running_tasks (
123-
task_id TEXT PRIMARY KEY NOT NULL,
124-
pid INTEGER NOT NULL,
125-
command TEXT NOT NULL,
126-
cwd TEXT NOT NULL
127-
);
128-
",
129-
)?;
130-
debug!("Setup running tasks service");
131-
Ok(())
132-
}
133121
}
134122

135123
impl Drop for RunningTasksService {

packages/nx/src/native/tasks/task_history.rs

Lines changed: 13 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,18 @@ use std::collections::HashMap;
66
use std::rc::Rc;
77
use tracing::trace;
88

9+
pub const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS task_history (
10+
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
11+
hash TEXT NOT NULL,
12+
status TEXT NOT NULL,
13+
code INTEGER NOT NULL,
14+
start TIMESTAMP NOT NULL,
15+
end TIMESTAMP NOT NULL,
16+
FOREIGN KEY (hash) REFERENCES task_details (hash)
17+
);
18+
CREATE INDEX IF NOT EXISTS hash_idx ON task_history (hash);
19+
CREATE INDEX IF NOT EXISTS status_idx ON task_history (status);";
20+
921
#[napi(object)]
1022
pub struct TaskRun {
1123
pub hash: String,
@@ -24,33 +36,7 @@ pub struct NxTaskHistory {
2436
impl NxTaskHistory {
2537
#[napi(constructor)]
2638
pub fn new(db: External<NxDbConnection>) -> anyhow::Result<Self> {
27-
let s = Self { db };
28-
29-
s.setup()?;
30-
31-
Ok(s)
32-
}
33-
34-
fn setup(&self) -> anyhow::Result<()> {
35-
self.db
36-
.execute_batch(
37-
"
38-
BEGIN IMMEDIATE;
39-
CREATE TABLE IF NOT EXISTS task_history (
40-
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
41-
hash TEXT NOT NULL,
42-
status TEXT NOT NULL,
43-
code INTEGER NOT NULL,
44-
start TIMESTAMP NOT NULL,
45-
end TIMESTAMP NOT NULL,
46-
FOREIGN KEY (hash) REFERENCES task_details (hash)
47-
);
48-
CREATE INDEX IF NOT EXISTS hash_idx ON task_history (hash);
49-
CREATE INDEX IF NOT EXISTS status_idx ON task_history (status);
50-
COMMIT;
51-
",
52-
)
53-
.map_err(anyhow::Error::from)
39+
Ok(Self { db })
5440
}
5541

5642
#[napi]

packages/nx/src/tasks-runner/cache.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,6 @@ export class DbCache {
7878
workspaceRoot,
7979
cacheDir,
8080
getDbConnection(),
81-
undefined,
8281
resolveMaxCacheSize(this.nxJson)
8382
);
8483

0 commit comments

Comments
 (0)