Skip to content

Commit f100d97

Browse files
committed
Implement creating table
1 parent 7bbaa03 commit f100d97

File tree

41 files changed

+936
-256
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+936
-256
lines changed

Cargo.lock

Lines changed: 209 additions & 27 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: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
import 'reflect-metadata'
22

3-
import { Column, DevupModel, Func, Model } from '@devup-api/model'
3+
import {
4+
Column,
5+
DevupModel,
6+
DevupModelColumnType,
7+
Func,
8+
Model,
9+
} from '@devup-api/model'
410
import { createSqliteConnection } from '@devup-sql/sqlite'
511
describe('sqlite', async () => {
612
const pool = await createSqliteConnection({
@@ -56,6 +62,7 @@ describe('sqlite', async () => {
5662
// local default
5763
default: () => 'Hello',
5864
nullable: true,
65+
type: DevupModelColumnType.Text,
5966
})
6067
tag?: string
6168

@@ -78,8 +85,8 @@ describe('sqlite', async () => {
7885
const revisionSql = await pool.getRevisionSql(nextRevision, true)
7986
expect(revisionSql).toEqual([
8087
{
81-
sql: `CREATE TABLE "User" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "username" TEXT, "tag" TEXT, "createdAt" TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP))`,
82-
revision: 1,
88+
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))`,
89+
params: [],
8390
},
8491
])
8592
expect(await pool.getCurrentRevision()).toBe(0)

apps/sql-demo/src/index.ts

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,23 @@
1-
import { createPostgresPool } from "@devup-sql/postgres";
1+
import { createPostgresPool } from '@devup-sql/postgres'
22

33
async function main(): Promise<void> {
4-
try{
5-
4+
try {
65
console.log('[JS] create pool')
76
const pool = await createPostgresPool()
87

98
console.log('[JS] execute', pool)
109

11-
const result1 = await pool.fetchAll("SELECT 3", [])
10+
const result1 = await pool.fetchAll('SELECT 3', [])
1211
console.info('[JS] result1', result1)
13-
const result2 = await pool.fetchAll("SELECT 2", [])
12+
const result2 = await pool.fetchAll('SELECT 2', [])
1413
console.info('[JS] result2', result2)
15-
const result = await pool.execute("SELECT 1", [])
14+
const result = await pool.execute('SELECT 1', [])
1615

1716
console.info('[JS] result', result)
1817
console.info('[JS] finish')
19-
} catch (error) {
20-
console.error('[JS] error', error)
21-
}
18+
} catch (error) {
19+
console.error('[JS] error', error)
20+
}
2221
}
2322

2423
console.log('[JS] start')

core/api-option/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,4 @@ edition = "2024"
77
serde = { version = "1.0.219", features = ["derive"] }
88
serde_json = "1.0.140"
99
once_cell = "1.21.3"
10+
bincode = "2.0.1"

core/api-option/src/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
use bincode::{Decode, Encode};
12
use serde::{Deserialize, Serialize};
23

3-
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
4+
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Encode, Decode)]
45
pub enum DtoType {
56
One,
67
List,

core/model/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,5 @@ serde_json = "1.0.140"
99
once_cell = "1.21.3"
1010
schema = { path = "../schema" }
1111
api-option = { path = "../api-option" }
12+
shared_memory = "0.12.4"
13+
bincode = "2.0.1"

core/model/src/column.rs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
use api_option::DtoType;
2+
use bincode::{Decode, Encode};
23
use schema::{DevupSchema, field::DevupSchemaField};
34
use serde::{Deserialize, Serialize};
45
use std::collections::{HashMap, HashSet};
56

6-
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, Eq)]
7+
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, Eq, Encode, Decode)]
78
pub enum DevupModelColumnType {
89
String(u32),
910
Text,
@@ -32,36 +33,36 @@ pub enum DevupModelColumnType {
3233
Schema(DevupSchema),
3334
}
3435

35-
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
36+
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Encode, Decode)]
3637
pub enum DevupModelColumnUnique {
3738
True,
3839
Key(String),
3940
}
40-
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
41+
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Encode, Decode)]
4142
pub enum DevupModelColumnIndex {
4243
True,
4344
Key(String),
4445
}
45-
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
46+
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Encode, Decode)]
4647
pub enum DevupModelColumnDefault {
4748
Default(String),
4849
ServerDefault(String),
4950
Func(String),
5051
}
5152

52-
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
53+
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Encode, Decode)]
5354
pub enum DevupModelColumnDtoOptionType {
5455
All,
5556
Each(Vec<DtoType>),
5657
}
5758

58-
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
59+
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Encode, Decode)]
5960
pub struct DevupModelColumnDtoOption {
6061
pub pick: Option<DevupModelColumnDtoOptionType>,
6162
pub omit: Option<DevupModelColumnDtoOptionType>,
6263
}
6364

64-
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, Eq)]
65+
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, Eq, Encode, Decode)]
6566
pub struct DevupModelColumn {
6667
pub name: String,
6768
pub r#type: DevupModelColumnType,
@@ -79,14 +80,14 @@ pub struct DevupModelColumn {
7980
pub dto: Option<DevupModelColumnDtoOption>,
8081
}
8182

82-
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
83+
#[derive(Debug, Serialize, Deserialize, Clone, Default, Encode, Decode)]
8384
pub struct DevupModelRelation {
8485
pub name: String,
8586
pub field: Option<String>,
8687
pub dto: Option<DevupModelColumnDtoOption>,
8788
}
8889

89-
#[derive(Debug, Serialize, Deserialize, Clone)]
90+
#[derive(Debug, Serialize, Deserialize, Clone, Encode, Decode)]
9091
pub enum DevupModelFieldType {
9192
Column(DevupModelColumn),
9293
Relation(DevupModelRelation),

core/model/src/lib.rs

Lines changed: 56 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,30 +6,73 @@ use std::{
66
sync::{Arc, Mutex},
77
};
88

9+
use bincode::{Decode, Encode, config};
910
pub use column::DevupModelFieldType;
11+
1012
use once_cell::sync::Lazy;
1113
use serde::{Deserialize, Serialize};
12-
13-
#[derive(Debug, Serialize, Deserialize, Clone)]
14+
use shared_memory::*;
15+
#[derive(Debug, Serialize, Deserialize, Clone, Encode, Decode)]
1416
pub struct DevupModel {
1517
pub name: String,
1618
pub fields: Vec<DevupModelFieldType>,
1719
}
20+
// current timestamp
21+
static INIT: Lazy<Mutex<bool>> = Lazy::new(|| Mutex::new(false));
22+
23+
fn get_shmem_ptr() -> Result<Shmem, ShmemError> {
24+
let shmem = match ShmemConf::new()
25+
.size(4096)
26+
.os_id("devup_model_map")
27+
.create()
28+
{
29+
Ok(m) => m,
30+
Err(ShmemError::MappingIdExists | ShmemError::LinkExists) => {
31+
ShmemConf::new().os_id("devup_model_map").open().unwrap()
32+
}
33+
Err(e) => {
34+
eprintln!("Unable to create or open shmem file devup_model_map : {e}");
35+
return Err(e);
36+
}
37+
};
38+
Ok(shmem)
39+
}
40+
pub fn add_model(model: DevupModel) -> Result<(), Box<dyn std::error::Error>> {
41+
let mut shmem = get_shmem_ptr()?;
1842

19-
static MODEL_MAP: Lazy<Mutex<HashMap<String, Arc<DevupModel>>>> =
20-
Lazy::new(|| Mutex::new(HashMap::new()));
43+
let mut init = INIT.lock().unwrap();
2144

22-
pub fn add_model(model: DevupModel) {
23-
MODEL_MAP
24-
.lock()
25-
.unwrap()
26-
.insert(model.name.clone(), Arc::new(model));
45+
if !*init {
46+
*init = true;
47+
unsafe {
48+
shmem.as_slice_mut()[0..4096].fill(0);
49+
}
50+
}
51+
52+
let mut data: (HashMap<String, Arc<DevupModel>>, usize) =
53+
bincode::decode_from_slice(unsafe { shmem.as_slice() }, config::standard())?;
54+
data.0.insert(model.name.clone(), Arc::new(model));
55+
let serialized = bincode::encode_to_vec(&data, config::standard())?;
56+
unsafe {
57+
shmem.as_slice_mut()[0..serialized.len()].copy_from_slice(&serialized);
58+
};
59+
60+
Ok(())
2761
}
2862

29-
pub fn get_model(name: &str) -> Option<Arc<DevupModel>> {
30-
MODEL_MAP.lock().unwrap().get(name).cloned()
63+
pub fn get_model(name: &str) -> Result<Arc<DevupModel>, Box<dyn std::error::Error>> {
64+
let shmem = get_shmem_ptr()?;
65+
let data: (HashMap<String, Arc<DevupModel>>, usize) =
66+
bincode::decode_from_slice(unsafe { shmem.as_slice() }, config::standard())?;
67+
68+
let model = data.0.get(name).cloned().unwrap();
69+
70+
Ok(model)
3171
}
3272

33-
pub fn get_all_models() -> Vec<Arc<DevupModel>> {
34-
MODEL_MAP.lock().unwrap().values().cloned().collect()
73+
pub fn get_all_models() -> Result<Vec<Arc<DevupModel>>, Box<dyn std::error::Error>> {
74+
let shmem = get_shmem_ptr()?;
75+
let data: (HashMap<String, Arc<DevupModel>>, usize) =
76+
bincode::decode_from_slice(unsafe { shmem.as_slice() }, config::standard())?;
77+
Ok(data.0.values().cloned().collect())
3578
}

core/schema/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,4 @@ edition = "2024"
77
serde = { version = "1.0.219", features = ["derive"] }
88
serde_json = "1.0.140"
99
once_cell = "1.21.3"
10+
bincode = "2.0.1"

core/schema/src/field.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1+
use bincode::{Decode, Encode};
12
use serde::{Deserialize, Serialize};
23
use std::collections::HashMap;
34

4-
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
5+
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Encode, Decode)]
56
pub enum DevupSchemaField {
67
String,
78
Int,

0 commit comments

Comments
 (0)