Created
August 28, 2025 17:30
-
-
Save mohessaid/90be3fc172f4b317de06198f926c88af to your computer and use it in GitHub Desktop.
Instant DB set default value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const getDefaultValue = (type) => { | |
| const defaults = { | |
| 'date': () => new Date().toISOString(), | |
| 'string': '', | |
| 'number': 0, | |
| 'boolean': false, | |
| 'json': {}, | |
| 'any': null, | |
| }; | |
| return typeof defaults[type] === 'function' ? defaults[type]() : defaults[type]; | |
| }; | |
| // Configuration | |
| const ENTITY_NAME = 'users'; | |
| const PAGE_SIZE = 100; | |
| // Define the new fields you want to add with their types and update criteria | |
| const NEW_FIELDS = [ | |
| { | |
| name: 'first_time', | |
| type: 'boolean', | |
| shouldUpdate: (row) => !row.first_time // Only update if field is missing/null | |
| }, | |
| ]; | |
| // Update entity function | |
| const updateEntity = async (entity, rows, fieldsToUpdate) => { | |
| const batch = []; | |
| for (const row of rows) { | |
| const updateData = {}; | |
| let needsUpdate = false; | |
| // Check each field and add to update if criteria is met | |
| for (const field of fieldsToUpdate) { | |
| const shouldUpdate = field.shouldUpdate ? field.shouldUpdate(row) : true; | |
| if (shouldUpdate) { | |
| updateData[field.name] = getDefaultValue(field.type); | |
| needsUpdate = true; | |
| } | |
| } | |
| // Only add to batch if there's something to update | |
| if (needsUpdate) { | |
| console.log(`Updating ${entity} ${row.id} with:`, updateData); | |
| batch.push( | |
| db.tx[entity][row.id].update(updateData) | |
| ); | |
| } | |
| } | |
| // Execute batch update if there are items to update | |
| if (batch.length > 0) { | |
| try { | |
| await db.transact(batch); | |
| console.log(`Successfully updated ${batch.length} ${entity} records`); | |
| return batch.length; | |
| } catch (error) { | |
| console.error(`Error updating ${entity} records:`, error); | |
| throw error; | |
| } | |
| } else { | |
| console.log(`No ${entity} records needed updating in this batch`); | |
| return 0; | |
| } | |
| }; | |
| // Main function to paginate and update | |
| const setDefaultValues = async () => { | |
| let pageNumber = 0; | |
| let hasData = true; | |
| let totalProcessed = 0; | |
| let totalUpdated = 0; | |
| console.log(`Starting default value update for ${ENTITY_NAME}...`); | |
| console.log(`Fields to process:`, NEW_FIELDS.map(f => f.name)); | |
| do { | |
| // Get all fields we need to check, plus id | |
| const fieldsToQuery = ['id', ...NEW_FIELDS.map(f => f.name)]; | |
| const query = { | |
| [ENTITY_NAME]: { | |
| $: { | |
| fields: fieldsToQuery, | |
| limit: PAGE_SIZE, | |
| offset: pageNumber * PAGE_SIZE | |
| } | |
| } | |
| }; | |
| console.log(`\nProcessing batch ${pageNumber + 1} (offset: ${pageNumber * PAGE_SIZE})...`); | |
| try { | |
| // Query the database | |
| let result; | |
| do { | |
| result = await db.query(query); | |
| } while (result.isLoading); | |
| if (result.error) { | |
| console.error("Query error:", result.error); | |
| break; | |
| } | |
| const rows = result?.[ENTITY_NAME] || []; | |
| console.log(`Found ${rows.length} ${ENTITY_NAME} records in batch ${pageNumber + 1}`); | |
| hasData = rows.length > 0; | |
| if (hasData) { | |
| // Update the entities in this batch | |
| const batchUpdateCount = await updateEntity(ENTITY_NAME, rows, NEW_FIELDS); | |
| totalUpdated += batchUpdateCount; | |
| totalProcessed += rows.length; | |
| console.log(`Batch ${pageNumber + 1} complete. Processed: ${rows.length}, Updated: ${batchUpdateCount}`); | |
| pageNumber++; | |
| // Optional: Add a small delay to avoid overwhelming the database | |
| await new Promise(resolve => setTimeout(resolve, 100)); | |
| } | |
| } catch (error) { | |
| console.error(`Error processing batch ${pageNumber + 1}:`, error); | |
| break; | |
| } | |
| } while (hasData); | |
| console.log(`\n✅ Default value update complete!`); | |
| console.log(`Total records processed: ${totalProcessed}`); | |
| console.log(`Total records updated: ${totalUpdated}`); | |
| }; | |
| // Run the update | |
| setDefaultValues().catch(console.error); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment