أداة 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
}
)
يمكنك إضافة مصفوفة فهرس لتعريف 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: {}
})