Get last inserted record ID

@param string $table Table name (to find the incremented sequence)

@return mixed ID or false on failure
504266
public function insert_id($table = null)
    {
        if (!$this->db_connected || $this->db_mode == 'r' || empty($table)) {
            return false;
        }

        $sequence = $this->quote_identifier($this->sequence_name($table));
        $result   = $this->query("SELECT $sequence.currval FROM dual");
        $result   = $this->fetch_array($result);

        return $result[0] ?: false;
    }
796066
public function getPrimaryKeyDDL(Table $table)
    {
        if ($table->hasPrimaryKey()) {

            $keys = $table->getPrimaryKey();

            //MySQL throws an 'Incorrect table definition; there can be only one auto column and it must be defined as a key'
            //if the primary key consists of multiple columns and if the first is not the autoIncrement one. So
            //this push the autoIncrement column to the first position if its not already.
            $autoIncrement = $table->getAutoIncrementPrimaryKey();
            if ($autoIncrement && $keys[0] != $autoIncrement) {
                $idx = array_search($autoIncrement, $keys);
                if ($idx !== false) {
                    unset($keys[$idx]);
                    array_unshift($keys, $autoIncrement);
                }
            }

            return 'PRIMARY KEY (' . $this->getColumnListDDL($keys) . ')';
        }
    }
320636
public function insert_id($table = '')
    {
        if (!$this->db_connected || $this->db_mode == 'r') {
            return false;
        }

        if ($table) {
            // resolve table name
            $table = $this->table_name($table);
        }

        $id = $this->dbh->lastInsertId($table);

        return $id;
    }
26438
public static function getLastId($table, $field) {

        try {
            $sql = 'SELECT max(' . $field . ') as lastid FROM ' . $table;
            list($lastid) = self::dbFetch(self::query($sql), "num"); // cause warning when use assoc array
            return (int) $lastid;
        } catch (Exception $e) {
            echo $e->getTraceAsString();
        }        
    }
176994
public function getLastInsertId()
    {
        try {
            $lastInsertId = $this->getConnection()->lastInsertId();
        } catch (DBALException $exception) {
            $exception = $this->convertException($exception);
            $this->handleException($exception);
        } catch (PDOException $exception) {
            $exception = $this->convertException($exception);
            $this->handleException($exception);
        }

        return $lastInsertId;
    }
1163988
public function getNextId()
    {
        $sql   = 'UPDATE ' . $this->table . ' SET value = LAST_INSERT_ID(value + 1) WHERE name = ?';

        $result   = $this->db->query($sql, array($this->name));
        $rowCount = $result->rowCount();

        if (1 !== $rowCount) {
            throw new Exception("Sequence '" . $this->name . "' not found.");
        }

        $createdId = $this->db->lastInsertId();

        return (int) $createdId;
    }
1034336
public function getIdentityField(Table $table)
    {
        $fields = $table->getFields()->filter(function (Field $field) {
            return $field->isAutoIncrement() || $field->isIdentity() || $field->isPrimaryKey();
        });
        
        return $fields->exists() ? current($fields->toArray()) : null;
    }
636877
public function generateNewId($table)
    {
        if (!isset($this->idCounterByTable[$table])) {
            $this->idCounterByTable[$table] = $this->getSQLBuilder()->select($table)->field('id')->orderDesc('id')->limit(0, 1)->fetchResult();
        }

        for ($i = 0; $i < 50; $i++) {
            $this->idCounterByTable[$table]++;

            if ($this->getCache()) {
                $key = 'grace_id_gen_' . $table . '_' . strval($this->idCounterByTable[$table]);

                $isBusy = $this->getCache()->get($key);
                if ($isBusy === null) {
                    $this->getCache()->set($key, '1', 60);
                    return $this->idCounterByTable[$table];
                }
            } else {
                return $this->idCounterByTable[$table];
            }
        }

        throw new \OutOfBoundsException('Maximum number of cycles to generate new id has reached');
    }
654823
public function getLastInsertedId($column = null)
    {
        if (is_string($column)) {
            return $this->getConnection()->lastInsertId($column);
        }

        return $this->getConnection()->lastInsertId();
    }
1344530
public function getPrimaryKeyDDL(Table $table)
    {
        if ($table->hasPrimaryKey() && !$table->hasAutoIncrementPrimaryKey()) {
            return 'PRIMARY KEY (' . $this->getColumnListDDL($table->getPrimaryKey()) . ')';
        }

        return '';
    }
296521
protected function fetchIndexesDb($table = '') {
        $stm = $this->get(
            new Identifier('information_schema', 'STATISTICS'),
            [
                'TABLE_SCHEMA' => $this->getDbName(),
                'TABLE_NAME' => $this->prefixTable($table, false)
            ],
            [
                'columns' => [
                    'INDEX_NAME',
                    'COLUMN_NAME',
                    'NON_UNIQUE'
                ],
                'order' => ['INDEX_NAME', 'SEQ_IN_INDEX']
            ]
        );
        $indexRows = $stm->fetchAll(PDO::FETCH_ASSOC | PDO::FETCH_GROUP);

        $indexes = [];
        foreach ($indexRows as $indexName => $columns) {
            $index = [
                'type' => null,
                'columns' => array_column($columns, 'COLUMN_NAME'),
                'name' => $indexName
            ];

            if ($indexName === 'PRIMARY') {
                $index['type'] = Db::INDEX_PK;
            } else {
                $index['type'] = $columns[0]['NON_UNIQUE'] ? Db::INDEX_IX : Db::INDEX_UNIQUE;
            }
            $indexes[] = $index;
        }

        return $indexes;
    }
542820
public function getLastInsertId()
    {
        $connection = $this->getConnection();
        $id = $connection->lastInsertId();
        if ($id < 1) {
            $fullTableName = $this->tableName;
            $fullUniqueIdName = $connection->quoteIdentifier($this->getUniqueId());
            $sql = /** @lang PostgreSQL */
                "SELECT $fullUniqueIdName 
                 FROM $fullTableName
                 LIMIT 1 
                 OFFSET (SELECT count($fullUniqueIdName)-1 FROM $fullTableName )";

            $id = $connection->fetchColumn($sql);
        }
        return $id;
    }
1095254
final public function fetchTableDef(string $table) {
        $tableKey = strtolower($table);

        // First check the table cache.
        if (isset($this->tables[$tableKey])) {
            $tableDef = $this->tables[$tableKey];

            if (isset($tableDef['columns'], $tableDef['indexes'])) {
                return $tableDef;
            }
        } elseif ($this->tableNames !== null && !isset($this->tableNames[$tableKey])) {
            return null;
        }

        $tableDef = $this->fetchTableDefDb($table);
        if ($tableDef !== null) {
            $this->fixIndexes($tableDef['name'], $tableDef);
            $this->tables[$tableKey] = $tableDef;
        }

        return $tableDef;
    }
508086
public function getTableName($table) {
        if (preg_match('#^`?\{[^\}]+\}.*$#', $table)) {
            return $this->sanitize(str_replace(['{', '}'], [$this->tablePrefix, ''], $table));
        } else {
            return $this->sanitize($table);
        }
    }
682895
public function getTableSequences($table)
	{
		$this->connect();

		// To check if table exists and prevent SQL injection
		$tableList = $this->getTableList();

		if (\in_array($table, $tableList, true))
		{
			$name = array('s.relname', 'n.nspname', 't.relname', 'a.attname', 'info.data_type',
				'info.minimum_value', 'info.maximum_value', 'info.increment', 'info.cycle_option',
			);
			$as = array('sequence', 'schema', 'table', 'column', 'data_type',
				'minimum_value', 'maximum_value', 'increment', 'cycle_option',
			);

			if (version_compare($this->getVersion(), '9.1.0') >= 0)
			{
				$name[] .= 'info.start_value';
				$as[] .= 'start_value';
			}

			// Get the details columns information.
			$query = $this->getQuery(true);
			$query->select($this->quoteName($name, $as))
				->from('pg_class AS s')
				->leftJoin("pg_depend d ON d.objid=s.oid AND d.classid='pg_class'::regclass AND d.refclassid='pg_class'::regclass")
				->leftJoin('pg_class t ON t.oid=d.refobjid')
				->leftJoin('pg_namespace n ON n.oid=t.relnamespace')
				->leftJoin('pg_attribute a ON a.attrelid=t.oid AND a.attnum=d.refobjsubid')
				->leftJoin('information_schema.sequences AS info ON info.sequence_name=s.relname')
				->where("s.relkind='S' AND d.deptype='a' AND t.relname=" . $this->quote($table));
			$this->setQuery($query);

			return $this->loadObjectList();
		}

		return false;
	}
996106
public function getIndexes($table): ?array
	{
		return $this->driverQuery($this->getSql()->indexList($this->prefixTable($table)), FALSE);
	}
677831
public function getTableKeys($table)
	{
		$this->connect();

		// To check if table exists and prevent SQL injection
		$tableList = $this->getTableList();

		if (\in_array($table, $tableList, true))
		{
			// Get the details columns information.
			$this->setQuery('
				SELECT indexname AS "idxName", indisprimary AS "isPrimary", indisunique  AS "isUnique",
					CASE WHEN indisprimary = true THEN
						( SELECT \'ALTER TABLE \' || tablename || \' ADD \' || pg_catalog.pg_get_constraintdef(const.oid, true)
							FROM pg_constraint AS const WHERE const.conname= pgClassFirst.relname )
					ELSE pg_catalog.pg_get_indexdef(indexrelid, 0, true)
					END AS "Query"
				FROM pg_indexes
				LEFT JOIN pg_class AS pgClassFirst ON indexname=pgClassFirst.relname
				LEFT JOIN pg_index AS pgIndex ON pgClassFirst.oid=pgIndex.indexrelid
				WHERE tablename=' . $this->quote($table) . ' ORDER BY indkey'
			);

			return $this->loadObjectList();
		}

		return false;
	}