sidorares/node-mysql2 · error · Error

"database" connection config property must be a string

Error message

"database" connection config property must be a string

What it means

ChangeUser.toPacket (lib/packets/change_user.js:88-90) requires the database field to be a string before serializing it null-terminated into COM_CHANGE_USER. A non-string database corrupts the wire format, so the driver throws.

Solutions

  1. Coerce: database: String(opts.database || '').
  2. Validate typeof before the changeUser call.
  3. Ensure the tenant selector returns a string identifier.

Example fix

// before
connection.changeUser({ database: tenant.id }); // number

// after
connection.changeUser({ database: tenant.dbName }); // string
Defensive patterns

Strategy: validation

Validate before calling

function assertChangeUserOpts(opts) {
  if (typeof opts.database !== 'string') throw new TypeError('changeUser: database must be string');
}

Type guard

const isDatabaseString = (opts) => typeof (opts && opts.database) === 'string';

Prevention

When it happens

Trigger: connection.changeUser({ database: null }) (the constructor coerces falsy to '' but an explicit non-string truthy value reaches here); passing a number or object as database; reusing a config whose database is undefined-coerced to a non-string.

Common situations: Tenant switching with database: tenantId (number) instead of tenantId.toString(); config building that defaults database to an object on missing key.

Related errors


AI-assisted analysis of sidorares/node-mysql2@8b1f829d37 (2026-08-11). Data as JSON: /api/errors/68f7cd0c50a01d84. Report an issue: GitHub.

Appendix: source

Thrown at lib/packets/change_user.js:89

      }
      packet.writeLengthCodedNumber(keysLength);
      for (let k = 0; k < attrNames.length; ++k) {
        packet.writeLengthCodedString(attrNames[k], encoding);
        packet.writeLengthCodedString(
          connectAttributes[attrNames[k]],
          encoding
        );
      }
    }
    return packet;
  }

  toPacket() {
    if (typeof this.user !== 'string') {
      throw new Error('"user" connection config property must be a string');
    }
    if (typeof this.database !== 'string') {
      throw new Error('"database" connection config property must be a string');
    }
    // dry run: calculate resulting packet length
    const p = this.serializeToBuffer(Packet.MockBuffer());
    return this.serializeToBuffer(Buffer.allocUnsafe(p.offset));
  }
}

module.exports = ChangeUser;

View on GitHub (pinned to 8b1f829d37)