أداة Sumor Cloud.
المزيد من الوثائق
موصل قاعدة بيانات لـ MySQL، إلخ. يعتمد على entity.
npm i @sumor/database --save
يتطلب إصدار Node.JS 16.x أو أعلى
نظرًا لأن هذه الحزمة مكتوبة بتنسيق ES module،
يرجى تغيير الكود التالي في ملف 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: {}
})
// الحصول على عميل مع حوض اتصال
const client = await database.client(config)
// الاتصال
const db = await client.connect()
// تعيين مستخدم العمل
db.setUser('tester')
// إنشاء سجل
const car1Id = await db.insert('Car', {
brand: 'BMW',
model: 'X5'
})
const car2Id = await db.insert('Car', {
brand: 'BMW',
model: 'X6'
})
// قراءة السجل
const car = await db.single('Car', { id: carId })
// car = {id: car1Id, brand: 'BMW', model: 'X5'}
// استعلام السجلات
const cars = await db.query('Car', {
brand: 'BMW'
})
// cars = [{id: car1Id, brand: 'BMW', model: 'X5'}, {id: car2Id, brand: 'BMW', model: 'X6'}]
// عد السجلات
const count = await db.count('Car', {
brand: 'BMW'
})
// count = 2
// تحديث السجل
await db.update(
'Car',
{ id: car1Id },
{
brand: 'BMW',
model: 'X5M'
}
)
// ضمان السجل
await db.ensure('Car', ['brand'], {
brand: 'BMW',
model: 'X5C'
})
// لن يُضاف السجل إذا كانت العلامة التجارية 'BMW' موجودة بالفعل
// تعديل السجل
await db.modify('Car', ['brand'], {
brand: 'BMW',
model: 'X5C'
})
// سيقوم بتحديث نموذج السجل إذا كانت العلامة التجارية 'BMW' موجودة بالفعل
// حذف السجل
await db.delete('Car', { id: car1Id })
// إغلاق الاتصال
await db.commit()
// إلغاء الرجوع
await db.rollback()
// إغلاق الاتصال
await db.release()
// تدمير العميل عندما يجب إيقاف الخادم
await client.destroy()
// استعلام السجلات مع خيارات
const cars = await db.select(
'Car',
{
brand: 'BMW'
},
{
term: 'X5',
termRange: ['model'],
top: 10,
skip: 0
}
)
يمكنك إضافة مصفوفة index إلى تعريف entity لإنشاء فهرس على الجدول،
افتراضيًا، سيتم إنشاء الفهرس على حقل id.
يمكنك إضافة كائن join إلى تعريف entity لإنشاء عملية join على الجدول.
مثل المثال أدناه، سيتم إنشاء حقل 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: {}
})