SQLite की परफ़ॉर्मेंस (व्यू) के लिए सबसे सही तरीके

कॉन्सेप्ट और Jetpack Compose को लागू करना

Android में SQLite के लिए पहले से मौजूद सहायता मिलती है. यह एक असरदार एसक्यूएल डेटाबेस है. अपने ऐप्लिकेशन की परफ़ॉर्मेंस को ऑप्टिमाइज़ करने के लिए, इन सबसे सही तरीकों को अपनाएं. इससे यह पक्का किया जा सकेगा कि डेटा बढ़ने पर भी आपका ऐप्लिकेशन तेज़ी से काम करे. इन सबसे सही तरीकों को अपनाकर, परफ़ॉर्मेंस की समस्याओं का सामना करने की संभावना भी कम हो जाती है जिन्हें फिर से पैदा करना और समस्या का हल करना मुश्किल होता है.

बेहतर परफ़ॉर्मेंस पाने के लिए, परफ़ॉर्मेंस से जुड़े इन सिद्धांतों का पालन करें:

  • कम पंक्तियां और कॉलम पढ़ें: अपनी क्वेरी को ऑप्टिमाइज़ करें, ताकि सिर्फ़ ज़रूरी डेटा ही वापस लाया जा सके. डेटाबेस से कम से कम डेटा पढ़ें, क्योंकि ज़्यादा डेटा वापस पाने से परफ़ॉर्मेंस पर असर पड़ सकता है.

  • SQLite इंजन पर काम को पुश करना: एसक्यूएल क्वेरी में कंप्यूटेशन, फ़िल्टरिंग, और क्रम से लगाने की कार्रवाइयां करें. SQLite के क्वेरी इंजन का इस्तेमाल करने से, परफ़ॉर्मेंस को काफ़ी बेहतर बनाया जा सकता है.

  • डेटाबेस स्कीमा में बदलाव करना: अपने डेटाबेस स्कीमा को इस तरह डिज़ाइन करें कि SQLite, क्वेरी प्लान और डेटा को बेहतर तरीके से दिखा सके. टेबल को सही तरीके से इंडेक्स करें और टेबल के स्ट्रक्चर को ऑप्टिमाइज़ करें, ताकि परफ़ॉर्मेंस को बेहतर बनाया जा सके.

इसके अलावा, समस्या हल करने के लिए उपलब्ध टूल का इस्तेमाल करके, अपने SQLite डेटाबेस की परफ़ॉर्मेंस को मेज़र किया जा सकता है. इससे उन हिस्सों की पहचान करने में मदद मिलती है जिन्हें ऑप्टिमाइज़ करने की ज़रूरत है.

हमारा सुझाव है कि आप Jetpack Room लाइब्रेरी का इस्तेमाल करें.

परफ़ॉर्मेंस के लिए डेटाबेस को कॉन्फ़िगर करना

SQLite में अपने डेटाबेस को बेहतर परफ़ॉर्मेंस के लिए कॉन्फ़िगर करने के लिए, इस सेक्शन में दिया गया तरीका अपनाएं.

सिंक करने के मोड को आसान बनाना

SQLite में सिंक्रोनस मोड को कंट्रोल करने का विकल्प होता है. FULL मोड में, हर कमिट एक fsync जारी करता है, ताकि यह पक्का किया जा सके कि डेटा डिस्क तक पहुंच जाए. इससे डेटा की ड्यूरेबिलिटी बेहतर होती है, लेकिन कमिट की प्रोसेस धीमी हो जाती है. WAL के साथ, NORMAL मोड हर कमिट पर सिंक नहीं होता. इसके बावजूद, यह डेटाबेस को खराब होने से बचाता है.

फ़्रेमवर्क की मदद से WAL को चालू करने पर, Android डिवाइस के डिफ़ॉल्ट WAL सिंक्रोनस मोड को लागू करता है. यह Android 9 और इसके बाद के वर्शन के लिए, एओएसपी में NORMAL होता है. डिवाइस बनाने वाली कंपनियां, इस डिफ़ॉल्ट सेटिंग को बदल सकती हैं. साथ ही, WAL का इस्तेमाल न करने वाले डेटाबेस, डिफ़ॉल्ट रूप से FULL पर सेट होते हैं. यह पक्का करने के लिए कि आपका डेटाबेस NORMAL का इस्तेमाल करता है, डेटाबेस खोलते समय इसे सेट करें:

Kotlin

// When opening the database
val params = SQLiteDatabase.OpenParams.Builder()
    .addOpenFlags(SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING)
    // SYNC_MODE_NORMAL is available in API level 33 and higher.
    // On API levels 28 to 32, pass "NORMAL" instead.
    .setSynchronousMode(SQLiteDatabase.SYNC_MODE_NORMAL)
    .build()
// With SQLiteOpenHelper, call setOpenParams(params) in your constructor.

// Or: after having opened the database
db.execSQL("PRAGMA synchronous = NORMAL")

Java

// When opening the database
SQLiteDatabase.OpenParams params = new SQLiteDatabase.OpenParams.Builder()
    .addOpenFlags(SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING)
    // SYNC_MODE_NORMAL is available in API level 33 and higher.
    // On API levels 28 to 32, pass "NORMAL" instead.
    .setSynchronousMode(SQLiteDatabase.SYNC_MODE_NORMAL)
    .build();
// With SQLiteOpenHelper, call setOpenParams(params) in your constructor.

// Or: after having opened the database
db.execSQL("PRAGMA synchronous = NORMAL");

इस सेटिंग में, डिस्क में डेटा सेव होने से पहले कमिट वापस आ सकता है. अगर डिवाइस बंद हो जाता है, जैसे कि पावर बंद होने या कर्नेल पैनिक की वजह से, तो कमिट किया गया डेटा मिट सकता है. हालांकि, लॉगिंग की वजह से आपका डेटाबेस खराब नहीं होता.

अगर सिर्फ़ आपका ऐप्लिकेशन क्रैश होता है, तो भी आपका डेटा डिस्क में सेव हो जाता है. ज़्यादातर ऐप्लिकेशन के लिए, इस सेटिंग से परफ़ॉर्मेंस में सुधार होता है. इसके लिए, कोई शुल्क नहीं देना पड़ता.

क्वेरी की परफ़ॉर्मेंस को बेहतर बनाना

SQLite में क्वेरी की परफ़ॉर्मेंस को बेहतर बनाने के लिए, यहां दिए गए सबसे सही तरीके अपनाएं. इनसे, जवाब देने में लगने वाले समय को कम किया जा सकता है और प्रोसेसिंग की क्षमता को बढ़ाया जा सकता है.

सिर्फ़ अपनी ज़रूरत की लाइनें पढ़ना

फ़िल्टर की मदद से, नतीजों को तारीख की सीमा, जगह या नाम जैसी कुछ शर्तों के हिसाब से सीमित किया जा सकता है. सीमाओं की मदद से, आपको दिखने वाले नतीजों की संख्या को कंट्रोल किया जा सकता है:

Kotlin

db.rawQuery("""
    SELECT name
    FROM Customers
    LIMIT 10;
    """.trimIndent(),
    null
).use { cursor ->
    while (cursor.moveToNext()) {
        // Process cursor data
    }
}

Java

try (Cursor cursor = db.rawQuery("""
    SELECT name
    FROM Customers
    LIMIT 10;
    """, null)) {
  while (cursor.moveToNext()) {
    // Process cursor data
  }
}

सिर्फ़ अपनी ज़रूरत के कॉलम पढ़ें

ऐसे कॉलम चुनने से बचें जिनकी ज़रूरत नहीं है. इससे आपकी क्वेरी की रफ़्तार धीमी हो सकती है और संसाधनों की बर्बादी हो सकती है. इसके बजाय, सिर्फ़ उन कॉलम को चुनें जिनका इस्तेमाल किया जाता है.

यहां दिए गए उदाहरण में, id, name, और phone को चुना गया है:

Kotlin

// This is not the most efficient way of doing this.
// See the following example for a better approach.

db.rawQuery(
    """
    SELECT id, name, phone
    FROM customers;
    """.trimIndent(),
    null
).use { cursor ->
    while (cursor.moveToNext()) {
        val name = cursor.getString(1)
        // Further processing
    }
}

Java

// This is not the most efficient way of doing this.
// See the following example for a better approach.

try (Cursor cursor = db.rawQuery("""
    SELECT id, name, phone
    FROM customers;
    """, null)) {
  while (cursor.moveToNext()) {
    String name = cursor.getString(1);
    // Further processing
  }
}

हालांकि, आपको सिर्फ़ name कॉलम की ज़रूरत होगी:

Kotlin

db.rawQuery("""
    SELECT name
    FROM Customers;
    """.trimIndent(),
    null
).use { cursor ->
    while (cursor.moveToNext()) {
        val name = cursor.getString(0)
        // Further processing
    }
}

Java

try (Cursor cursor = db.rawQuery("""
    SELECT name
    FROM Customers;
    """, null)) {
  while (cursor.moveToNext()) {
    String name = cursor.getString(0);
    // Further processing
  }
}

क्वेरी को पैरामीटर के हिसाब से बनाना

आपकी क्वेरी स्ट्रिंग में ऐसा पैरामीटर शामिल हो सकता है जो सिर्फ़ रनटाइम के दौरान पता चलता है. जैसे:

Kotlin

fun getNameById(id: Long): String? {
    db.rawQuery(
        "SELECT name FROM customers WHERE id=$id", null
    ).use { cursor ->
        return if (cursor.moveToFirst()) {
            cursor.getString(0)
        } else {
            null
        }
    }
}

Java

@Nullable
public String getNameById(long id) {
  try (Cursor cursor = db.rawQuery(
      "SELECT name FROM customers WHERE id=" + id, null)) {
    if (cursor.moveToFirst()) {
      return cursor.getString(0);
    } else {
      return null;
    }
  }
}

ऊपर दिए गए कोड में, हर क्वेरी एक अलग स्ट्रिंग बनाती है. इसलिए, इसे स्टेटमेंट कैश मेमोरी से फ़ायदा नहीं मिलता. हर कॉल को SQLite की ज़रूरत होती है, ताकि उसे कंपाइल किया जा सके. इसके बाद ही, उसे एक्ज़ीक्यूट किया जा सकता है. इसके बजाय, id आर्ग्युमेंट को पैरामीटर से बदला जा सकता है और वैल्यू को selectionArgs से बाइंड किया जा सकता है:

Kotlin

fun getNameById(id: Long): String? {
    db.rawQuery(
        """
          SELECT name
          FROM customers
          WHERE id=?
        """.trimIndent(), arrayOf(id.toString())
    ).use { cursor ->
        return if (cursor.moveToFirst()) {
            cursor.getString(0)
        } else {
            null
        }
    }
}

Java

@Nullable
public String getNameById(long id) {
  try (Cursor cursor = db.rawQuery("""
          SELECT name
          FROM customers
          WHERE id=?
      """, new String[] {String.valueOf(id)})) {
    if (cursor.moveToFirst()) {
      return cursor.getString(0);
    } else {
      return null;
    }
  }
}

अब क्वेरी को एक बार कंपाइल करके कैश मेमोरी में सेव किया जा सकता है. कंपाइल की गई क्वेरी को getNameById(long) के अलग-अलग इन्वोकेशन के बीच फिर से इस्तेमाल किया जाता है.

यूनीक वैल्यू के लिए DISTINCT का इस्तेमाल करना

DISTINCT कीवर्ड का इस्तेमाल करके, क्वेरी की परफ़ॉर्मेंस को बेहतर बनाया जा सकता है. इसके लिए, प्रोसेस किए जाने वाले डेटा की मात्रा को कम करना होगा. उदाहरण के लिए, अगर आपको किसी कॉलम से सिर्फ़ यूनीक वैल्यू चाहिए, तो DISTINCT का इस्तेमाल करें:

Kotlin

db.rawQuery("""
    SELECT DISTINCT name
    FROM Customers;
    """.trimIndent(),
    null
).use { cursor ->
    while (cursor.moveToNext()) {
        // Only iterate over distinct names in Kotlin
        // Process distinct name
    }
}

Java

try (Cursor cursor = db.rawQuery("""
    SELECT DISTINCT name
    FROM Customers;
    """, null)) {
  while (cursor.moveToNext()) {
    // Only iterate over distinct names in Java
    // Process distinct name
  }
}

जब भी संभव हो, एग्रीगेट फ़ंक्शन का इस्तेमाल करें

बिना लाइन डेटा के एग्रीगेट किए गए नतीजे पाने के लिए, एग्रीगेट फ़ंक्शन का इस्तेमाल करें. उदाहरण के लिए, यहां दिया गया कोड यह जांच करता है कि मैच होने वाली कम से कम एक लाइन मौजूद है या नहीं:

Kotlin

// This is not the most efficient way of doing this.
// See the following example for a better approach.

db.rawQuery("""
    SELECT id, name
    FROM Customers
    WHERE city = 'Paris';
    """.trimIndent(),
    null
).use { cursor ->
    if (cursor.moveToFirst()) {
        // At least one customer from Paris
        // Handle found
    } else {
        // No customers from Paris
        // Handle not found
}

Java

// This is not the most efficient way of doing this.
// See the following example for a better approach.

try (Cursor cursor = db.rawQuery("""
    SELECT id, name
    FROM Customers
    WHERE city = 'Paris';
    """, null)) {
  if (cursor.moveToFirst()) {
    // At least one customer from Paris
    // Handle found
  } else {
    // No customers from Paris
    // Handle not found
  }
}

सिर्फ़ पहली लाइन फ़ेच करने के लिए, EXISTS() का इस्तेमाल किया जा सकता है. इससे, मैच होने वाली लाइन मौजूद न होने पर 0 और एक या उससे ज़्यादा लाइनें मैच होने पर 1 दिखेगा:

Kotlin

db.rawQuery("""
    SELECT EXISTS (
        SELECT null
        FROM Customers
        WHERE city = 'Paris';
    );
    """.trimIndent(),
    null
).use { cursor ->
    if (cursor.moveToFirst() && cursor.getInt(0) == 1) {
        // At least one customer from Paris
        // Handle found
    } else {
        // No customers from Paris
        // Handle not found
    }
}

Java

try (Cursor cursor = db.rawQuery("""
    SELECT EXISTS (
      SELECT null
      FROM Customers
      WHERE city = 'Paris'
    );
    """, null)) {
  if (cursor.moveToFirst() && cursor.getInt(0) == 1) {
    // At least one customer from Paris
    // Handle found
  } else {
    // No customers from Paris
    // Handle not found
  }
}

अपने ऐप्लिकेशन में SQLite एग्रीगेट फ़ंक्शन का इस्तेमाल करना

  • COUNT: इससे किसी कॉलम में मौजूद पंक्तियों की संख्या का पता चलता है.
  • SUM: किसी कॉलम में मौजूद सभी अंकों वाली वैल्यू को जोड़ता है.
  • MIN या MAX: इससे सबसे कम या सबसे ज़्यादा वैल्यू तय होती है. यह न्यूमेरिक कॉलम, DATE टाइप, और टेक्स्ट टाइप के लिए काम करता है.
  • AVG: इससे औसत संख्यात्मक वैल्यू का पता चलता है.
  • GROUP_CONCAT: यह फ़ंक्शन, स्ट्रिंग को जोड़ने के लिए इस्तेमाल किया जाता है. इसके लिए, सेपरेटर का इस्तेमाल किया जा सकता है.

Cursor.getCount() के बजाय COUNT() का इस्तेमाल करें

इस उदाहरण में, Cursor.getCount() फ़ंक्शन, डेटाबेस की सभी लाइनें पढ़ता है और उनकी वैल्यू दिखाता है:

Kotlin

// This is not the most efficient way of doing this.
// See the following example for a better approach.

db.rawQuery("""
    SELECT id
    FROM Customers;
    """.trimIndent(),
    null
).use { cursor ->
    val count = cursor.getCount()
    // Use count
}

Java

// This is not the most efficient way of doing this.
// See the following example for a better approach.

try (Cursor cursor = db.rawQuery("""
    SELECT id
    FROM Customers;
    """, null)) {
  int count = cursor.getCount();
  // Use count
}

हालांकि, COUNT() का इस्तेमाल करने पर, डेटाबेस सिर्फ़ संख्या दिखाता है:

Kotlin

db.rawQuery("""
    SELECT COUNT(*)
    FROM Customers;
    """.trimIndent(),
    null
).use { cursor ->
    cursor.moveToFirst()
    val count = cursor.getInt(0)
    // Use count
}

Java

try (Cursor cursor = db.rawQuery("""
    SELECT COUNT(*)
    FROM Customers;
    """, null)) {
  cursor.moveToFirst();
  int count = cursor.getInt(0);
  // Use count
}

कोड के बजाय क्वेरी को नेस्ट करना

एसक्यूएल को कंपोज़ किया जा सकता है. साथ ही, यह सबक्वेरी, जॉइन, और फ़ॉरेन की की शर्तों के साथ काम करता है. ऐप्लिकेशन कोड का इस्तेमाल किए बिना, एक क्वेरी के नतीजे को दूसरी क्वेरी में इस्तेमाल किया जा सकता है. इससे SQLite से डेटा कॉपी करने की ज़रूरत कम हो जाती है. साथ ही, डेटाबेस इंजन आपकी क्वेरी को ऑप्टिमाइज़ कर पाता है.

यहां दिए गए उदाहरण में, क्वेरी चलाकर यह पता लगाया जा सकता है कि किस शहर में सबसे ज़्यादा ग्राहक हैं. इसके बाद, उस शहर के सभी ग्राहकों को ढूंढने के लिए, नतीजे का इस्तेमाल दूसरी क्वेरी में किया जा सकता है:

Kotlin

// This is not the most efficient way of doing this.
// See the following example for a better approach.

db.rawQuery("""
    SELECT city
    FROM Customers
    GROUP BY city
    ORDER BY COUNT(*) DESC
    LIMIT 1;
    """.trimIndent(),
    null
).use { cursor ->
    if (cursor.moveToFirst()) {
        val topCity = cursor.getString(0)
        db.rawQuery("""
            SELECT name, city
            FROM Customers
            WHERE city = ?;
        """.trimIndent(),
        arrayOf(topCity)).use { innerCursor ->
            while (innerCursor.moveToNext()) {
                // Process inner cursor data
            }
        }
    }
}

Java

// This is not the most efficient way of doing this.
// See the following example for a better approach.

try (Cursor cursor = db.rawQuery("""
    SELECT city
    FROM Customers
    GROUP BY city
    ORDER BY COUNT(*) DESC
    LIMIT 1;
    """, null)) {
  if (cursor.moveToFirst()) {
    String topCity = cursor.getString(0);
    try (Cursor innerCursor = db.rawQuery("""
        SELECT name, city
        FROM Customers
        WHERE city = ?;
        """, new String[] {topCity})) {
        while (innerCursor.moveToNext()) {
          // Process inner cursor data
        }
    }
  }
}

पिछले उदाहरण के मुकाबले आधे समय में नतीजा पाने के लिए, नेस्ट किए गए स्टेटमेंट वाली एक SQL क्वेरी का इस्तेमाल करें:

Kotlin

db.rawQuery("""
    SELECT name, city
    FROM Customers
    WHERE city IN (
        SELECT city
        FROM Customers
        GROUP BY city
        ORDER BY COUNT (*) DESC
        LIMIT 1;
    );
    """.trimIndent(),
    null
).use { cursor ->
    if (cursor.moveToNext()) {
        // Process cursor data
    }
}

Java

try (Cursor cursor = db.rawQuery("""
    SELECT name, city
    FROM Customers
    WHERE city IN (
      SELECT city
      FROM Customers
      GROUP BY city
      ORDER BY COUNT(*) DESC
      LIMIT 1
    );
    """, null)) {
  while(cursor.moveToNext()) {
    // Process cursor data
  }
}

एसक्यूएल में यूनीक वैल्यू की जांच करना

अगर किसी पंक्ति को तब तक शामिल नहीं किया जाना चाहिए, जब तक कि टेबल में किसी खास कॉलम की वैल्यू यूनीक न हो, तो उस यूनीक वैल्यू को कॉलम की शर्त के तौर पर लागू करना ज़्यादा असरदार हो सकता है.

यहां दिए गए उदाहरण में, इंसर्ट की जाने वाली लाइन की पुष्टि करने के लिए एक क्वेरी चलाई गई है. साथ ही, असल में इंसर्ट करने के लिए दूसरी क्वेरी चलाई गई है:

Kotlin

// This is not the most efficient way of doing this.
// See the following example for a better approach.

db.rawQuery(
    """
    SELECT EXISTS (
        SELECT null
        FROM customers
        WHERE username = ?
    );
    """.trimIndent(),
    arrayOf(customer.username)
).use { cursor ->
    if (cursor.moveToFirst() && cursor.getInt(0) == 1) {
        throw AddCustomerException(customer)
    }
}
db.execSQL(
    "INSERT INTO customers VALUES (?, ?, ?)",
    arrayOf(
        customer.id.toString(),
        customer.name,
        customer.username
    )
)

Java

// This is not the most efficient way of doing this.
// See the following example for a better approach.

try (Cursor cursor = db.rawQuery("""
    SELECT EXISTS (
      SELECT null
      FROM customers
      WHERE username = ?
    );
    """, new String[] { customer.username })) {
  if (cursor.moveToFirst() && cursor.getInt(0) == 1) {
    throw new AddCustomerException(customer);
  }
}
db.execSQL(
    "INSERT INTO customers VALUES (?, ?, ?)",
    new String[] {
      String.valueOf(customer.id),
      customer.name,
      customer.username,
    });

Kotlin या Java में यूनीक कंस्ट्रेंट की जांच करने के बजाय, टेबल तय करते समय SQL में इसकी जांच की जा सकती है:

CREATE TABLE Customers(
  id INTEGER PRIMARY KEY,
  name TEXT,
  username TEXT UNIQUE
);

SQLite भी यही काम करता है:

CREATE TABLE Customers(...);
CREATE UNIQUE INDEX CustomersUsername ON Customers(username);

अब आपके पास एक लाइन डालने और SQLite को कंस्ट्रेंट की जांच करने की अनुमति देने का विकल्प है:

Kotlin

try {
    db.execSQL(
        "INSERT INTO Customers VALUES (?, ?, ?)",
        arrayOf(customer.id.toString(), customer.name, customer.username)
    )
} catch(e: SQLiteConstraintException) {
    throw AddCustomerException(customer, e)
}

Java

try {
  db.execSQL(
      "INSERT INTO Customers VALUES (?, ?, ?)",
      new String[] {
        String.valueOf(customer.id),
        customer.name,
        customer.username,
      });
} catch (SQLiteConstraintException e) {
  throw new AddCustomerException(customer, e);
}

SQLite में, एक से ज़्यादा कॉलम वाले यूनीक इंडेक्स इस्तेमाल किए जा सकते हैं:

CREATE TABLE table(...);
CREATE UNIQUE INDEX unique_table ON table(column1, column2, ...);

SQLite, Kotlin या Java कोड की तुलना में, कंस्ट्रेंट की पुष्टि तेज़ी से और कम ओवरहेड के साथ करता है. ऐप्लिकेशन कोड के बजाय SQLite का इस्तेमाल करना सबसे सही तरीका है.

एक ही लेन-देन में कई इंसर्शन को बैच करना

एक लेन-देन में कई कार्रवाइयां की जाती हैं. इससे न सिर्फ़ काम करने की क्षमता बेहतर होती है, बल्कि सही तरीके से काम करने में भी मदद मिलती है. डेटा की एकरूपता को बेहतर बनाने और परफ़ॉर्मेंस को तेज़ करने के लिए, इंसर्शन को बैच में किया जा सकता है:

Kotlin

db.beginTransaction()
try {
    customers.forEach { customer ->
        db.execSQL(
            "INSERT INTO Customers VALUES (?, ?, ?)",
            arrayOf(customer.id.toString(), customer.name, "customerValue")
        )
    }
    db.setTransactionSuccessful()
} finally {
    db.endTransaction()
}

Java

db.beginTransaction();
try {
  for (Customer customer : customers) {
    db.execSQL(
        "INSERT INTO Customers VALUES (?, ?, ?)",
        new String[] {
          String.valueOf(customer.id),
          customer.name,
          "customerValue"
        });
  }
  db.setTransactionSuccessful();
} finally {
  db.endTransaction();
}