반응형
해당 글은 Expo-cli 프로젝트(React-native) 내에 데이터베이스로 사용되는 Sqlite에 대한 이해를 하고 환경설정을 위한 연결하기 위한 expo-sqlite 라이브러리를 적용하는 가이드입니다.
💡 필자는 해당 개발환경을 아래와 같이 구성하였습니다.
{
"dependencies": {
"react-native": "0.64.3",
"expo": "^44.0.6",
"expo-sqlite": "~10.1.0",
"react": "17.0.1"
},
"devDependencies": {
"typescript": "~4.3.5"
}
}
1) expo-sqlite 설명
1. expo-sqlite 정의
💡 SQLite는 설치나 설정이 필요하지 않은 내장형 파일 기반의 관계형 데이터베이스(RDBMS)입니다. 외부에 데이터베이스를 두지 않고 모든 휴대폰 및 대부분의 컴퓨터에 내장되어 있어서 로컬/클라이언트 저장소를 위한 임베디드 DB입니다. 결론적으로 위 정의를 기반으로 expo-sqlite는 expo에서 Sqlite를 사용하기 편하게 제공해주는 라이브러리입니다.
- 해당 데이터베이스는 앱을 다시 시작해도 값이 유지가 됩니다.
- IoT 및 임베디드 장치에 적합한 데이터베이스입니다.
2. expo-sqlite 데이터 자료형
데이터 자료형 | 설명 | 예 |
NULL | 값이 정의되지 않거나 존재하지 않는 값을 저장합니다. | NULL |
INTEGER | 양수(+), 음수(-)와 같이 부호를 가지는 '정수 값'으로 저장이 되며 1, 2, 4, 6, 8 바이트와 같은 가변의 크기를 가질 수 있다. | -1234, 1234, 0 |
REAL | 양수(+), 음수(-)와 같이 부호를 가지는 '실수 값'으로 저장이 되며 실수 또는 8바이트 부동 소수점 숫자로 저장이 됩니다. | 0, 3.14, 3.22331, 1.0 |
TEXT | '문자 값'을 저장하는데 사용이 되며 기본적으로 ‘UTF-8’을 기준으로 저장이 되며, 해당 크기는 제한이 없으며 데이터베이스 인코딩을 사용하여 저장된 텍스트 문자열. UTF-8, UTF-16BE, UTF-16LE를 지원한다. | "문자열", "한" |
BLOB | 바이너리 타입의 파일을 저장한다. 이미지, 비디오, mp3멀티미디어 파일을 저장한다. | x'0101', x'0fac', x'0F0FAC', x'01234532' |
기타 데이터 자료형에 대한 저장 방법
- Boolean : 정수로 false(0), true(1)의 값으로 저장이 된다 (=INTEGER)
- Date, Time: 텍스트의 'YYYY-MM-DD hh:mm:ss'형태로 저장이 된다(=TEXT)
2) expo-sqlite 환경설정
1. expo-sqlite 라이브러리를 설치합니다.
💡 expo에서 sqlite를 사용할 수 있도록 하는 ‘expo-sqlite’ 라이브러리를 설치합니다.
# expo-sqlite install
$ expo install expo-sqlite
# yarn install
$ yarn add expo-sqlite
# or
# npm install
$ npm install expo-sqlite
[참고] Expo-SQLite
[참고] npm expo-sqlite
2. 데이터베이스 파일을 열 수 있도록 환경설정을 합니다.
💡 기존의 데이터베이스를 열 수 있도록 'db'파일에 대한 환경설정이 필요합니다.
expo 환경 파일 중 metro.config.ts파일에 ‘. db’ 파일을 열 수 있도록 환경설정을 해줍니다.
const { getDefaultConfig } = require('@expo/metro-config');
module.exports = (async () => {
const defaultConfig = await getDefaultConfig();
const { assetExts } = defaultConfig.resolver;
return {
resolver: {
// Add bin to assetExts
assetExts: [...assetExts, 'db'],
},
};
})();
3. SQLite 데이터베이스 연결을 합니다.
💡 [꿀팁] expo-sqlit는 'Web' 플랫폼을 제외하고 모두 연결이 가능합니다.
[출처] expo-sqlite 공식 사이트(https://docs.expo.dev/versions/latest/sdk/sqlite/)
💡 디바이스에 저장할 데이터베이스로 설정을 합니다. 최종 디바이스에 저장될 환경설정이 완료되면 함수 내에서 연결된 db를 리턴하도록 구성하였습니다.
import * as SQLite from 'expo-sqlite';
import { Platform } from 'react-native';
const DATABASE_NAME: string = 'db.testDb'; // db.데이터베이스 명
let db: SQLite.WebSQLDatabase | null = null;
/**
* 최초 데이터 베이스에 연결한다.
* ㄴ 데이터베이스 연결을 위해서는 필수.
* @returns {SQLite.WebSQLDatabase} db
*/
export const initDatabaseConfig = (): any => {
// 웹 플랫폼은 지원하지 않음.
if (Platform.OS === "web") {
return {
transaction: () => {
return {
executeSql: () => { },
};
},
};
}
db = SQLite.openDatabase(DATABASE_NAME);
// [필수] 코드가 트랜잭션내에서 작동하지 않는 경우
db.exec([{ sql: 'PRAGMA foreign_keys = ON;', args: [] }], false, () => { });
return db;
}
4. 연결된 데이터베이스를 기반으로 테이블을 연결합니다.
💡 연결된 데이터베이스 및 스키마에 데이터베이스를 연결한다. 이전에 연결해둔 데이터베이스 정보를 리턴 받아서 테이블을 연결합니다.
import { initDatabaseConfig } from '../configs/SqliteConfig';
import { UserType, UserResolvers } from '../types/common/UserType';
const TABLE_USER = 'tb_user';
/**
* [init] 연결한 데이터 베이스 정보를 가져온다.
*/
const DBInstance = initDatabaseConfig();
5. 테이블을 생성합니다.
💡 디바이스 내에 테이블의 존재 여부에 따라서 테이블을 생성한다
/**
* [API] 유저 테이블 생성
* @returns
*/
const createUserInfo = async (): Promise<void> => {
const query: string =
`create table if not exists ${TABLE_USER}
(
userSq INTEGER PRIMARY KEY AUTOINCREMENT,
userId TEXT,
userName TEXT
)`;
return await new Promise((resolve, reject) => {
DBInstance.transaction(
(tx: any) => {
tx.executeSql(query);
},
() => {
reject('Fail to create a todo table');
},
() => {
resolve();
}
);
});
}
6. 구성한 함수를 호출합니다.
App.tsx 파일이 실행될 때, useEffect()를 통해서 해당 테이블을 호출합니다.
import { useEffect } from "react";
import { userResolvers } from "../../services/UserService";
const App: React.FC = () => {
useEffect(() => {
(async () => {
_initConnectSqlite(); // [API] 테이블 존재 체크 이후 테이블 생성
})();
}, []);
/**
* [API] 테이블 존재 체크 이후 테이블 생성
*/
const _initConnectSqlite = async () => {
// 테이블이 존재하지 않을 경우 USER 테이블 생성
await userResolvers.createUserInfo();
}
return(
<>
</>
)
}
export default App;
오늘의 결론
환경설정 이후 테이블을 생성하는 것까지 작업을 완료하였습니다.
다음 작성 글에서 SQL문을 사용하는 방법에 대해서 공부해 볼 예정입니다.
오늘도 감사합니다😀
반응형
'React & React Native > 라이브러리 활용' 카테고리의 다른 글
[RN] React Native 자이로센서를 활용한 자이로스코프, 디바이스 모션 이해하기: expo-sensors (0) | 2022.05.15 |
---|---|
[RN] React Native Tensorflow.js 메모리 관리 이해하기 (0) | 2022.04.10 |
[RN] React Native 앱 상태 관리 이해 및 구성 방법: AppState (0) | 2022.03.27 |
[RN] React Native Tensorflow의 blazeface 모델을 이용한 얼굴 감지 (6) | 2022.03.09 |
[React] React-konva 이해하기-1 (구조편) (1) | 2022.01.29 |