أداة Sumor Cloud.
المزيد من الوثائق
موصل قاعدة بيانات لـ MySQL، إلخ. يعتمد على entity.
npm i @sumor/database --save
تتطلب إصدار Node.JS 16.x أو أعلى
نظرًا لأن هذه الحزمة مكتوبة بوحدة ES،
يرجى تغيير الكود التالي في ملف package.json:
{
"type": "module"
}
import database from '@sumor/database'
const config = {
host: 'localhost',
user: 'root',
password: 'password',
database: 'database',
port: 3306
}
await database.install(config, {
entity: {
Car: {
property: {
brand: {
type: 'string',
length: 100
},
model: {
type: 'string',
length: 100
}
}
}
},
view: {}
})
// get client with connection pool
const client = await database.client(config)
// get connection
const db = await client.connect()
// set operate user
db.setUser('tester')
// create record
const car1Id = await db.insert('Car', {
brand: 'BMW',
model: 'X5'
})
const car2Id = await db.insert('Car', {
brand: 'BMW',
model: 'X6'
})
// read record
const car = await db.single('Car', { id: carId })
// car = {id: car1Id, brand: 'BMW', model: 'X5'}
// query records
const cars = await db.query('Car', {
brand: 'BMW'
})
// cars = [{id: car1Id, brand: 'BMW', model: 'X5'}, {id: car2Id, brand: 'BMW', model: 'X6'}]
// count records
const count = await db.count('Car', {
brand: 'BMW'
})
// count = 2
// update record
await db.update(
'Car',
{ id: car1Id },
{
brand: 'BMW',
model: 'X5M'
}
)
// ensure record
await db.ensure('Car', ['brand'], {
brand: 'BMW',
model: 'X5C'
})
// لن يقوم بإدراج السجل إذا كان brand 'BMW' موجودًا بالفعل
// modify record
await db.modify('Car', ['brand'], {
brand: 'BMW',
model: 'X5C'
})
// سيقوم بتحديث نموذج السجل إذا كان brand 'BMW' موجودًا بالفعل
// delete record
await db.delete('Car', { id: car1Id })
// close connection
await db.commit()
// rollback
await db.rollback()
// close connection
await db.release()
// destroy client when server should be shutdown
await client.destroy()
// query records with options
const cars = await db.select(
'Car',
{
brand: 'BMW'
},
{
term: 'X5',
termRange: ['model'],
top: 10,
skip: 0
}
)
يمكنك إضافة مصفوفة index إلى تعريف entity لإنشاء فهرس على الجدول، بشكل افتراضي سيتم إنشاء الفهرس على الحقل id.
يمكنك إضافة كائن join إلى تعريف entity لإنشاء انضمام على الجدول. كما في المثال التالي، سيتم إنشاء حقل userId في entity Car.
import database from '@sumor/database'
const config = {
host: 'localhost',
user: 'root',
password: 'password',
database: 'database',
port: 3306
}
await database.install(config, {
entity: {
Car: {
property: {
brand: {
type: 'string',
length: 100
},
model: {
type: 'string',
length: 100
}
},
index: ['userId'],
join: {
user: 'User'
}
}
},
view: {}
})