Ошибка primary key must be unique

This is my first attempt at implementing SQLite and I am running into a common error that I have not been able to resolve. The error is

03-12 15:37:20.432: E/SQLiteDatabase(1603): Error inserting Test=test string value Entry=entry string value _id=1
03-12 15:37:20.432: E/SQLiteDatabase(1603): android.database.sqlite.SQLiteConstraintException: PRIMARY KEY must be unique (code 19)

I have a high level understanding of what might be going on. The error is saying that my primary key—which is _id for me—should be unique for each entry. But as far as I know, I am only trying to add one element, and I believe I have set things up based on the tutorials I have followed. Please take a look at what I have, and let me know what I have done in error. Thanks in advance!

First, I try to save an entry with the below line. I set id as 1 and then try to save some test values in other columns

DatabaseManager.saveEntry(MainActivity.this, "1", "entry string value", "test string value");

DatabaseManager.java

public class DatabaseManager {

    public static void saveEntry(Context context, String id, String entry, String test) {

        try {
            ContentValues values = getContentValuesEntryTable(id, entry, test);
            ContentResolver resolver = context.getContentResolver();
            Cursor cursor = resolver.query(EntryTable.CONTENT_URI, null, null, null, null);
            if (cursor != null && cursor.getCount() > 0) {
                resolver.update(EntryTable.CONTENT_URI, values, null, null);
            } else {
                resolver.insert(EntryTable.CONTENT_URI, values);
            }
            cursor.close();
            resolver.insert(EntryTable.CONTENT_URI, values);
        } catch (Exception e) {
            Log.e("TEST", "error: " + e.toString());
            e.printStackTrace();
        }

    }

    public static Cursor getEntry(Context context, String entry) {
        Cursor cursor;
        String sorting = null;
        if (TextUtils.isEmpty(entry)) {
            cursor = context.getContentResolver().query(EntryTable.CONTENT_URI, null, null, null, sorting);
        } else {
            cursor = context.getContentResolver().query(EntryTable.CONTENT_URI, null, EntryTable.Cols.COLUMN_ENTRY + " ='" + entry + "'", null, sorting);
        }

        if (cursor != null) {
            cursor.moveToFirst();
        }
        return cursor;
    }

    public static Cursor getTest(Context context, String test) {
        Cursor cursor;
        String sorting = null;
        if (TextUtils.isEmpty(test)) {
            cursor = context.getContentResolver().query(EntryTable.CONTENT_URI, null, null, null, sorting);
        } else {
            cursor = context.getContentResolver().query(EntryTable.CONTENT_URI, null, EntryTable.Cols.COLUMN_TEST + " = '" + test + "'", null, sorting);
        }

        if (cursor != null) {
            cursor.moveToFirst();
        }
        return cursor;
    }

    private static ContentValues getContentValuesEntryTable(String id, String entry, String test) {
        ContentValues values = new ContentValues();
        values.put(EntryTable.Cols.COLUMN_ID, id);
        values.put(EntryTable.Cols.COLUMN_ENTRY, entry);
        values.put(EntryTable.Cols.COLUMN_TEST, test);
        return values;
    }
}

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String KEY_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS {0} ({1})";
    public static final String KEY_DROP_TABLE = "DROP TABLE IF EXISTS {0}";

    private static final int CURRENT_DB_VERSION = 1;
    private static final String DB_NAME = "qmun.db";

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, CURRENT_DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d("TEST", "DB Creation :: Going to create db ");
        createEntryTable(db);
    }

    private void createEntryTable(SQLiteDatabase db) {
        StringBuilder entryTableFields = new StringBuilder();
        entryTableFields.append(EntryTable.Cols.COLUMN_ID)
        .append(" INTEGER PRIMARY KEY AUTOINCREMENT, ")
        .append(EntryTable.Cols.COLUMN_ENTRY).append(" TEXT, ")
        .append(EntryTable.Cols.COLUMN_TEST).append(" TEXT");
        createTable(db, EntryTable.TABLE_NAME, entryTableFields.toString());
    }

    public void dropTable(SQLiteDatabase db, String name) {
        String query = MessageFormat.format(DatabaseHelper.KEY_DROP_TABLE, name);
        db.execSQL(query);
    }

    public void createTable(SQLiteDatabase db, String name, String fields) {
        String query = MessageFormat.format(DatabaseHelper.KEY_CREATE_TABLE, name, fields);
        db.execSQL(query);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        dropTable(db, EntryTable.TABLE_NAME);
        onCreate(db);
    }

}

DatabaseProvider.java

public class DatabaseProvider extends ContentProvider {

    private static final String UNKNOWN_URI = "unknown_uri";
    private DatabaseHelper dBHelper;

    @Override
    public boolean onCreate() {
        // TODO Auto-generated method stub
        Log.i("TEST", "creating db");
        dBHelper = new DatabaseHelper(getContext());
        dBHelper.getWritableDatabase();
        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        // TODO Auto-generated method stub
        SQLiteDatabase db = dBHelper.getReadableDatabase();
        final int token = ContentDescriptor.URI_MATCHER.match(uri);
        Cursor result = null;

        switch (token) {
        case EntryTable.PATH_TOKEN: {
            result = doQuery(db, uri, EntryTable.TABLE_NAME, projection, selection, selectionArgs,
                sortOrder);
            break;
        }
        default:
            break;
        }

        // db.close(); // added line, investigate if needed. Received lint about it
        return result;
    }

    private Cursor doQuery(SQLiteDatabase db, Uri uri, String tableName, String[] projection,
        String selection, String[] selectionArgs, String sortOrder) {

        SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
        builder.setTables(tableName);
        Cursor result = builder.query(db, projection, selection, selectionArgs, sortOrder, null, null);
        result.setNotificationUri(getContext().getContentResolver(), uri);
        return result;
    }

    @Override
    public String getType(Uri uri) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // TODO Auto-generated method stub
        SQLiteDatabase db = dBHelper.getWritableDatabase();
        int token = ContentDescriptor.URI_MATCHER.match(uri);
        Uri result = null;

        switch (token) {
        case EntryTable.PATH_TOKEN: {
            result = doInsert(db, EntryTable.TABLE_NAME, EntryTable.CONTENT_URI, uri, values);
            break;
        }
        default:
            break;
        }

        db.close(); // added line, investigate if needed. Received lint about it

        if (result == null) {
            throw new IllegalArgumentException(UNKNOWN_URI + uri);
        }

        return result;
    }

    @Override
    public int bulkInsert(Uri uri, ContentValues[] values) {
        String table = null;
        int token = ContentDescriptor.URI_MATCHER.match(uri);

        switch (token) {
        case EntryTable.PATH_TOKEN: {
            table = EntryTable.TABLE_NAME;
            break;
        }
        default:
            break;
        }

        SQLiteDatabase db = dBHelper.getWritableDatabase();
        db.beginTransaction();

        for (ContentValues cv : values) {
            db.insert(table, null, cv);
        }

        db.setTransactionSuccessful();
        db.endTransaction();
        db.close(); // added line, investigate if needed. Received lint about it

        return values.length;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // TODO Auto-generated method stub

        SQLiteDatabase db = dBHelper.getWritableDatabase();
        int token = ContentDescriptor.URI_MATCHER.match(uri);
        int result = 0;

        switch (token) {
        case EntryTable.PATH_TOKEN: {
            result = doDelete(db, uri, EntryTable.TABLE_NAME, selection, selectionArgs);
            break;
        }
        default:
            break;
        }

        db.close(); // added line, investigate if needed. Received lint about it
        return result;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        // TODO Auto-generated method stub
        SQLiteDatabase db = dBHelper.getWritableDatabase();
        int token = ContentDescriptor.URI_MATCHER.match(uri);
        int result = 0;

        switch (token) {
        case EntryTable.PATH_TOKEN: {
            result = doUpdate(db, uri, EntryTable.TABLE_NAME, selection, selectionArgs, values);
            break;
        }
        default:
            break;
        }

        db.close(); // added line, investigate if needed. Received lint about it
        return result;
    }

    private int doUpdate(SQLiteDatabase db, Uri uri, String tableName, String selection,
        String[] selectionArgs, ContentValues values) {
        int result = db.update(tableName, values, selection, selectionArgs);
        getContext().getContentResolver().notifyChange(uri, null);
        return result;
    }

    private int doDelete(SQLiteDatabase db, Uri uri, String tableName, String selection,
        String[] selectionArgs) {
        int result = db.delete(tableName, selection, selectionArgs);
        getContext().getContentResolver().notifyChange(uri, null);
        return result;
    }

    private Uri doInsert(SQLiteDatabase db, String tableName, Uri contentUri, Uri uri, ContentValues values) {
        long id = db.insert(tableName, null, values);
        Uri result = contentUri.buildUpon().appendPath(String.valueOf(id)).build();
        getContext().getContentResolver().notifyChange(uri, null);
        return result;
    }

}

DBHelper.java

public class DBHelper extends SQLiteOpenHelper {
    public static String TAG = DBHelper.class.getSimpleName();

    // Constants
    private static Context mContext;
    private SQLiteDatabase mDatabase;
    public static final String KEY_ID = "id";

    private static final String DATABASE_NAME = "abcmouse.db";
    private static final String DATABASE_PATH = "data/sqlite/abcmouse/";
    private static final String DATABASE_TABLE = "tbl_masteraccount";
    private static final int DATABASE_VERSION = 1;

    public DBHelper(Context context) {
        // TODO Auto-generated constructor stub
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        mContext = context;

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        System.out.println("Upgrading db version (v" + oldVersion +
            ") to (v" + newVersion + ")");
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
        onCreate(db);

    }

    /**
     * Method is used to create an empty database that will be created into the default system path
     * of the application. The former database will be overwritten
     *
     * @throws IOException
     */
    public void createDatabase() throws IOException {
        boolean dBExist = checkDatabase();
        if (!dBExist) {
            getReadableDatabase();
            try {
                copyDatabase();
            } catch (Exception e) {
                Log.e(TAG, "error creating db: " + e.toString());
                e.printStackTrace();
            }
        }
    }

    /**
     * Method is used to copy database from local assets folder to the created database in the
     * system folder. The copying is done via transferring bytestream
     *
     * @throws IOException
     */
    private void copyDatabase() throws IOException {
        // open local db as input stream
        InputStream is = mContext.getAssets().open(DATABASE_NAME);

        // path to the new created empty db
        String outFileName = DATABASE_PATH + DATABASE_NAME;

        // open the empty db as the output stream
        OutputStream os = new FileOutputStream(outFileName);

        // transfer bytes from the inputfile to the outputfile
        byte buffer[] = new byte[1024];

        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }

        // close streams
        os.flush();
        os.close();
        is.close();
    }

    /**
     * Method is used to check if the database already exists to avoid re-copying the file each time
     * you open the application
     *
     * @return true if it exists, otherwise false
     */
    private boolean checkDatabase() {
        SQLiteDatabase checkDb = null;
        try {
            String mPath = DATABASE_PATH + DATABASE_NAME;
            checkDb = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.OPEN_READONLY);
        } catch (Exception e) {
            Log.e(TAG, "error checking existing db: " + e.toString());
            e.printStackTrace();
        }

        if (checkDb != null) {
            checkDb.close();
        }
        return checkDb != null ? true : false;
    }

    /**
     * Method is used to add data to database
     *
     * @param table
     * @param key
     * @param value
     * @return
     */
    public long addData(String table, String[] key, String[] value) {
        mDatabase = getWritableDatabase();
        if (mDatabase.isOpen()) {
            ContentValues cv = new ContentValues();
            for (int i = 0; i < key.length; i++) {
                cv.put(key[i], value[i]);
            }
            return mDatabase.insert(table, null, cv);
        }
        return 0;
    }

    /**
     * Method is used to update data on database
     *
     * @param table
     * @param key
     * @param value
     * @param whereClause
     * @return
     */
    public long upgradeData(String table, String[] key, String[] value, String whereClause) {
        mDatabase = getWritableDatabase();
        if (mDatabase.isOpen()) {
            ContentValues cv = new ContentValues();
            for (int i = 0; i < key.length; i++) {
                cv.put(key[i], value[i]);
            }
            return mDatabase.update(table, cv, whereClause, null);
        }
        return 0;
    }

    /**
     * Method is used to retrieve stored data
     *
     * @param table
     * @param columns
     * @param selection
     * @param selectionArgs
     * @param groupBy
     * @param having
     * @param orderBy
     * @return
     */
    public Cursor getAllData(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) {
        Cursor cursor = null;
        if (mDatabase != null) {
            if (!mDatabase.isOpen()) {
                mDatabase = getWritableDatabase();
            }

            if (mDatabase.isOpen()) {
                cursor = mDatabase.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
            }
        }
        return cursor;
    }

    /**
     * Method is used to open the database
     *
     * @throws SQLException
     */
    public void openDatabase() throws SQLException {
        String mPath = DATABASE_PATH + DATABASE_NAME;
        mDatabase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.OPEN_READONLY);
    }

    public long deleteRecord(String table, String condition) {
        mDatabase = getWritableDatabase();
        if (mDatabase.isOpen()) {
            return mDatabase.delete(table, condition, null);
        }

        return 0;
    }

    @Override
    public void close() {
        if (mDatabase != null) {
            mDatabase.close();
        }
        super.close();
    }

}

In my manifest I have provider set

<provider
            android:name=".helper.DatabaseProvider"
            android:authorities="com.abcmouse"
            android:exported="true"
            android:grantUriPermissions="true"
            android:readPermission="com.abcmouse.READ"
            android:writePermission="com.abcmouse.WRITE" />

  • Remove From My Forums
  • Question

  • Hallo,

    I am new to databases.

    I have the folowing problem:

    I have a sqlite db in wich just for a test i want to insert 100000 rows. The table has a date column as primary key. I use

    date.ToFileTimeUtc(); to convert all my dates to longs. In the loop to add the 100000 rows i add 1 hour to the datetime in order to have unique dates. However after a certain amount of rows i get the error «Abort due to constraint violation PRIMARY
    KEY must be unique». If I add minutes, seconds or days i dont get this problem. I would like to understand waths going wrong so that i dont get this error later on.

    Abort due to constraint violation
    PRIMARY KEY must be unique


    Jc

Answers

  • Hi Jc,

    as ThankfulHeart trys to explain,  you can get the same hour because of the
    daylight saving, see
    Issues with the DateTime.Now() Method

    Replace DateTime.Now with DateTime.UtcNow to use an UTC time from the beginning, that avoids overlapping times.

    BTW: To avoid other errors like conversions you should define the parameter types according to the table. An example for a «Table1»:

            private void InsertTable()
            {
                using (var connection = new SQLiteConnection(Properties.Settings.Default.SQLiteConnectionString))
                {
                    connection.Open();
    
                    // Cleanup old values
                    var deleteCommand = new SQLiteCommand("DELETE FROM Table1;", connection);
                    deleteCommand.ExecuteNonQuery();
    
                    using (var transaction = connection.BeginTransaction())
                    {
                        var insertCommand = new SQLiteCommand("INSERT INTO Table1(Date, Score, Score2, Score3) VALUES(@Date, @Score, @Score2, @Score3);", connection);
                        insertCommand.Transaction = transaction;
    
                        var dateParameter = insertCommand.Parameters.Add("@Date", DbType.Int64);
                        var scoreParameter = insertCommand.Parameters.Add("@Score", DbType.Int32);
                        var score2Parameter = insertCommand.Parameters.Add("@Score2", DbType.Int32);
                        var score3Parameter = insertCommand.Parameters.Add("@Score3", DbType.Int32);
    
                        // using UTC date
                        DateTime hh = DateTime.UtcNow;
    
                        for (var i = 0; i < 100000; i++)
                        {
                            hh = hh.AddHours(1);
    
                            dateParameter.Value = getLongFromDateTimeUtc(hh);
                            scoreParameter.Value = i;
                            score2Parameter.Value = 1000000 - i;
                            score3Parameter.Value = 0;
                            insertCommand.ExecuteNonQuery();
                        }
    
                        transaction.Commit();
                    }
    
                    var countCommand = new SQLiteCommand(
                        "SELECT COUNT(*) AS RowCount FROM Table1;",
                        connection);
                    var count = (long)countCommand.ExecuteScalar();
                    Console.WriteLine("Rowcount: {0}", count);
                }
            }
    
            private long getLongFromDateTimeUtc(DateTime date)
            {
                return date.ToFileTimeUtc();
            }

    Regards, Elmar

    • Edited by

      Wednesday, November 6, 2013 11:00 AM
      Format

    • Marked as answer by
      bochelie
      Wednesday, November 6, 2013 11:49 AM
    • Unmarked as answer by
      bochelie
      Friday, November 8, 2013 10:02 AM
    • Marked as answer by
      bochelie
      Friday, November 8, 2013 2:03 PM

See more:

Abort due to constraint violation PRIMARY KEY must be unique, any one tell me what error this…..

private void tsbtnEdit_Click(object sender, EventArgs e)
        {
            try
            {
                frmAddEditEvents obj = new frmAddEditEvents();
                obj.ShowDialog();
                    SQLiteConnection connection = new SQLiteConnection(connectionString);
                    if (grdEvents.Rows.Count > 1 && grdEvents.SelectedRows[0].Index != grdEvents.Rows.Count - 0)
                    {
                        delcmd.CommandText = "UPDATE AddEvent SET ID=" + grdEvents.SelectedRows[0].Cells[0].Value.ToString()+ "";
                        connection.Open();
                        delcmd.Connection = connection;
                        delcmd.ExecuteNonQuery();
                        connection.Close();  

                        grdEvents.Update();
                        MessageBox.Show("Row updated");
                    }
                else
                {
                    MessageBox.Show("Please select any record to update");
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


Dear you are trying to update the ID field which you had defined Primary Key in you table structure. Primary key is always a unique and not supposed to insert a duplicate key and you are forcefully trying to update through a data which is already defined as a primary key.

Following is wrong.

delcmd.CommandText = "UPDATE AddEvent SET ID=" + grdEvents.SelectedRows[0].Cells[0].Value.ToString()+ "";

Thanks
Ashish

Hi darshan_ur,

The problem you stated above explains that you’re trying to insert a duplicate value in the column which has a constraint of being Primary Key.

Check the value which you’re passing to insert as ID, it must not be a duplicate n that’s all.

Hope this helps.

Happy Coding :)

If it is the problem with the Id column you can use Auto generated column I guess.
And I don think that you can update a primary key column with the same Data which is already in the database column

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900

I am combining various db (sqlite ) there is a chance from time to time that they may have the same incident number (unique Identifier) how can I deal with this in my DB(sqlite) ? or python coding ?

Traceback (most recent call last):
  File "C:Python26signgetting_it_work.py", line 22, in <module>
    Provider_1,Provider_2,Sys,Dia,Pulse,Resp,Weather, Temp,Humid,Wind,TimeStamp))
sqlite3.IntegrityError: PRIMARY KEY must be unique

Open in new window

import csv
import sqlite3 as lite

fname="recieved_data.txt"
f = open(fname, 'rb')
print f
# notice the binary mode again
reader = csv.reader(f)
for row in reader:    
    (Incident_number,Last_Name,First_Name,Age,Gender,Address,City,State,Zip,Ailment,Treatment,Patient_reprt,Initial_contact,Hospital, 
    Destination,Inservice,Provider_1,Provider_2,Sys,Dia,Pulse,Resp,Weather,Temp,Humid,Wind,TimeStamp) =row
    print row
    #print name
    Age = int(Age)
    Incident_number=int(Incident_number)	# convert to a number
	
    con = lite.connect('specialeventms.sqlite')
    cur = con.cursor()
    cur.execute('insert into ptrecords values(?,?,?,?,?,?,?,?,?,?,?, ?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0)',
                (Incident_number, Last_Name, First_Name, Age,Gender,Address,City,State,Zip
                 ,Ailment,Treatment,Patient_reprt,Initial_contact,Hospital,Destination,Inservice,
                 Provider_1,Provider_2,Sys,Dia,Pulse,Resp,Weather, Temp,Humid,Wind,TimeStamp))
    #cur.execute('insert into neighbours values(?, ?, ?)', (name, age, remark))
    con.commit()
    cur.close()
    con.close()
    
f.close()

Open in new window

I’m updated Drupal 7.10 to 7.12 with SQLite database, and error message:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 19 PRIMARY KEY must be unique: UPDATE {sequences} SET value = GREATEST(value, :existing_id) + 1; Array ( [:existing_id] => 0 ) in db_next_id()

Update is not success.

Tag1 supports the Drupal Project.Tag1 logo

Comments

chx’s picture

Comment #1

chx CreditAttribution: chx commented 2 February 2012 at 11:43

Title: SQLite update fail: 7.10 -> 7.12 » SQLite GREATEST is broken
Version: 7.12 » 8.x-dev
Component: database update system » database system
Priority: Normal » Critical
  • Log in or register to post comments

lotyrin’s picture

I’m with chx in #1. I can’t imagine that loop is acting as intended there.

I don’t have an SQLite install to run tests against, but here’s a patch.

  • Log in or register to post comments

chx’s picture

Comment #5

chx CreditAttribution: chx commented 9 February 2012 at 18:53

Priority: Critical » Normal
Status: Needs review » Needs work

Actually Damien said that if any of the arguments of GREATEST is NULL the result is NULL which makes sense — if you compare any ways anything to NULL the result will be NULL. So, 1, 2, NULL, compare 2 to NULL is NULL, then 1 to NULL, NULL. See. So the loop actually is correct.

  • Log in or register to post comments

lotyrin’s picture

File Size
1425794-6-simplify-sqlite-greatest.patch 693 bytes

FAILED: [[SimpleTest]]: [MySQL] Unable to apply patch 1425794-6-simplify-sqlite-greatest.patch. Unable to apply patch. See the log in the details link for more information. View

Hmm. That is the SQL GREATEST behavior. But, doing it as implemented spits out a notice:

PHP Notice: Undefined variable: args in /home/ubuntu/drupal/core/includes/database/sqlite/database.inc on line 165

because $args got unset. Also, the way it flows makes this behavior seem like an error rather than intended. I’m changing this to an early return and adding a comment. This change also simplifies the logic.

Probably doesn’t fix the issue here though, so leaving as needs work.

  • Log in or register to post comments

chx’s picture

Comment #7

chx CreditAttribution: chx commented 11 February 2012 at 18:25

Comment — good idea. Simplification — even better idea. What about

return array_search($args, NULL) === FALSE ? max($args) : NULL;
  • Log in or register to post comments

Damien Tournoud’s picture

The search needs to be strict:

return array_search($args, NULL, TRUE) === FALSE ? max($args) : NULL;

That said, in_array() would be a tad more self-documenting:

return !in_array(NULL, $args, TRUE) ? max($args) : NULL;
  • Log in or register to post comments

lotyrin’s picture

File Size
1425794-9-simplify-sqlite-greatest-more.patch 728 bytes

FAILED: [[SimpleTest]]: [MySQL] Unable to apply patch 1425794-9-simplify-sqlite-greatest-more.patch. Unable to apply patch. See the log in the details link for more information. View

Implemented second suggestion from #8, as well as decided that less verbose code means more verbose comment.

  • Log in or register to post comments

lotyrin’s picture

Title: SQLite GREATEST is broken » SQLite upgrade breaks
Version: 8.x-dev » 7.x-dev
Component: database system » database update system
Assigned: Unassigned » lotyrin
Priority: Normal » Major

Going to see if I can reproduce and solve the actual issue here, since the ambiguous code this patch fixes doesn’t seem to be the cause.

  • Log in or register to post comments

marcingy’s picture

Version: 7.x-dev » 8.x-dev
Priority: Major » Normal

patch needs to be against d8 and as per #7 this should be normal.

  • Log in or register to post comments

marcingy’s picture

  • Log in or register to post comments

marcingy’s picture

  • Log in or register to post comments

lotyrin’s picture

Status: Needs work » Postponed (maintainer needs more info)

nevergone, do you have a minimal case which reproduces this? I’ve done the following:

  • Install Apache and PHP (5.3.6) with sqlite + PDO
  • Install Drush (4.4)
  • Check Drupal 7.10 out from git
  • Run drush site-install.
  • Verify the site is up and working.
  • Check Drupal 7.12 out from git
  • Run drush updatedb
  • Update completes successfully

I’ll be trying other things (creating content types, enabling more core modules), but so far I’m unable to reproduce.

  • Log in or register to post comments

lotyrin’s picture

Nothing to go on here, unassigning.

  • Log in or register to post comments

geek-merlin’s picture

Comment #16

geek-merlin

Primary language German

Location Freiburg, Germany

CreditAttribution: geek-merlin commented 6 June 2012 at 17:10

«hint»: i have had good «success» seeing this error when enabling modules.

  • Log in or register to post comments

geek-merlin’s picture

Comment #17

geek-merlin

Primary language German

Location Freiburg, Germany

CreditAttribution: geek-merlin commented 6 June 2012 at 19:30

Title: SQLite upgrade breaks » SQLite exception «primary key must be unique» when sequences table erroneously contains more than one row

OK, hunted this down, it’s all about db_next_id() and the sequences table (which contains ony one unique row «value»)
look at #2! in our case the sequences table contains 2 entries (which i think should normally never happen).
of course sqlite update will freak out when next_id() sais:

update sequences set value=123;

as it is told to update *all* rows to the same value.

inserting «on conflict replace» here should do the trick.

  • Log in or register to post comments

geek-merlin’s picture

Comment #18

geek-merlin

Primary language German

Location Freiburg, Germany

CreditAttribution: geek-merlin commented 6 June 2012 at 19:32

so let’s feed the bot with a test case that should fail.

  • Log in or register to post comments

geek-merlin’s picture

Comment #19

geek-merlin

Primary language German

Location Freiburg, Germany

CreditAttribution: geek-merlin commented 6 June 2012 at 19:33

Status: Postponed (maintainer needs more info) » Needs review
  • Log in or register to post comments

geek-merlin’s picture

Comment #21

geek-merlin

Primary language German

Location Freiburg, Germany

CreditAttribution: geek-merlin commented 6 June 2012 at 19:50

upsala, forgot to change method name, so here’s the stuff.

  • Log in or register to post comments

geek-merlin’s picture

Comment #22

geek-merlin

Primary language German

Location Freiburg, Germany

CreditAttribution: geek-merlin commented 6 June 2012 at 19:57

and — in case this all works — here’s the straight d7 backport.

  • Log in or register to post comments

lotyrin’s picture

Won’t on conflict replace mean that we’ve gotten the same value twice (once when the duplicate entry was created, once when we get and resolve the conflict)?

Is it unavoidable that the duplicate sequence entry gets created on SQLite? Should we try to prevent that from happening somehow?

Other than that this seems good, we’ll see what the bots say.

It (rightfully) doesn’t include the changes from my patch, that should become a separate issue.

  • Log in or register to post comments

geek-merlin’s picture

Comment #24

geek-merlin

Primary language German

Location Freiburg, Germany

CreditAttribution: geek-merlin commented 6 June 2012 at 20:02

Status: Needs review » Needs work

what? i must have been lacking sleep when first testing the sql…

hold on and sorry folks and bot for all that noise.

  • Log in or register to post comments
Status: Needs review » Needs work

The last submitted patch, 0001-D7-backport-of-1425794-SQLite-exception-primary-key-.patch, failed testing.

  • Log in or register to post comments

geek-merlin’s picture

Comment #27

geek-merlin

Primary language German

Location Freiburg, Germany

CreditAttribution: geek-merlin commented 8 June 2012 at 15:35

to interpret this:
* d7 patch MUST fail
the other patches must be tested in a sqlite environment
the tests in my d7 environment do what they should (fail unpatched, pass patched)
as soon as i can i will set up a d8 sqlite environment and run tests locally.

  • Log in or register to post comments
  • Log in or register to post comments
  • Log in or register to post comments
Version: 8.1.x-dev » 8.2.x-dev

Drupal 8.1.9 was released on September 7 and is the final bugfix release for the Drupal 8.1.x series. Drupal 8.1.x will not receive any further development aside from security fixes. Drupal 8.2.0-rc1 is now available and sites should prepare to upgrade to 8.2.0.

Bug reports should be targeted against the 8.2.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.3.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

  • Log in or register to post comments
Version: 8.2.x-dev » 8.3.x-dev

Drupal 8.2.6 was released on February 1, 2017 and is the final full bugfix release for the Drupal 8.2.x series. Drupal 8.2.x will not receive any further development aside from critical and security fixes. Sites should prepare to update to 8.3.0 on April 5, 2017. (Drupal 8.3.0-alpha1 is available for testing.)

Bug reports should be targeted against the 8.3.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.4.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

  • Log in or register to post comments
Version: 8.3.x-dev » 8.4.x-dev

Drupal 8.3.6 was released on August 2, 2017 and is the final full bugfix release for the Drupal 8.3.x series. Drupal 8.3.x will not receive any further development aside from critical and security fixes. Sites should prepare to update to 8.4.0 on October 4, 2017. (Drupal 8.4.0-alpha1 is available for testing.)

Bug reports should be targeted against the 8.4.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.5.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

  • Log in or register to post comments
Version: 8.4.x-dev » 8.5.x-dev

Drupal 8.4.4 was released on January 3, 2018 and is the final full bugfix release for the Drupal 8.4.x series. Drupal 8.4.x will not receive any further development aside from critical and security fixes. Sites should prepare to update to 8.5.0 on March 7, 2018. (Drupal 8.5.0-alpha1 is available for testing.)

Bug reports should be targeted against the 8.5.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.6.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

  • Log in or register to post comments
Version: 8.5.x-dev » 8.6.x-dev

Drupal 8.5.6 was released on August 1, 2018 and is the final bugfix release for the Drupal 8.5.x series. Drupal 8.5.x will not receive any further development aside from security fixes. Sites should prepare to update to 8.6.0 on September 5, 2018. (Drupal 8.6.0-rc1 is available for testing.)

Bug reports should be targeted against the 8.6.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.7.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

  • Log in or register to post comments

mradcliffe’s picture

Tagging because the issue summary references Drupal 7, but we want to apply the fix to Drupal 9 first.

  • Log in or register to post comments

Понравилась статья? Поделить с друзьями:
  • Ошибка previous launch was unsuccessful would you like to
  • Ошибка press the restart key
  • Ошибка press f1 to run setup
  • Ошибка press ctrl alt del to restart как исправить
  • Ошибка press any key to reboot