أداة Sumor Cloud.
مزيد من التوثيق
موصل قاعدة بيانات لـ MySQL وما إلى ذلك. بناءً على entity.
npm i @sumor/database --save
يتطلب إصدار Node.JS 18.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: {}
})
// الحصول على العميل مع حزمة الاتصال
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 لإنشاء انضمام في الجدول. مثل المثال أدناه، سيتم إنشاء حقل 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: {}
})