Skip to content

Commit 043fa04

Browse files
committed
Implement save
1 parent d2baefb commit 043fa04

File tree

25 files changed

+620
-85
lines changed

25 files changed

+620
-85
lines changed

Cargo.lock

Lines changed: 78 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

__tests__/sql/index.test.ts

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,13 +74,13 @@ describe.sequential('sqlite', async () => {
7474

7575
@Column({
7676
default: Func.now(),
77+
type: DevupModelColumnType.DateTime,
7778
})
7879
createdAt: Date
7980
}
8081

8182
const hasRevision = await pool.hasRevision()
8283
expect(hasRevision).toBe(false)
83-
console.log('hasRevision', hasRevision)
8484
if (!hasRevision) {
8585
await pool.setupRevision()
8686
}
@@ -92,12 +92,12 @@ describe.sequential('sqlite', async () => {
9292
const revisionSql = await pool.getRevisionSql(nextRevision, true)
9393
expect(revisionSql).toEqual([
9494
{
95-
sql: `CREATE TABLE user (id INTEGER NOT NULL, username VARCHAR(255) NOT NULL DEFAULT \`devup\`, tag TEXT NULL, created_at DATE NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id))`,
95+
sql: `CREATE TABLE user (id INTEGER NOT NULL, username VARCHAR(255) NOT NULL DEFAULT \`devup\`, tag TEXT NULL, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id))`,
9696
params: [],
9797
},
9898
])
9999
expect(await pool.getCurrentRevision()).toBe(0)
100-
// // migrate to next revision
100+
// migrate to next revision
101101
await pool.migrate(nextRevision)
102102

103103
expect(await pool.getCurrentRevision()).toBe(1)
@@ -107,7 +107,6 @@ describe.sequential('sqlite', async () => {
107107
id: 1,
108108
tag: '',
109109
})
110-
111110
await pool.save(user)
112111
expect(await pool.fetchAll('SELECT COUNT(*) as count FROM user')).toEqual(
113112
[
@@ -117,7 +116,16 @@ describe.sequential('sqlite', async () => {
117116
],
118117
)
119118
const ac = await pool.begin()
120-
await pool.save(user, ac)
119+
// assign __devup_instance_id to user
120+
await pool.save(
121+
User.create({
122+
username: 'devup',
123+
createdAt: new Date(),
124+
id: 3,
125+
tag: '',
126+
}),
127+
ac,
128+
)
121129

122130
expect(await pool.fetchAll('SELECT COUNT(*) as count FROM user')).toEqual(
123131
[
@@ -135,6 +143,17 @@ describe.sequential('sqlite', async () => {
135143
},
136144
],
137145
)
146+
console.log(user)
147+
148+
// user.id = 100
149+
// await pool.save(user)
150+
// expect(await pool.fetchAll('SELECT COUNT(*) as count FROM user')).toEqual(
151+
// [
152+
// {
153+
// count: 2,
154+
// },
155+
// ],
156+
// )
138157
// await user.save()
139158

140159
// const user2 = new User()

core/model/src/column.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,10 @@ pub enum DevupModelColumnType {
1616
Float,
1717
Number,
1818
Date,
19-
Time {
20-
timezone: bool,
21-
},
22-
DateTime {
23-
timezone: bool,
24-
},
19+
// timezone
20+
Time(bool),
21+
// timezone
22+
DateTime(bool),
2523
Binary,
2624
Enum(HashSet<String>),
2725

libs/node/model/src/model.rs

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
use model::{DevupModel, add_model};
22
use napi::{Env, JsFunction, JsObject, JsString, bindgen_prelude::*};
33

4+
use crate::utils::{console_dir, log};
5+
46
/// Model decorator
57
#[napi(js_name = "Model")]
68
pub fn model(env: Env, name: Option<String>) -> Result<JsFunction> {
@@ -18,17 +20,32 @@ pub fn model(env: Env, name: Option<String>) -> Result<JsFunction> {
1820
.unwrap()
1921
.to_string()
2022
});
23+
let cls = cls.into_unknown();
2124

22-
let fields = ctx.env.from_js_value(get_metadata.call(
25+
println!("get_metadata:");
26+
let f = get_metadata.call(
2327
None,
2428
&[
2529
&ctx.env.create_string("devup-api:fields")?.into_unknown(),
26-
&cls.into_unknown(),
30+
&cls,
2731
],
28-
)?)?;
32+
)?;
33+
{
34+
let f = get_metadata.call(
35+
None,
36+
&[
37+
&ctx.env.create_string("devup-api:fields")?.into_unknown(),
38+
&cls,
39+
],
40+
)?;
41+
console_dir(&env, f)?;
42+
}
43+
44+
let fields = ctx.env.from_js_value(f);
45+
println!("fields: {:?}", fields);
2946
add_model(DevupModel {
3047
name: model_name,
31-
fields,
48+
fields: fields?,
3249
})
3350
.map_err(|e| napi::Error::from_reason(e.to_string()))?;
3451

libs/node/model/src/utils.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,13 @@ pub fn log(env: &Env, value: JsUnknown) -> Result<()> {
77
log_fn.call(None, &[value])?;
88
Ok(())
99
}
10+
11+
pub fn console_dir(env: &Env, value: JsUnknown) -> Result<()> {
12+
let global = env.get_global()?;
13+
let console: JsObject = global.get_named_property("console")?;
14+
let log_fn = console.get_named_property::<JsFunction>("dir")?;
15+
let mut options = env.create_object()?;
16+
options.set_named_property("depth", env.get_null())?;
17+
log_fn.call(None, &[value, options.into_unknown()])?;
18+
Ok(())
19+
}

libs/node/struct/src/column/devup_model_column_type.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ impl From<JsDevupModelColumnType> for DevupModelColumnType {
3535
JsDevupModelColumnType::Float => DevupModelColumnType::Float,
3636
JsDevupModelColumnType::Number => DevupModelColumnType::Number,
3737
JsDevupModelColumnType::Date => DevupModelColumnType::Date,
38-
JsDevupModelColumnType::Time => DevupModelColumnType::Time { timezone: false },
39-
JsDevupModelColumnType::DateTime => DevupModelColumnType::DateTime { timezone: false },
38+
JsDevupModelColumnType::Time => DevupModelColumnType::Time(true),
39+
JsDevupModelColumnType::DateTime => DevupModelColumnType::DateTime(true),
4040
JsDevupModelColumnType::Binary => DevupModelColumnType::Binary,
4141
JsDevupModelColumnType::Enum => DevupModelColumnType::Enum(HashSet::new()),
4242
JsDevupModelColumnType::Any => DevupModelColumnType::Any,

sql/core/database_strategy/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,4 @@ edition = "2024"
77
sqlx = { version = "0.8" }
88
async-trait = "0.1"
99
model = { path = "../../../core/model" }
10+
serde_json = "1.0.140"
Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,46 @@
1+
use std::sync::Arc;
2+
13
use async_trait::async_trait;
2-
use model::column::DevupModelColumn;
3-
use sqlx::{Any, Error, Pool, Transaction};
4+
use model::{
5+
DevupModel,
6+
column::{DevupModelColumn, DevupModelColumnType},
7+
};
8+
use serde_json::{Map, Value};
9+
use sqlx::{Any, AnyConnection, Error, Pool, Transaction};
410

511
pub enum QueryParams {
612
Number,
713
QuestionMark,
814
}
915

16+
pub struct InsertResult {
17+
pub instance: Map<String, Value>,
18+
pub instance_id: Map<String, Value>,
19+
}
20+
21+
#[derive(Debug)]
22+
pub enum BindWrapper {
23+
Bind(Value),
24+
Direct(Value),
25+
}
26+
1027
#[async_trait]
1128
pub trait DatabaseStrategy: Send + Sync {
1229
async fn has_revision(&self, pool: &Pool<Any>) -> Result<bool, Error>;
1330
async fn setup_revision(&self, tx: &mut Transaction<'_, Any>) -> Result<(), Error>;
1431
fn convert_sql_column_type(&self, column: &DevupModelColumn) -> String;
32+
// fn convert_value_to_sql_value(
33+
// &self,
34+
// value: String,
35+
// column_type: &DevupModelColumnType,
36+
// ) -> String;
1537
fn get_query_params(&self) -> QueryParams;
1638
fn get_auto_increment_sql(&self) -> Option<String>;
1739
fn get_default_function_sql(&self, default: &str) -> String;
40+
async fn insert_sql_and_return_instance(
41+
&self,
42+
tx: &mut AnyConnection,
43+
model: Arc<DevupModel>,
44+
obj: &Value,
45+
) -> Result<InsertResult, Error>;
1846
}

0 commit comments

Comments
 (0)