MySQL Shell API 8.4.3
Unified development interface for MySQL Products
Methods | List of all members
Table Class Reference

Represents a Table on an Schema, retrieved with a session created using mysqlx module. More...

Methods

TableInsert insert (...)
 Creates TableInsert object to insert new records into the table. More...
 
TableSelect select (...)
 Creates a TableSelect object to retrieve rows from the table. More...
 
TableUpdate update ()
 Creates a record update handler. More...
 
TableDelete delete ()
 Creates a record deletion handler. More...
 
Bool isView ()
 Indicates whether this Table object represents a View on the database. More...
 
Integer count ()
 Returns the number of records in the table.
 
- Methods inherited from DatabaseObject
String getName ()
 Returns the name of this database object.

Returns
The name this database object.

 
Object getSession ()
 Returns the Session object of this database object.

Returns
The Session object used to get to this object.
More...
 
Object getSchema ()
 Returns the Schema object of this database object.

Returns
The Schema object used to get to this object.
More...
 
Bool existsInDatabase ()
 Verifies if this object exists in the database.

Returns
A boolean indicating if the object still exists on the database.

 

Additional Inherited Members

- Properties inherited from DatabaseObject
String name
 The name of this database object.
 
Object session
 The Session object of this database object.
 
Object schema
 The Schema object of this database object.
 

Detailed Description

Represents a Table on an Schema, retrieved with a session created using mysqlx module.

Member Function Documentation

◆ insert()

TableInsert insert (   ...)

Creates TableInsert object to insert new records into the table.

Full Syntax

Table.insert(...)
[.values(value[, value, ...])]
.execute()

.insert(...)

Overloads
  • insert‌()
  • insert‌(columnList)
  • insert‌(column[, column, ...])
  • insert‌({column:value[, column:value, ...]})

An insert operation requires the values to be inserted, optionally the target columns can be defined.

If this function is called without any parameter, no column names will be defined yet.

The column definition can be done by three ways:

  • Passing to the function call an array with the columns names that will be used in the insertion.
  • Passing multiple parameters, each of them being a column name.
  • Passing a JSON document, using the column names as the document keys.

If the columns are defined using either an array or multiple parameters, the values must match the defined column names in order and data type.

If a JSON document was used, the operation is ready to be completed and it will insert the associated values into the corresponding columns.

If no columns are defined, insertion will succeed if the provided values match the database columns in number and data types.

.values(value[, value, ...])

Returns
This TableInsert object.

Each parameter represents the value for a column in the target table.

If the columns were defined on the insert() function, the number of values on this function must match the number of defined columns.

If no column was defined, the number of parameters must match the number of columns on the target Table.

This function is not available when the insert() is called passing a JSON object with columns and values.

Using Expressions As Values

If a mysqlx.expr(...) object is defined as a value, it will be evaluated in the server, the resulting value will be inserted into the record.

.execute()

Executes the insert operation.

See also
TableInsert

Examples

Inserting values without specifying the column names

result = table.insert().values('jack', 17, 'male').execute();
print("Affected Rows No Columns:", result.affectedItemsCount, "\n");

The column names given as a list of strings

result = table.insert(['age', 'name', 'gender']).values(21, 'john', 'male').execute();
print("Affected Rows Columns:", result.affectedItemsCount, "\n");

The column names given as a sequence of strings

var insert = table.insert('name', 'age', 'gender')
var insert = insert.values('clark', 22, 'male')
var insert = insert.values('mary', 13, 'female')
result = insert.execute()
print("Affected Rows Multiple Values:", result.affectedItemsCount, "\n");

The column names and corresponding values given as a JSON document

result = table.insert({ 'age': 14, 'name': 'jackie', 'gender': 'female' }).execute();
print("Affected Rows Document:", result.affectedItemsCount, "\n");

◆ select()

TableSelect select (   ...)

Creates a TableSelect object to retrieve rows from the table.

Full Syntax

Table.select(...)
[.where(expression)]
[.groupBy(...)[.having(condition)]]
[.orderBy(...)]
[.limit(numberOfRows)[.offset(numberOfRows)]]
[.lockShared(lockContention)|.lockExclusive(lockContention)]
<tr><td></td><td>[.bind(name, value)]</td></tr>
<tr><td></td><td>.execute()</td></tr>

.select(...)

Overloads
  • select‌()
  • select‌(columnList)
  • select‌(column[, column, ...])

Defines the columns that will be retrieved from the Table.

To define the column list either use a list object containing the column definitions or pass each column definition on a separate parameter.

If the function is called without specifying any column definition, all the columns in the table will be retrieved.

.where(expression)

If used, only those rows satisfying the expression will be retrieved.

The expression supports Parameter Binding.

.groupBy(...)

Overloads
  • groupBy‌(columnList)
  • groupBy‌(column[, column, ...]) Sets a grouping criteria for the retrieved rows.

.having(condition)

If used the TableSelect operation will only consider the records matching the established criteria.

The condition supports Parameter Binding.

.orderBy(...)

Overloads
  • orderBy‌(sortCriteriaList)
  • orderBy‌(sortCriterion[, sortCriterion, ...]) If used, the TableSelect operation will return the records sorted with the defined criteria.

Every defined sort criterion follows the format:

name [ ASC | DESC ]

ASC is used by default if the sort order is not specified.

.limit(numberOfRows)

If used, the operation will return at most numberOfRows rows.

This function can be called every time the statement is executed.

.offset(numberOfRows)

If used, the first numberOfRows records will not be included on the result.

.lockShared(lockContention)

When this function is called, the selected rows will be locked for write operations, they may be retrieved on a different session, but no updates will be allowed.

The acquired locks will be released when the current transaction is committed or rolled back.

The lockContention parameter defines the behavior of the operation if another session contains an exclusive lock to matching rows.

The lockContention can be specified using the following constants:

  • mysqlx.LockContention.DEFAULT
  • mysqlx.LockContention.NOWAIT
  • mysqlx.LockContention.SKIP_LOCKED

The lockContention can also be specified using the following string literals (no case sensitive):

  • 'DEFAULT'
  • 'NOWAIT'
  • 'SKIP_LOCKED'

If no lockContention or the default is specified, the operation will block if another session already holds an exclusive lock on matching rows until the lock is released.

If lockContention is set to NOWAIT and another session already holds an exclusive lock on matching rows, the operation will not block and an error will be generated.

If lockContention is set to SKIP_LOCKED and another session already holds an exclusive lock on matching rows, the operation will not block and will return only those rows not having an exclusive lock.

This operation only makes sense within a transaction.

.lockExclusive(lockContention)

When this function is called, the selected rows will be locked for read operations, they will not be retrievable by other session.

The acquired locks will be released when the current transaction is committed or rolled back.

The lockContention parameter defines the behavior of the operation if another session contains a lock to matching rows.

The lockContention can be specified using the following constants:

  • mysqlx.LockContention.DEFAULT
  • mysqlx.LockContention.NOWAIT
  • mysqlx.LockContention.SKIP_LOCKED

The lockContention can also be specified using the following string literals (no case sensitive):

  • 'DEFAULT'
  • 'NOWAIT'
  • 'SKIP_LOCKED'

If no lockContention or the default is specified, the operation will block if another session already holds a lock on matching rows until the lock is released.

If lockContention is set to NOWAIT and another session already holds a lock on matching rows, the operation will not block and an error will be generated.

If lockContention is set to SKIP_LOCKED and another session already holds a lock on matching rows, the operation will not block and will return only those rows not having an exclusive lock.

This operation only makes sense within a transaction.

.bind(name, value)

Binds the given value to the placeholder with the specified name.

An error will be raised if the placeholder indicated by name does not exist.

This function must be called once for each used placeholder or an error will be raised when the execute() method is called.

.execute()

Executes the select operation with all the configured options.

See also
TableSelect

Examples

Fetching all the records

var records = table.select().execute().fetchAll();
print("All:", records.length, "\n");

Fetching records matching specified criteria

var records = table.select().where('gender = "male"').execute().fetchAll();
print("Males:", records.length, "\n");
var records = table.select().where('gender = "female"').execute().fetchAll();
print("Females:", records.length, "\n");
var records = table.select().where('age = 13').execute().fetchAll();
print("13 Years:", records.length, "\n");
var records = table.select().where('age = 14').execute().fetchAll();
print("14 Years:", records.length, "\n");
var records = table.select().where('age < 17').execute().fetchAll();
print("Under 17:", records.length, "\n");
var records = table.select().where('name like "a%"').execute().fetchAll();
print("Names With A:", records.length, "\n");
var records = table.select().where('name LIKE "a%"').execute().fetchAll();
print("Names With A:", records.length, "\n");
var records = table.select().where('NOT (age = 14)').execute().fetchAll();
print("Not 14 Years:", records.length, "\n");

Selecting which columns to fetch

var result = table.select(['name', 'age']).execute();
var record = result.fetchOne();
var columns = dir(record)
print(columns)
print('1-Metadata Length:', columns.length, '\n');
print('1-Metadata Field:', columns[1], '\n');
print('1-Metadata Field:', columns[2], '\n');
var result = table.select(['age']).execute();
var record = result.fetchOne();
var columns = dir(record)
print('2-Metadata Length:', columns.length, '\n');
print('2-Metadata Field:', columns[1], '\n');

Sorting the results

var records = table.select().orderBy(['name']).execute().fetchAll();
for (index = 0; index < 7; index++) {
print('Select Asc', index, ':', records[index].name, '\n');
}
var records = table.select().orderBy(['name desc']).execute().fetchAll();
for (index = 0; index < 7; index++) {
print('Select Desc', index, ':', records[index].name, '\n');
}

Setting limit and offset

var records = table.select().limit(4).execute().fetchAll();
print('Limit-Offset 0 :', records.length, '\n');
for (index = 1; index < 8; index++) {
var records = table.select().limit(4).offset(index).execute().fetchAll();
print('Limit-Offset', index, ':', records.length, '\n');
}

Using parameter binding

var records = view.select().where('my_age = :years and my_gender = :heorshe').bind('years', 13).bind('heorshe', 'female').execute().fetchAll();
print('Select Binding Length:', records.length, '\n');
print('Select Binding Name:', records[0].my_name, '\n');

◆ update()

TableUpdate update ( )

Creates a record update handler.

Full Syntax

Table.update()
.set(attribute, value)
[.where(expression)]
[.orderBy(...)]
<tr><td></td><td>[.limit(numberOfRows)]</td></tr>
<tr><td></td><td>[.bind(name, value)]</td></tr>
<tr><td></td><td>.execute()</td></tr>

.update()

Initializes the update operation.

.set(attribute, value)

Parameters
attributeIdentifies the column to be updated by this operation.
valueDefines the value to be set on the indicated column.
Returns
This TableUpdate object.

Adds an operation into the update handler to update a column value in the records that were included on the selection filter and limit.

Using Expressions As Values

If a mysqlx.expr(...) object is defined as a value, it will be evaluated in the server, the resulting value will be set at the indicated column.

The expression also can be used for Parameter Binding.

.where(expression)

If used, only those rows satisfying the expression will be updated

The expression supports Parameter Binding.

.orderBy(...)

Overloads
  • orderBy‌(sortCriteriaList)
  • orderBy‌(sortCriterion[, sortCriterion, ...]) If used, the TableUpdate operation will update the records in the order established by the sort criteria.

Every defined sort criterion follows the format:

name [ ASC | DESC ]

ASC is used by default if the sort order is not specified.

.limit(numberOfRows)

If used, the operation will update only numberOfRows rows.

This function can be called every time the statement is executed.

.bind(name, value)

Binds the given value to the placeholder with the specified name.

An error will be raised if the placeholder indicated by name does not exist.

This function must be called once for each used placeholder or an error will be raised when the execute method is called.

.execute()

Executes the delete operation with all the configured options.

See also
TableUpdate

Examples

Updating a single field in a record

var result = table.update().set('name', 'aline').where('age = 13').execute();
print('Affected Rows:', result.affectedItemsCount, '\n');
var result = table.select().where('name = "aline"').execute();
record = result.fetchOne();
print("Updated Record:", record.name, record.age);

Updating a single field using expressions

var result = table.update().set('age', mysqlx.expr('13+10')).where('age = 13').execute();
print('Affected Rows:', result.affectedItemsCount, '\n');
var result = table.select().where('age = 23').execute();
record = result.fetchOne();
print("Updated Record:", record.name, record.age);

Updating a single field using expressions and parameter binding

var result = table.update().set('age', mysqlx.expr(':new_year')).where('age = :old_year').limit(2).bind('new_year', 16).bind('old_year', 15).execute();
print('Affected Rows:', result.affectedItemsCount, '\n');
var records = table.select().where('age = 16').execute().fetchAll();
print('With 16 Years:', records.length, '\n');
var records = table.select().where('age = 15').execute().fetchAll();
print('With 15 Years:', records.length, '\n');

Updating a view

var result = view.update().set('my_gender', 'female').execute();
print('Updated Females:', result.affectedItemsCount, '\n');
// Result gets reflected on the target table
var records = table.select().where('gender = "female"').execute().fetchAll();
print('All Females:', records.length, '\n');

◆ delete()

TableDelete delete ( )

Creates a record deletion handler.

Full Syntax

Table.delete()
[.where(expression)]
[.orderBy(...)]
<tr><td></td><td>[.limit(numberOfRows)]</td></tr>
<tr><td></td><td>[.bind(name, value)]</td></tr>
<tr><td></td><td>.execute()</td></tr>

.delete()

Initializes the deletion operation.

.where(expression)

If used, only those rows satisfying the expression will be deleted

The expression supports Parameter Binding.

.orderBy(...)

Overloads
  • orderBy‌(sortCriteriaList)
  • orderBy‌(sortCriterion[, sortCriterion, ...]) If used, the TableDelete operation will delete the records in the order established by the sort criteria.

Every defined sort criterion follows the format:

name [ ASC | DESC ]

ASC is used by default if the sort order is not specified.

.limit(numberOfRows)

If used, the operation will delete only numberOfRows rows.

This function can be called every time the statement is executed.

.bind(name, value)

Binds the given value to the placeholder with the specified name.

An error will be raised if the placeholder indicated by name does not exist.

This function must be called once for each used placeholder or an error will be raised when the execute method is called.

.execute()

Executes the delete operation with all the configured options.

See also
TableDelete

Examples

Deleting records with a condition

var result = table.delete().where('age = 15').execute();
print('Affected Rows:', result.affectedItemsCount, '\n');
var records = table.select().execute().fetchAll();
print('Records Left:', records.length, '\n');

Deleting records with a condition and parameter binding

var result = table.delete().where('gender = :heorshe').limit(2).bind('heorshe', 'male').execute();
print('Affected Rows:', result.affectedItemsCount, '\n');
var records = table.select().execute().fetchAll();
print('Records Left:', records.length, '\n');

Deleting all records using a view

var result = view.delete().execute();
print('Affected Rows:', result.affectedItemsCount, '\n');
// Deletion is of course reflected on the target table
var records = table.select().execute().fetchAll();
print('Records Left:', records.length, '\n');

Deleting records with a limit

var result = table.delete().limit(2).execute();
print('Affected Rows:', result.affectedItemsCount, '\n');
var records = table.select().execute().fetchAll();
print('Records Left:', records.length, '\n');

◆ isView()

Bool isView ( )

Indicates whether this Table object represents a View on the database.

Returns
True if the Table represents a View on the database, False if represents a Table.